简体   繁体   中英

C# export datatable to excel spreadsheet *object reference not set to an instance of an object

Hey folks I am trying to export a datatable to an excel spreadsheet (excel 15.0 library, excel 2013, VS 2013), and I am running into an issue. Right now I'm not worried so much about getting column headers and all that I'd just be happy with getting the data into the spreadsheet, my code is below and when I run it I keep getting

Object reference not set to an instance of an object

on the

workSheet.Cells[(i+2),(j+1)]

line of code.

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)
        {
        }
}

I believe you have to create a new workbook before accessing the active sheet. Try:

excelApp.Workbooks.Add();

BEFORE accessing the active worksheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM