Retrieve Data From Excel file Using C#

Two different types are there to fetch the data from the Excel file.

  1. Using OLeDb Connection
  2. Using Excel Reference Object

Also we will define, what are the advantages and disadvantages of both the processes.

  1. Using OleDb Connection
    1. string cs=@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ContactDetailsofGICEmployee.xls';Extended Properties=Excel 8.0;";  
    2. DataTable EmployeeTable=new DataTable();  
    3. OleDbConnection con=new OleDbConnection(cs);  
    4. OleDbCommand cmd=new OleDbCommand("Select * from [sheet1$]",con);  
    5. OleDbDataAdapter oda=new OleDbDataAdapter(cmd);  
    6. oda.Fill(EmployeeTable);  
    7. return EmployeeTable;  
    Advantages: Simple to use and same like SQL coding.

    Disadvantages: Excel should contain the data in table format for Insert and Update commands to use.

  2. Using Excel Reference Object
    1. Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();  
    2. Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(@"D:\ContactDetailsofGICEmployee.xls", 0, true, 5, """"true,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t"falsefalse, 0, true, 1, 0);  
    3. Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;  
    4. Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)theWorkbook.Worksheets.get_Item(1);  
    5. Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;  
    6. int r=range.Rows.Count;  
    7. dt.Columns.Add("EmpCode");  
    8. dt.Columns.Add("EmpName");  
    9. dt.Columns.Add("Email");  
    10. dt.Columns.Add("ContactNo");  
    11. for(int i=1;i<=r;i++)  
    12. {  
    13.    DataRow dr=dt.NewRow();  
    14.    dr["EmpCode"]= Convert.ToString((worksheet.Cells[i, 1] as Microsoft.Office.Interop.Excel.Range).Value2);  
    15.    dr["EmpName"]= Convert.ToString((worksheet.Cells[i, 2] as Microsoft.Office.Interop.Excel.Range).Value2);  
    16.    dr["Email"]= Convert.ToString((worksheet.Cells[i, 3] as Microsoft.Office.Interop.Excel.Range).Value2);  
    17.    dr["Cont"]= Convert.ToString((worksheet.Cells[i, 4] as Microsoft.Office.Interop.Excel.Range).Value2);  
    18.    dt.Rows.Add(dr);  
    19. }  
    20. return dt;  
    Advantages: Dynamic Row and Column Index can be accessed i.e no need to have data in excel in tabular format.

    Disadvantages: Coding is difficult and requires to create the reference for many types thus memory allocation will be high.
Ebook Download
View all
Learn
View all