drupal stats

Reading Excel and Binding to DataGridView using Microsoft.Office.Interop.Excel

July 14th, 2011 Windows Forms 1 Comment


Add a reference “Microsoft.Office.Interop.Excel” into project

Add a reference to the Microsoft.Office.Interop thumb Reading Excel and Binding to DataGridView using Microsoft.Office.Interop.Excel

 

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

Reading Excel thumb Reading Excel and Binding to DataGridView using Microsoft.Office.Interop.Excel

 

zip Reading Excel and Binding to DataGridView using Microsoft.Office.Interop.Excel Download Example Code

Tags: c# read xlsx file, read xlsx file in c#, how to read xlsx file in c#, C# read xlsx, import excel file in c#, read xlsx c#, c# xlsx, reading xlsx file in c#, read xlsx file c#, datagridview to excel c#

Related posts:

  1. Export DataGridView to Excel
  2. Import Excel file into DataGridView
  3. Import Excel Data to GridView
  4. Export DataGridView to CSV
  5. Import CSV file into DataGridView

1 Comment

  1. valv says:

    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 :)