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?
Related
I am trying to write excel .xls files in c# by the use of the Google Code "ExcelLibrary". I want to write lines without writing over the data that is already in the spreadsheet. Any ideas on how I can do this? If there is a better library that I should use, please let me know!
My code is shown below:
//gives us correct location to find excel file to edit
string loco = "D://PayDay//PayDay_Files//Debtors//";
loco = loco + debtorName;
//declaration of XLS File
string file = loco + "//debtor_template.xls";
Workbook wb = new Workbook();
Worksheet ws = new Worksheet("Worksheet 1");
//header of XLS
ws.Cells[0, 1] = new Cell("Debt Name");
ws.Cells[0, 2] = new Cell("Amount");
ws.Cells[0, 3] = new Cell("Date");
ws.Cells[0, 4] = new Cell("Payment Due");
ws.Cells[0, 5] = new Cell("Notes");
//data collected from form to print on xls file
ws.Cells[2, 1] = new Cell(debtName);
ws.Cells[2, 2] = new Cell(amount);
ws.Cells[2, 3] = new Cell(date);
ws.Cells[2, 4] = new Cell(paymentDue);
ws.Cells[2, 5] = new Cell(notes);
wb.Worksheets.Add(ws);
wb.Save(file);
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.
this is my first time using ExcelLibrary and I seem to have run into a little problem. I am saving a test file using the following code:
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("Sheet 1");
//Write the first row
worksheet.Cells[0, 0] = new Cell("Name");
worksheet.Cells[0, 1] = new Cell("Address");
worksheet.Cells[0, 2] = new Cell("Phone");
worksheet.Cells[0, 3] = new Cell("Fax");
worksheet.Cells[0, 4] = new Cell("E-mail");
worksheet.Cells[0, 5] = new Cell("Contact Person/s");
worksheet.Cells[0, 6] = new Cell("Domain/s of Activity");
worksheet.Cells[0, 7] = new Cell("Number of Employees");
worksheet.Cells[0, 8] = new Cell("Turnover");
workbook.Worksheets.Add(worksheet);
workbook.Save(sfd.FileName);
But when I try to open the file, I get a warning box saying it is unreadable. I am opening the file in Excel 2010 and just as a side note, I can open other .xls files just not the ones generated by the program.
What am I doing wrong?
Thanks.
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.