I need to create an Excel spreadsheet and then I need to rename the sheets. What am I doing wrong?
Here is the code I have so far:
using System;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
public class CreateExcelWorksheet
{
static void Main()
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
oSheet.Name = "NewOne";
string filename = "C:\\" + DateTime.Now.ToString("dd_MM_yy_hhmmss");
oWB.SaveAs(filename + "asdaa" + ".xlsx");
oWB.Close();
}
}
oWB.Worksheets is where you find the sheets.
Can take them by index Worksheets[1] (or 2, or 3...)
Can take them by name Worksheets["SheetName"]
They come as object, so cast them to (Worksheet).
Worksheet oSheet = (Worksheet)oWB.Worksheets["TheSheetYouWant"];
To change name: oSheet.Name = "NewName";
Even shorter:
workbook.Worksheets[1].Name = "Sheet Name";
Related
I'm trying to create and save an Excel workbook to my desktop and so far have the following C# code:
using System
using System.Net
using Microsoft.Office.Interop.Excel;
//LAUNCH AND TEMPLATE EXCEL
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xlApp.Workbooks.Add();
Worksheet ws = (Worksheet)wb.Worksheets[1]
ws.Cells[1, 1] = "Report Date";
ws.Cells[1, 2] = "Catagories";
ws.Cells[1, 3] = "Page Name";
ws.Cells[1, 4] = "Last Revision Date";
ws.Cells[1, 5] = "Beginning Total";
ws.Cells[1, 6] = "Ending Total";
ws.Cells[1, 7] = "Monthly Total";
ws.Cells[1, 8] = "YTD";
//LAUNCH AND TEMPLATE EXCEL
wb.SaveCopyAs("C:/Users/pta72645/Desktop/TestFile5_2.xlsx"); //save Excel, **ERROR OCCURS HERE**
The error that occurs on the very last line where I try to save the workbook instance. Visual Studio says: "An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in wikiScrapeData.exe". I have looked on MSDN and other sources and have not been able to solve the issue.
How do I properly save this Excel workbook?
I actually wrote this over a month ago in preparation for a project, and I had it working. Now I get this error and cannot figure out why its being thrown. I even created a folder and checked the permissions on it. Any suggestions?
namespace E_Report
{
class Program
{
static void Main(string[] args)
{
Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Add("Report.xlsx");
Worksheet xlWorksheet = xlApp.Worksheets.Add("Sheet1"); // Exception from HRESULT: 0x800A03EC
xlWorksheet = (Worksheet)xlWorkbook.Worksheets.get_Item("Sheet1");
xlWorksheet.Cells[1, 1] = "Account Number";
xlWorksheet.Cells[1, 2] = "Amount";
xlWorksheet.Cells[1, 3] = "Code";
xlWorksheet.Cells[1, 4] = "Date";
xlWorksheet.Cells[1, 5] = "Audit";
xlWorksheet.Cells[1, 6] = "ID";
xlWorksheet.Cells[1, 7] = "Customer Name";
xlWorksheet.Cells[1, 8] = "Payment Source";
xlWorkbook.SaveAs("C:\\Temp\\Report.xlsx");
xlApp.Quit();
xlWorkbook.Close(0);
}
}
}
Thanks for any help!
With xlApp.Worksheets.Add("Sheet1") you're trying to add a new worksheet before Sheet1, it expects an existing Worksheet object (and 0x800A03EC is NAME_NOT_FOUND).
I suppose what you're trying to do is to add a new sheet named Sheet1:
Worksheet xlWorksheet = xlApp.Worksheets.Add();
xlWorksheet.Name = "Sheet1";
Now also the line xlWorksheet = (Worksheet)xlWorkbook.Worksheets.get_Item("Sheet1");
can be simply dropped.
I am writing an application to add a pivot table sheet in an existing excel workbook. Here's the code:
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
if (e.Name.StartsWith("~$"))
return;
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
oApp = new Excel.Application();
try
{
oBook = oApp.Workbooks.Open(e.FullPath);
oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//Excel.Range finalCell = oSheet.Cells[2, oSheet.Rows.Count];
Excel.Range oRange = oSheet.get_Range("A1", "M9");
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Pivot Table";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[3,1];
// create Pivot Cache and Pivot Table
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
Excel.PivotField oPivotField1 = (Excel.PivotField)oPivotTable.PivotFields("Field1");
oPivotField1.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
oPivotField1.Position = 1;
oPivotField1.Name = "Field1";
Excel.PivotField oPivotField2 = (Excel.PivotField)oPivotTable.PivotFields("Field2");
oPivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
oPivotField2.Position = 2;
oPivotField2.Name = "Field2";
oBook.Save();
Console.WriteLine("Operation Complete");
}
This is inside a FileSystemWatcher's event handler for file creation. The program runs and creates the sheet for the Pivot table, but data values are not listed and also i get two separate columns. Here's the screen
Please let me know what i'm doing wrong. Using Visual Studio 2015 and project type is Windows Form Application.
Replace the pivot cache/table creation lines:
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
with
PivotCache oPivotCache = oBook.PivotCaches().Create(XlPivotTableSourceType.xlDatabase, oRange, XlPivotTableVersionList.xlPivotTableVersion14);
PivotTable oPivotTable = oPivotCache.CreatePivotTable(TableDestination: oRange2, TableName: "Summary");
Note that you are doing a lot of redundant casting. You generally don't have to cast all those pivotCache and pivotfield variables.
I have 2 textbox i.e. textbox1,textbox2
I want to export the data from these textboxes to an excel sheet i.e. test.xlsx
using a button.
Anyone know what's the code to do that?
First, you need to add a reference to the Excel Object Library in your project.
You can than import the library to your form:
using Excel = Microsoft.Office.Interop.Excel;
You can add similar code to this:
var excelApp = new Excel.Application();
excelApp.Workbooks.Open(filePath);
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
workSheet.Cells[1, "A"] = textBox1.Text;
workSheet.Cells[1, "B"] = textBox1.Text;
You can also check this Walkthrough for an detailed explanation
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
string myPath = tbFolderpath.Text + tbFileName.Text;//User Given Path Value
FileInfo fi = new FileInfo(myPath);
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (!fi.Exists)//To Check File exist in a location,if not exist it will create new file
{
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, "A"] = "Name";
xlWorkSheet.Cells[1, "B"] = "Age";
xlWorkSheet.Cells[1, "C"] = "CurrentTime";
var columnHeadingsRange = xlWorkSheet.Range[xlWorkSheet.Cells[1, "A"],
xlWorkSheet.Cells[1, "C"]];
columnHeadingsRange.Interior.Color = Excel.XlRgbColor.rgbYellow;//To Give Header Color
xlWorkBook.SaveAs(myPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook,
misValue,misValue, misValue, misValue,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
}
//Already File Exist it will open the File and update the data into excel`enter code here`
var workbook = xlApp.Workbooks.Open(myPath);
xlWorkSheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);
int _lastRow = xlWorkSheet.Range["A" +xlWorkSheet.Rows.Count].
End[Excel.XlDirection.xlUp].Row + 1;
xlWorkSheet.Cells[_lastRow, "A"] = Textbox1.Text;
xlWorkSheet.Cells[_lastRow, "B"] = Textbox2.Text;
DateTime currentTime = DateTime.Now;//To Get the Current Time
string formattedTime = currentTime.ToString("dd/MM/yyyy-hh:mm:ss");
xlWorkSheet.Cells[_lastRow, "C"] = formattedTime;
workbook.Save();
workbook.Close();
xlApp.Quit();
First i apologize for the mistakes in my text, english is not my native language and i do my best.
I'm a very beginner in coding and i have a little question about loading an excel sheet.
I'm trying to do a project with vb in c# and i have to load an excel sheet which already exist and write in it. I found some explanations who help me to create a New sheet and write in it :
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
oXL = new Excel.Application("Exemple.xlsx");
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[4, 0] = "Adam";
saNames[4, 1] = "Johnson";
oSheet.get_Range("A2", "B6").Value2 = saNames;
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
The things i write don't really matter but i can't load my own sheet. I tought by replacing
oXL = new Excel.Application();
by
oXL = new Excel.Application("Exemple.xlsx");
I could load my sheet ( call Exemple.xlsx)
Unfortunately it don't work, could you tell me what's wrong?
Thanks!
Once you have your reference to Excel, you must call the Workbooks.Open method to open an existing file:
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Open("Example.xlsx"));