Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# COM Interop: Writing to a Cell in an Excel Sheet

I am using Microsoft.Office.Interop.Excel in a winform where I am reading one excel file, processing the data, and outputting a new excel file. However I am having trouble writing to the cells -- specifically to add column headings. Here's the code:

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
for (int i = 0; i < dt.Columns.Count; i++)
{
    for (int j = 0; j < dt.Rows.Count; j++)
    {
        ws.Cells[j + 1, i] = dt.Rows[j][i].ToString();
    }
}
ws.Cells[0, 0] = "Ticket Number";
ws.Cells[0, 1] = "Transit";
ws.Cells[0, 2] = "Outage Start Date";
ws.Cells[0, 3] = "Outage End Date";
ws.Cells[0, 4] = "Business Impact";
wb.Worksheets.Add(ws);

where "dt" is my DataTable. The nested for-loop doesn't throw a runtime error but the code following it does. The error just says: COM Exception was unhandled, Exception from HRESULT: 0x800A03EC.

Any advice is appreciated.

Regards.

like image 337
Kevin Avatar asked Feb 21 '23 00:02

Kevin


1 Answers

Cells[] is 1-based, not zero-based.

like image 60
Tim Williams Avatar answered Feb 28 '23 07:02

Tim Williams