Please help to fix importing data from Excel document to DataGridView
control with following code:
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;
}
}
when i run this code, I always get an exception saying
"Index was out of range. Must be non-negative and less than the size of the collection."
"Parameter name: index."
you can add rows like below
What you are doing is set the values of existing rows of gridview. if gridview not having rows given by index then you will get exception
but without all these you can use Ado.net and get read the data from excel and bind it to gridview. check below sample code from this KB article
Try Below code
This error means that the index which throw error is either not exists in gridview or there is column missing in your excel file.
Number of index in datagridView must be equal to number of fields you send for datagridview.
Assuming
dataGridView1
has 2 columns,Assuming
dataGridView1
has 0 columns,