嘿,伙计们,我正试图将数据表导出到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:exceltestexceltestsheet.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)
{
}
}
我认为您必须在访问活动工作表之前创建一个新的工作簿。试一试:
excelApp.Workbooks.Add();