【问题标题】:C# export datatable to excel spreadsheet *object reference not set to an instance of an objectC# 将数据表导出到 excel 电子表格 *对象引用未设置为对象的实例
【发布时间】: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 方法也比一次写入一个单元格要快得多。

标签: c# sql excel datatable


【解决方案1】:

我相信您必须在访问活动工作表之前创建一个新工作簿。试试:

excelApp.Workbooks.Add();

在访问活动工作表之前。

【讨论】:

  • 谢谢!这解决了我的问题!我很感激。实际上,我过去曾多次遇到此问题,我的解决方法总是导出到文本文件,然后将其打开/保存为 .xlsx。但这将使我受益匪浅。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2016-08-22
相关资源
最近更新 更多