【发布时间】:2014-09-24 17:16:32
【问题描述】:
大家好,我正在尝试将数据表导出到 excel 电子表格(excel 15.0 库、excel 2013、VS 2013),但遇到了问题。现在我不太担心获取列标题,我只是很高兴将数据输入电子表格,我的代码在下面,当我运行它时,我不断得到
对象引用未设置为对象的实例
关于
workSheet.Cells[(i+2),(j+1)]
代码行。
public static void exportReport(System.Data.DataTable Results)
{
try
{
string excelFilePath = @"C:\exceltest\exceltestsheet.xlsx";
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;
if (Results == null || Results.Columns.Count == 0)
{
throw new Exception("null or empty table");
}
for (int i = 0; i < Results.Rows.Count; i++)
{
for (int j = 0; j < Results.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Results.Rows[i][j];
}
}
if (excelFilePath != null && excelFilePath != "")
{
workSheet.SaveAs(excelFilePath);
excelApp.Quit();
Console.WriteLine("Excel File Saved!");
}
}
catch(Exception ex)
{
}
}
【问题讨论】:
-
检查
workSheet是否为空 -
也许将其更改为 Worksheet.Cells[(i + 2), (j +1)].Value ??但这是写入 Excel 的一种非常缓慢的方法,您可能想改用 OpenXML 吗?即使是 ADO CopyFromRecordset 方法也比一次写入一个单元格要快得多。