I don't get the error that appears in my export to excel code. I have this error
Unable to cast COM object of type 'System.__ComObject' to interface
type 'Microsoft.Office.Interop.Excel.Range'. This operation failed
because the QueryInterface call on the COM component for the interface
with IID '{00020846-0000-0000-C000-000000000046}' failed due to the
following error: No such interface supported (Exception from HRESULT:
0x80004002 (E_NOINTERFACE)).
Here is the code in my gridview, my gridview's name is dgvCommission.
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_elapsed);
timer.Start();
Invoke(new MyDelegate(ShowLabel), "Loading...");
BACS.DateFrom = this.dtFrom.Value.ToShortDateString(); //this.dtFrom.Text;
BACS.DateTo = this.dtTo.Value.ToShortDateString(); //this.dtTo.Text;
BACS.BrokerAgent = BrokerXML;
BACS.Payor = PayorXML;
DS = BACS.GET_SP_BACS_ComputeCommission();
ReadData(DS, this.dgvCommision);
CheckGrid();
Thread.Sleep(1);
timer.Stop();
}
catch
{ }
}
And here is my export to excel code in my form.
private void ExportToExcel()
{
string[] arrays = new string[19];
arrays[0] = "Type";
arrays[1] = "Broker Agent";
arrays[2] = "Payor";
arrays[3] = "Billing #";
arrays[4] = "OR No.";
arrays[5] = "OR Date";
arrays[6] = "Particulars";
arrays[7] = "Mode";
arrays[8] = "Amount Billed";
arrays[9] = "Amount Paid";
arrays[10] = "Non Comm Items";
arrays[11] = "Net";
arrays[12] = "Output VAT";
arrays[13] = "Commissionable Amount";
arrays[14] = "WTAX Rate";
arrays[15] = "WTAX";
arrays[16] = "Net Commission";
arrays[17] = "InputVAT";
arrays[18] = "For Fund Release";
SystemUtil.ExportToExel(DS, arrays);
}
ExportToExcel class code is this:
public void ExportToExel(DataSet ds,string[] arrays)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
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 = "EXCEL";
DataTable dt2 = new DataTable();
if (ds.Tables[0] != null)
{
dt2 = ds.Tables[0];
}
int rowCount = 1;
foreach (DataRow dr in dt2.Rows)
{
rowCount += 1;
for (int i = 1; i < dt2.Columns.Count + 1; i++)
{
if (rowCount == 2)
{
oSheet.Cells[1, i] = arrays[i - 1];// dt.Columns[i - 1].ColumnName;
// oSheet.Cells[1,i].Font.Background = System.Drawing.Color.Red;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
////// Resize the columns
//oRange = oSheet.get_Range(1, 23);
////oRange.EntireColumn.AutoFit();
//oRange.Range[1, 2].AutoFit();
// Save the sheet and close
oSheet = null;
// oRange = null;
//oWB.SaveAs(#"c:\REPORTS.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();
}
The exception error pops up in this code. oSheet.Cells[1, i] = arrays[i - 1];
Do you guys know how can this happen? I don't understand what's wrong in my code.. Please help me on this one. Thanks in advance for your help.
Try changing
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
To
oSheet = (Excel.Worksheet)oXL.ActiveSheet;
Further explanation: MSDN provides the following note regarding the Workbook Interface....
"This interface is implemented by the Visual Studio Tools for Office runtime. It is not intended to be implemented in your code. For more information, see Visual Studio Tools for Office Runtime Overview."
That's why you have to reference the application interface after initializing a new workbook.
Please mark this as answered if it resolved your question.
Related
this ist my first VS and C# project. I want to access an excel file and add some data. Pretty much standard I guess. So I used a code example from the microsoft page (see below). No red underlines in the editor. But when I run it, I get the error message below. I guess it is not a problem of the code. Can anyone help me or send me a helpful link?
I use Visual Studio 2019 Community and Office 365 64-bit.
Error:
Message=Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))
I already tried this solution, but it didn't work.
VB: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace test2Excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
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;
// Create an array to multiple values at once.
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";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
//Manipulate a variable number of columns for Quarterly Sales Data.
DisplayQuarterlySales(oSheet);
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
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");
}
}
private void DisplayQuarterlySales(Excel._Worksheet oWS)
{
Excel._Workbook oWB;
Excel.Series oSeries;
Excel.Range oResizeRange;
Excel._Chart oChart;
String sMsg;
int iNumQtrs;
//Determine how many quarters to display data for.
for (iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)
{
sMsg = "Enter sales data for ";
sMsg = String.Concat(sMsg, iNumQtrs);
sMsg = String.Concat(sMsg, " quarter(s)?");
DialogResult iRet = MessageBox.Show(sMsg, "Quarterly Sales?",
MessageBoxButtons.YesNo);
if (iRet == DialogResult.Yes)
break;
}
sMsg = "Displaying data for ";
sMsg = String.Concat(sMsg, iNumQtrs);
sMsg = String.Concat(sMsg, " quarter(s).");
MessageBox.Show(sMsg, "Quarterly Sales");
//Starting at E1, fill headers for the number of columns selected.
oResizeRange = oWS.get_Range("E1", "E1").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";
//Change the Orientation and WrapText properties for the headers.
oResizeRange.Orientation = 38;
oResizeRange.WrapText = true;
//Fill the interior color of the headers.
oResizeRange.Interior.ColorIndex = 36;
//Fill the columns with a formula and apply a number format.
oResizeRange = oWS.get_Range("E2", "E6").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Formula = "=RAND()*100";
oResizeRange.NumberFormat = "$0.00";
//Apply borders to the Sales data and headers.
oResizeRange = oWS.get_Range("E1", "E6").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;
//Add a Totals formula for the sales data and apply a border.
oResizeRange = oWS.get_Range("E8", "E8").get_Resize(Missing.Value, iNumQtrs);
oResizeRange.Formula = "=SUM(E2:E6)";
oResizeRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle
= Excel.XlLineStyle.xlDouble;
oResizeRange.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).Weight
= Excel.XlBorderWeight.xlThick;
//Add a Chart for the selected data.
oWB = (Excel._Workbook)oWS.Parent;
oChart = (Excel._Chart)oWB.Charts.Add(Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
//Use the ChartWizard to create a new chart from the selected data.
oResizeRange = oWS.get_Range("E2:E6", Missing.Value).get_Resize(
Missing.Value, iNumQtrs);
oChart.ChartWizard(oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oSeries = (Excel.Series)oChart.SeriesCollection(1);
oSeries.XValues = oWS.get_Range("A2", "A6");
for (int iRet = 1; iRet <= iNumQtrs; iRet++)
{
oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
String seriesName;
seriesName = "=\"Q";
seriesName = String.Concat(seriesName, iRet);
seriesName = String.Concat(seriesName, "\"");
oSeries.Name = seriesName;
}
oChart.Location(Excel.XlChartLocation.xlLocationAsObject, oWS.Name);
//Move the chart so as not to cover your data.
oResizeRange = (Excel.Range)oWS.Rows.get_Item(10, Missing.Value);
oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;
oResizeRange = (Excel.Range)oWS.Columns.get_Item(2, Missing.Value);
oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
}
}
}
Interop always requires MS Office installed on your PC.
Looks like you are using Office 365 on web.
Anyways, the library excellibrary , can help
https://code.google.com/archive/p/excellibrary/
The Other option is using npoi NuGet which is a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
https://github.com/nissl-lab/npoi
https://www.nuget.org/packages/NPOI/
I'm currently writting a C#.NET application who use a VBA macro in an Excel file.
I run the macro from the c# application when the user click on a button. I have to wait all data are downloaded that's why this is the VBA code who execute "Application.Quit".
There is my code :
private void toolStripButton5_Click(object sender, EventArgs e)
{
int lastUsedRowFund, lastUsedRowEquity, lastUsedRowBond, lastUsedRowAccount = 0;
Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook oWB = null;
Excel.Worksheet oSheetFund = null;
Excel.Worksheet oSheetEquity = null;
Excel.Worksheet oSheetBond = null;
Excel.Worksheet oSheetAccount = null;
oXL.Visible = false;
oWB = oXL.Workbooks.Open("C:\\extract.xlsm");
oSheetFund = oWB.Sheets["Fund"];
oSheetEquity = oWB.Sheets["Equity"];
oSheetBond = oWB.Sheets["Bond"];
oSheetAccount = oWB.Sheets["Account"];
string[] valuesHeaderFund = {"field1", "field2" };
string[] valuesHeaderEquity = {"field1", "field2"};
string[] valuesHeaderBond = {"field1", "field2"};
string[] valuesHeaderAccount = {"field1", "field2"};
Excel.Range headerFund = oSheetFund.get_Range("A1", "AA1");
Excel.Range headerEquity = oSheetEquity.get_Range("A1", "AE1");
Excel.Range headerBond = oSheetBond.get_Range("A1", "AE1");
Excel.Range headerAccount = oSheetAccount.get_Range("A1", "AE1");
headerFund.Value2 = valuesHeaderFund;
headerEquity.Value2 = valuesHeaderEquity;
headerBond.Value2 = valuesHeaderBond;
headerAccount.Value2 = valuesHeaderAccount;
Excel.Range lastRowFund = oSheetFund.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowEquity = oSheetEquity.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowBond = oSheetBond.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowAccount = oSheetAccount.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
lastUsedRowFund = lastRowFund.Row;
lastUsedRowEquity = lastRowEquity.Row;
lastUsedRowBond = lastRowBond.Row;
lastUsedRowAccount = lastRowAccount.Row;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string[] data = { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()};
if (row.Cells[5].Value.ToString() == "FON")
{
lastUsedRowFund += 1;
oSheetFund.get_Range("A" + lastUsedRowFund, "K" + lastUsedRowFund).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "ACT")
{
lastUsedRowEquity += 1;
oSheetEquity.get_Range("A" + lastUsedRowEquity, "K" + lastUsedRowEquity).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "OBL")
{
lastUsedRowBond += 1;
oSheetBond.get_Range("A" + lastUsedRowBond, "K" + lastUsedRowBond).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "ACCOUNT")
{
lastUsedRowAccount += 1;
oSheetAccount.get_Range("A" + lastUsedRowAccount, "K" + lastUsedRowAccount).Value2 = data;
}
}
RunMacro(oXL, new Object[] { "Main" });
oXL.UserControl = false;
//oWB.Close();
//oXL.Quit();
releaseObject(lastRowFund);
releaseObject(lastRowEquity);
releaseObject(lastRowBond);
releaseObject(lastRowAccount);
releaseObject(headerFund);
releaseObject(headerEquity);
releaseObject(headerBond);
releaseObject(headerAccount);
releaseObject(oSheetFund);
releaseObject(oSheetEquity);
releaseObject(oSheetBond);
releaseObject(oSheetAccount);
releaseObject(oWB);
releaseObject(oXL);
private void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.InvokeMethod,
null, oApp, oRunArgs);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
When i click on the toolStripButton5, everything is working. But at the end an "EXCEL.EXE" processus still alive in task manager. When i click again on the button, a new "EXCEL.EXE" is create but when the task is finish, the processus is correctly release.
When i quit my application, the first processus is release.
Can you help me to correctly release the object at the first click.
Regards,
Danny.
Unfortunatelly this is not so simple to quit Excel app, because COM objects of Interoop services still exists in memory. That's why Excel.exe process is still running. Every object can be released using Marshal class. Sample codes:
Marshal.ReleaseComObject(excelSheets); //Worksheet
Marshal.ReleaseComObject(excelSheet); //Sheet
...and so on.
Hope this helps.
Now, it works greatly. When i execute a second extraction with Excel, the first process is correctly release when the new one is created.
I just replace in "releaseObject" System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); by
Marshal.ReleaseComObject(obj);
Maybe because i use "using System.Runtime.InteropServices;" in the header.
Thanks a lot.
Regards
I want to create Excel Sheet in asp.net. I have already done code for this and it is working fine in local system but when I am testing it on server then it gives the following error.
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.
My code is.
private static System.Data.DataTable GetDataSet()
{
System.Data.DataTable dt = new System.Data.DataTable("Table");
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Address", Type.GetType("System.String"));
dt.Columns.Add("Phone", Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["Name"] = "Balaji Selvarajan";
dr["Address"] = "Reddiyur";
dr["Phone"] = "000-000-0000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Balaji S";
dr["Address"] = "Kattumannar Koil";
dr["Phone"] = "000-000-0000";
dt.Rows.Add(dr);
return dt;
}
private static void DataSetToExcel(System.Data.DataTable dt, Boolean generateIdentity)
{
try
{
string Filename = HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls";
string imagepath1 = HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls";
FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~/Doc/") + "Test.xls");
if (fi.Exists)
{
fi.Delete();
}
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(misValue, misValue, misValue, misValue);
ws.Name = "Test";
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (i == 0)
ws.Cells[1, j + 1] = dt.Columns[j].ColumnName;
ws.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
}
ws.Protect("1235", true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
}
wb.Protect("my", true, true);
wb.Password = "1235";
wb.SaveAs(Filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, "1235", misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
wb.Close(true, misValue, misValue);
xlApp.Visible = true;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
HttpContext.Current.Response.ContentType = "Application/Excel";
string FilePath = imagepath1;
HttpContext.Current.Response.WriteFile(FilePath);
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Test.xls");
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
protected void BtnDn_Click(object sender, EventArgs e)
{
DataSetToExcel(GetDataSet(), false);
}
I am not able to solve this problem please help me. and give me solution as soon as possible please.
I am using Asp.net C#.
Try with this
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
namespace Excel
{
public class ExcelUtlity
{
public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType) {
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
try
{
// Start Excel and get Application object.
excel = new Microsoft.Office.Interop.Excel.Application();
// for making Excel visible
excel.Visible = false;
excel.DisplayAlerts = false;
// Creation a new Workbook
excelworkBook = excel.Workbooks.Add(Type.Missing);
// Workk sheet
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
excelSheet.Name = worksheetName;
excelSheet.Cells[1, 1] = ReporType;
excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString();
// loop through each row and add values to our sheet
int rowcount = 2;
foreach (DataRow datarow in dataTable.Rows)
{
rowcount += 1;
for (int i = 1; i <= dataTable.Columns.Count; i++)
{
// on the first iteration we add the column headers
if (rowcount == 3)
{
excelSheet.Cells[2, i] = dataTable.Columns[i-1].ColumnName;
excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
}
excelSheet.Cells[rowcount, i] = datarow[i-1].ToString();
//for alternate rows
if (rowcount > 3)
{
if (i == dataTable.Columns.Count)
{
if (rowcount % 2 == 0)
{
excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black,false);
}
}
}
}
}
// now we resize the columns
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
excelCellrange.EntireColumn.AutoFit();
Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
border.Weight = 2d;
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dataTable.Columns.Count]];
FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
//now save the workbook and exit Excel
excelworkBook.SaveAs(saveAsLocation);;
excelworkBook.Close();
excel.Quit();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
finally
{
excelSheet = null;
excelCellrange = null;
excelworkBook = null;
}
}
/// FUNCTION FOR FORMATTING EXCEL CELLS
public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool)
{
range.Interior.Color=System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode);
range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor);
if (IsFontbool == true)
{
range.Font.Bold = IsFontbool;
}
}
}
Error 80070005 is an Access Denied error. Try configuring your AppPool to run under LocalSystem (instead of ApplicationPoolIdentity), or try granting permissions for Excel in Component Services:
From the Start menu, click Run and type Dcomcnfg.exe.
In Component Services, click Console root, expand Component Services, expand Computers, expand My computer,expand DCOMConfig.
Search for Microsoft Word 14.0 Object Library. Click on it.
Right click and select Properties.
On security tab, select Customize in "Launch and Activation" section.
Click edit and add identity of app pool under which you application is running.
Repeat above step for "Access Permission"
AppPool account solution is from here: "Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
Component Services Permission answer is from here: Retrieving the COM class factory for component with CLSID failed due to the following error: 80070005 Access is denied.
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.