I am in the process of writing a module to export a DataTable to Excel using Microsoft.Office.Interop.Excel but before starting in earnest I want to get the very basics working: open file, save as, and close.
I have succeeded in opening and saving a file with the .xls extension, but saving with the .xlsx extension does not work. It writes the .xlsx file, but when I try to open it I get the following error:
Excel cannot open the file 'SomeFile.xlsx' because the file format is not valid. Verify that file has not been corrupted and that the file extension matched the format of the file.
The code I use to open, save and close the files is:
Excel.Application excelApplication = new Excel.Application();
//excelApplication.Visible = true;
//dynamic excelWorkBook = excelApplication.Workbooks.Add();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add();
//Excel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;
int rowIndex = 1; int colIndex = 1;
excelApplication.Cells[rowIndex, colIndex] = "TextField";
// This works.
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xls", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
// This does not!?
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xlsx", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excelWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
I have also tried the file format Excel.XlFileFormat.xlExcel12 in place of Excel.XlFileFormat.xlWorkbookNormal but this does not even write instead throwing the COMException:
Exception from HRESULT: 0x800A03EC
Any help resolving this would be most appreciated.
Edit: I have now also tried:
excelWorkBook.SaveAs("C:\\MyExcelTestTest", Excel.XlFileFormat.xlExcel12,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
Missing.Value is found in the System.Reflection namespace.
Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.
When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)
Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
Related
I am in the process of writing a module to export a DataTable to Excel using Microsoft.Office.Interop.Excel but before starting in earnest I want to get the very basics working: open file, save as, and close.
I have succeeded in opening and saving a file with the .xls extension, but saving with the .xlsx extension does not work. It writes the .xlsx file, but when I try to open it I get the following error:
Excel cannot open the file 'SomeFile.xlsx' because the file format is not valid. Verify that file has not been corrupted and that the file extension matched the format of the file.
The code I use to open, save and close the files is:
Excel.Application excelApplication = new Excel.Application();
//excelApplication.Visible = true;
//dynamic excelWorkBook = excelApplication.Workbooks.Add();
Excel.Workbook excelWorkBook = excelApplication.Workbooks.Add();
//Excel.Worksheet wkSheetData = excelWorkBook.ActiveSheet;
int rowIndex = 1; int colIndex = 1;
excelApplication.Cells[rowIndex, colIndex] = "TextField";
// This works.
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xls", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
// This does not!?
excelWorkBook.SaveAs("C:\\MyExcelTestTest.xlsx", Excel.XlFileFormat.xlWorkbookNormal,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excelWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
I have also tried the file format Excel.XlFileFormat.xlExcel12 in place of Excel.XlFileFormat.xlWorkbookNormal but this does not even write instead throwing the COMException:
Exception from HRESULT: 0x800A03EC
Any help resolving this would be most appreciated.
Edit: I have now also tried:
excelWorkBook.SaveAs("C:\\MyExcelTestTest", Excel.XlFileFormat.xlExcel12,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
Missing.Value is found in the System.Reflection namespace.
Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.
When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)
Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
I'm working on Excelsheet of .xls extensions with 4 Sheets in it. I'm writing xml content to all these sheets.After writing to each sheet I'm Saving and Collecting the Garbage using this method
private static void SaveAndCollecttheGarbage(Microsoft.Office.Interop.Excel.Application excelApp, string path, Microsoft.Office.Interop.Excel.Sheets sheet)
{
try
{
excelApp.Columns.AutoFit();
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(true, Missing.Value, Missing.Value);
sheet = null;
mWorkBook = null;
excelApplication.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch (Exception)
{
}
}
This is working fine for all my first 3 sheets but when coming to the my 4th sheet it is throwing an error when the cell value is --------Original------and the data goes on.....
Not enough storage is available to complete this operation. (Exception from HRESULT: 0x8007000E (E_OUTOFMEMORY))
My 4th sheet has more data (1100+ rows) than the other sheets. This is how I'm writing data to my 4th sheet
mWorkBook = excelApplication.Workbooks.Open(excelPath, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
mSheets = mWorkBook.Worksheets;
mWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)mSheets.Add();
mWorkSheet.Name = "Case History";
int l = 1, m = 1, n = 0;
mWorkSheet.Cells[1, 1] = "Id";
mWorkSheet.Cells[1, 2] = "Subject";
mWorkSheet.Cells[1, 3] = "CustomerHistory";
foreach (CaseHistory customerHistory in allCustomerHistory)
{
n = 0;
mWorkSheet.Cells[l + m, ++n] = customerHistory.id;
mWorkSheet.Cells[l + m, ++n] = customerHistory.caseSubject;
mWorkSheet.Cells[l + m, ++n] = customerHistory.caseBody;
m++;
}
I cannot find what I'm doing wrong. Isn't it possible to write huge data to excelsheet. If can do help me how to do it
I am trying to open (or create a new xls) Excel file and write some values to it. Although, the program below works just fine if I simply create a new xls file, I encounter the some problem in line
**mWorkBook = oXL.Workbooks.Open (path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);**
Here's the error:
'LOG.xls' cannot be accessed. The file may be corrupted, located on a server that is not responding, or read-only.
It's not read-only, it's not corrupted(because sometime the file is created on Run Time).
What is the problem then?
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
private void btnSignIn_Click ( object sender, EventArgs e )
{
string path = "D:\\LOG.xls";
if(!File.Exists(path))
{
File.Create (path);
}
oXL = new Microsoft.Office.Interop.Excel.Application ();
oXL.Visible = true;
oXL.DisplayAlerts = false;
//error on this line
mWorkBook = oXL.Workbooks.Open (path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item ("Sheet1");
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount = range.Rows.Count;
for ( int index = 1; index < 15; index++ )
{
mWSheet1.Cells [rowCount + index, 1] = rowCount + index;
mWSheet1.Cells [rowCount + index, 2] = "New Item" + index;
}
mWorkBook.SaveAs (path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close (Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
}
The using of File.Create is not appropriate here. It returns a (Blank) FileStream, not an Excel File (Define the path with .xls will not create an Excel File...).
And as you do not close and dispose it, you have an exception when you try to open it because it is already in use (and you will have an exception in any way even if you release it, because you have not create an Excel file at this stage).
So if the workbook exists, you can open it by using oXL.Workbooks.Open.
If the workbook does not exist, YOU HAVE to create it by using: oXL.Workbooks.Add() and then you call mWorkBook.SaveAs(...) method to really create it.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
string path = "D:\\LOG.xls";
if (!File.Exists(path))
{
mWorkBook = oXL.Workbooks.Add;
}
else
{
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
}
(Hope the VB=>C# is correct!)
And in your SaveAs method, you will have to set the correct FileFormat if you want to create a specific version of Excel file (again set .xls in the path is not enough...)
Optional Object. The file format to use when you save the file. For a
list of valid choices, see the FileFormat property. For an existing
file, the default format is the last file format specified; for a new
file, the default is the format of the version of Excel being used.
Hope this helps.
If the workbook does not exist, the better way to create one would be as such:
Excel.Workbook newWorkbook = excelApplication.Workbooks.Add();
File.Create() returns an instance of FileStream, which you need to close if you want to access the file. You can change..
if(!File.Exists(path))
{
File.Create (path);
}
to
if(!File.Exists(path))
{
File.Create (path).Close();
}
I have a Gridview which i fill with a Datatable. On the webpage the user has to be able to download an excel file with the contents of the Gridview. So mi thought the easiest way to save the files is to save the datatable as an excel file. I have troied this method, which i found here on stackoverflow.
using Excel = Microsoft.Office.Interop.Excel;
public static 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, 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.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;
}
Bu i get a build error stating that "The name Missing does not exist in the current context" and i cant seem to figure out why? can anyone help ?
the code is pasted from this stackoverflow page here
According to msdn here, Missing.Value is defined in System.Reflection. You should add a reference to this namespace.
using System.Reflection;
I want to export data from Dataset or Data Table to Excel file in C# without using Gridview.
I would recommend EPPlus - this solution doesn't require COM nor interop dlls and is very fast. Perfectly suited for web scenarios.
http://epplus.codeplex.com/
http://nuget.org/packages/EPPlus
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//Example how to Format Column 1 as numeric
using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
}
}
Get more ways : 9 Solutions to Export Data to Excel for ASP.NET
I have this code but for this you need to include Excel Com Component
Add reference of Microsoft.Office.Interop.Excel.dll in your project will do task for you.
using Excel = Microsoft.Office.Interop.Excel;
public static 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, 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.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;
}
you can use
using Microsoft.Office.Interop.Excel;
to work with excel documents "native"...
Using C# to Create an Excel Document
http://www.codeproject.com/Articles/20228/Using-C-to-Create-an-Excel-Document
But most of the common report Generator/Designers can easily export to excel
also check for Reporting Services if you are using SQL SERVER
Just in case somebody else used the chosen solution and run into the "object does not contain a definition for get_Range" exception. I found the solution here: Worksheet get_Range throws exception. I hope this will save your time.