Add a reference “Microsoft.Office.Interop.Excel” into project
![]()
Reading Excel file and Binding to DataGridView
Microsoft.Office.Interop.Excel.Application excelApp;
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
Microsoft.Office.Interop.Excel.Range range;
excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
// Opening Excel file
workbook = excelApp.Workbooks.Open(txtPath.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
range = worksheet.UsedRange;
int column = 0;
int row = 0;
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("CustomerID");
dt.Columns.Add("CompanyName");
dt.Columns.Add("ContactName");
for (row = 2; row <= range.Rows.Count; row++)
{
DataRow dr = dt.NewRow();
for (column = 1; column <= range.Columns.Count; column++)
{
dr[column - 1] = (range.Cells[row, column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
}
workbook.Close(true, null, null);
excelApp.Quit();
// Binding to DataGridView
dataGridView1.DataSource = dt;
Example
Related posts:
This is the best and smothest way of interacting with excel file that I could find so far.
Thanks a lot.
Even though, I was trying to mod the code for my own needs without success.
Please help me with my request:
I’d want to retrieve a cell value (say “CompanyName”) and put it in an Textbox based on user’s input/selection (say from a listbox where “CustomerID” values are kept).
This is the top of the iceberg. Once I have an idea how this may be accomplished, I think I can continue on my project.
Thank you in advance & happy new year