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.
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 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"));
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";
I'm trying to insert data from a datatable to an Excel file from my web application. At the press of a button a datatable is filled and it is inserted into an Excel file. The issue is that when the data is inserted correctly and i save the file and then close it, the data disappears. And it happens when the Excel document is closed.
this is my code:
public bool ExportDataTableToExcel(DataTable dt, string filepath)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, 1] = "CustID";
oSheet.Cells[1, 2] = "Alias";
oSheet.Cells[1, 3] = "AdrID";
oSheet.Cells[1, 4] = "Truck Delivery Days";
oSheet.Cells[1, 5] = "Truck Delivery Hours";
oSheet.Cells[1, 6] = "Truck Delivery Type";
oSheet.Cells[1, 7] = "Plane Delivery Days";
oSheet.Cells[1, 8] = "Plane Delivery Hours";
oSheet.Cells[1, 9] = "Plane Delivery Type";
oSheet.Cells[1, 10] = "Other Delivery Days";
oSheet.Cells[1, 11] = "Other Delivery Hours";
oSheet.Cells[1, 12] = "Other Delivery Type";
oSheet.Cells[1, 13] = "Distance to Dealer";
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
oRange = oSheet.Range[oSheet.Cells[1, 1],oSheet.Cells[rowCount, dt.Columns.Count]];
oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
And the data disappears after this line is executed:
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
can anybody help me with this?
thanks
Interop is NOT supported in sever-scenarios (like ASP...) by MS.
There are many options to read/edit/create Excel files without Interop/installing Excel on the server:
MS provides the free OpenXML SDK V 2.0 - see http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx (XLSX only)
This can read+write MS Office files (including Excel).
Another free option see http://www.codeproject.com/KB/office/OpenXML.aspx (XLSX only)
IF you need more like handling older Excel versions (like XLS, not only XLSX), rendering, creating PDFs, formulas etc. then there are different free and commercial libraries like ClosedXML (free, XLSX only), EPPlus (free, XLSX only), Aspose.Cells, SpreadsheetGear, LibXL and Flexcel etc.