我正在尝试使用以下代码将数据从c#导出到excel:
enter worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView1.Rows.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count - 1; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers,
// adding a condition check.
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
我收到以下错误:
指数超出范围。必须是非负数且小于集合的大小。参数名称:index。
更新我通过更改 for statement 解决了问题:
for ( int i = -1; i < DataGridView1.Columns.Count; i++)
答案 0 :(得分:1)
I think the problem is that many online guides and tutorials exlpain that when you count through Lists<>
, Arrays
and rows/columns
of a Table
you need to add +1 because all these object containers have a start index of 0.
As a newcomer it might be hard to figure out at the beginning where you have to place the +1 and especially when you have to. Maybe you were confused because you wanted the total amount of rows as your max definition of i
. But as you start your loop with int i = 0
(what is correct, because you dont want to skip the row with the index 0) you start as well at the point 0 and not 1. So there is no need to add +1 to the max breakpoint, because you still go dataGridView1.Rows.Count
times (<-- amount how often your loop gets executed) through the rows.
This exception Index was out of range
tells you that you wanted to do something with a row, which was out of range. It was out of range because this row's item didnt exist. Let´s say you have 10 rows with the index 0 - 9. Now you start going through them beginning at 0. So after 10 times executing, you went through rows 0 - 9. As dataGridView1.Rows.Count
gives you the total amount of rows, in this example 10. But you set as the breakpoint dataGridView1.Rows.Count + 1
so the loop wants to do your task the 11th time with the row that has the index 10, but the index of your last row is 9. So it can't find this row and thats the situation when it gives you the Index out of range
execption. Now I hope you understand what went wrong and why.
答案 1 :(得分:0)
尝试:
sheet.GetRow(rowNumber).CreateCell(columnNumber);
然后填写单元格值。