user2097314
user2097314

Reputation: 59

I get an exception when writing to Excel cell

I have a listview and I am trying to save the data in the listview to an Excel workbook. The exception occurs on the ws.Cells[row,col] line. Here is my code:

using Excel = Microsoft.Office.Interop.Excel;
...
Excel.Application xl = new Excel.Application();
xl.Visible = false;
Excel.Workbook wb = (Excel.Workbook)xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

for (int row = 0; row < listView1.Items.Count; row++)
{
    ListViewItem item = listView1.Items[row];

    for (int col = 0; col < item.SubItems.Count; col++)
    {
        ws.Cells[row,col] = item.SubItems[col].Text.ToString(); // exception here
        //ws.Cells[row,col] = "Test"; // I've tried this too
    }
 }

The exception is:

System.Runtime.InteropServices.COMException (0x800A03EC)

I've done some research on the error code, but I've only been able to find issues with people trying to save the file. I'm not at the point of saving the file and I am getting the exception.

Upvotes: 0

Views: 638

Answers (2)

TVOHM
TVOHM

Reputation: 2742

Excel cells are 1-base indexing, try:

ws.Cells[row + 1,col + 1] = item.SubItems[col].Text.ToString();

Upvotes: 1

Alex K.
Alex K.

Reputation: 175926

The Cells indexer is one-based not zero-based (so A1 is [1, 1])

for (int row = 1; row <= listView1.Items.Count; row++)
...
   for (int col = 1; col <= item.SubItems.Count; col++)

Upvotes: 0

Related Questions