写入Excel单元格时出现exception
我有一个列表视图,我试图将数据保存到Excel工作簿的列表视图。 ws.Cells[row,col]
行出现exception。 这是我的代码:
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)
我已经对错误代码做了一些研究,但是我只能find试图保存文件的人的问题。 我不在保存文件,我得到的例外。
Cells
格索引器是一个基于零而不是基于(所以A1
是[1, 1]
)
for (int row = 1; row <= listView1.Items.Count; row++) ... for (int col = 1; col <= item.SubItems.Count; col++)
Excel单元格是1基础索引,请尝试:
ws.Cells[row + 1,col + 1] = item.SubItems[col].Text.ToString();