Using Automation to write to Excel 2007 and 2003

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi. Ive been trying to find the best way to write a DataTable to an excel spreadsheet. I found and utilized what I believe is referred to as automation. This required I add a reference to the COM object, Microsoft Excel 12.0 Object Library. This seems to
run fine on my development PC (which has Excel 2007). However, when I deploy the application to a demo machine running Excel 2003 it crashes. From what I have been able to find it involves missing PIAs, or the need for Excel 11.0 Object
Library. I need my application to be self-contained so that my user is not required to download additional material. Can anyone provide some guidance on how to do this? (code below)

<div style="color:Black;background-color:White; <pre>
<span style="color:Blue; private <span style="color:Blue; void exportToExcelToolStripMenuItem_Click(<span style="color:Blue; object sender, EventArgs e)
{
DataSet ExcelDataSet = <span style="color:Blue; new DataSet();
ExcelDataSet = FilteredTable.DataSet; <span style="color:Green; //Assign filtered table to dataset

<span style="color:Blue; try
{
Microsoft.Office.Interop.Excel.ApplicationClass excel = <span style="color:Blue; new Microsoft.Office.Interop.Excel.ApplicationClass();

excel.Application.Workbooks.Add(<span style="color:Blue; true);
<span style="color:Blue; int ColumnIndex = 0;
<span style="color:Blue; foreach (DataColumn col <span style="color:Blue; in FilteredTable.Columns)
{
ColumnIndex++;
excel.Cells[1, ColumnIndex] = col.ColumnName;
}
<span style="color:Blue; int rowIndex = 0;

<span style="color:Blue; foreach (DataRow row <span style="color:Blue; in FilteredTable.Rows)
{
rowIndex++;
ColumnIndex = 0;
<span style="color:Blue; foreach (DataColumn col <span style="color:Blue; in FilteredTable.Columns)
{
ColumnIndex++;
excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName].ToString();
}
}
excel.Visible = <span style="color:Blue; true;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
worksheet.Activate();
}
<span style="color:Blue; catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
[/code]


Thanks
Cyber

View the full article
 
Back
Top