【发布时间】:2013-07-10 10:43:43
【问题描述】:
请使用以下代码帮助修复将数据从 Excel 文档导入到DataGridView 控件:
private void button5_Click(object sender, EventArgs e)
{
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook =app.Workbooks.Open(@"C:\Users\Admin\Desktop\Dropbox\Vandit's Folder\Internship\test.xlsx");
Excel.Worksheet worksheet = workbook.ActiveSheet;
rcount = worksheet.UsedRange.Rows.Count;
int i = 0;
for(;i<rcount;i++)
{
dataGridView1.Rows[i].Cells["Column1"].Value = worksheet.Cells[i + 1, 1].Value;
dataGridView1.Rows[i].Cells["Column2"].Value = worksheet.Cells[i + 1, 2].Value;
}
}
当我运行这段代码时,我总是得到一个异常提示
"Index was out of range. Must be non-negative and less than the size of the collection."
"Parameter name: index."
【问题讨论】:
-
看,
rowcount的dataGridView1为 0。因此,当调用dataGridView1.Rows[i].Cells["Column1"].Value时,未找到 Rows[0] 并引发异常。代码在这里所做的是修改数据网格中单元格的现有值,这些值尚不存在。所以请不要修改插入数据到数据网格中。
标签: c# datagridview import-from-excel