写入 Excel 单元格时出现异常

I get an exception when writing to Excel cell

我有一个列表视图,我正在尝试将列表视图中的数据保存到 Excel 工作簿中。异常发生在 ws.Cells[row,col] 行。这是我的代码:

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

例外情况是:

System.Runtime.InteropServices.COMException (0x800A03EC)

我已经对错误代码进行了一些研究,但我只能找到与尝试保存文件的人有关的问题。我还没到保存文件的时候,我遇到了异常。

Cells 索引器是从一开始而不是从零开始的(所以 A1[1, 1]

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

Excel 单元格是 1-base 索引,尝试:

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