Trouble Saving an Excel file using asp.NET - c#

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.

Related

COMException was unhandled when trying to save Excel workbook

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?

"Exception from HRESULT: 0x800A03EC" creating new worksheet

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.

C# how to rename Excel Sheet using Interop

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";

Prevent Excel from opening while creating excel file using interop

Hi all am creating a excel using Microsoft office interop.and it creates files successfully.But the problem is that when it creates a files it just opens excel adds the value in to excel and saves it in the specified name.Any accidental typing at that time results leads to a exception.Am creating nearly 75 files with many rows from database and hence takes time.During the processing am unable to do any task since it creates exception if its typed in the excel.Is there any way to run the process in background so that excel application does not open for each file creation.
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
// 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 = "Sales";
// Process the DataTable
// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
DataTable dt = dtt;
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, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
//oRange = oSheet.get_Range(oSheet.Cells[1, 1],
// oSheet.Cells[rowCount, dt.Columns.Count]);
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("" + username + " .xls", 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();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
By default Excel via Interop opens as Invisible.
It's your code that change the visibility of Excel.
Remove the line
oXL.Visible = true;
or set to false
oXL.Visible = false;
Try this...
// Start Excel and get Application object. oXL = new Excel.Application {Visible = false};
OR -
// Set some properties oXL.Visible = false;

how to send paramter from c# to excel and save the data there

i have 2 issues what i am facing
i have an dataset where i need to send the data from dataset to an
excel once data in dumped in that location.
i need to change the column headers make them bold
2:
Above the report headers we should pass 1 parameter that will be the name(Employee details) from c# we need to pass as an parameter to it.
it can change what ever parameter we pass it on.
ex:
Reportname: Employee details
Name EmpID city
Arun 11 bangalore
Kiran 56 chennai
Rahul 23 pune
The following should work, but I did not test it. Thank you to Deborah Kurata for writing a large part of the code below.
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
private void ExportToExcel(DataTable Table, string ReportName, string Filename)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
// 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 = "Report";
int rowCount = 3;
foreach (DataRow dr in Table.Rows)
{
for (int i = 1; i < Table.Columns.Count+1; i++)
{
// Add the header the first time through
if (rowCount==3)
{
oSheet.Cells[1, i] = Table.Columns[i - 1].ColumnName;
rowCount++;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
rowCount++;
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[3, 1],
oSheet.Cells[rowCount, Table.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Set report title *after* we adjust column widths
oSheet.Cells[1,1] = ReportName;
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(Filename, 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();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}

Categories

Resources