Nemo
Nemo

Reputation: 203

Import excel sheet to a datagrideview

I am trying to use this code Used Code to import an excel sheet to data grideview but this exception is fired and i do not know what is the main probelm.

Exception

I am trying some solutions like change the active solution platform from anyone to x86 but it does not work

Does the excel file version is important Excel 2010 , Excel 2013 ?

update:
I installed Microsoft Office Access database engine from this Site, and the last exception is disappeared but this new exception is fired

Exception#2

This is the used code:

public void importfromexcel()
    {
        string SheetPath = @"E:\students.xlsx";
        string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SheetPath + ";Extended Properties=Excel 12.0;';";
        OleDbConnection con = new OleDbConnection(constr);
        OleDbDataAdapter sda = new OleDbDataAdapter("Select * From [" + SheetPath + "$]", con);
        System.Data.DataTable data = new System.Data.DataTable();
        sda.Fill(data);
        dataGridView1.DataSource = data;
    }

Is there any problem in this code ??
Thanks in advance.

Upvotes: 2

Views: 193

Answers (1)

JohnG
JohnG

Reputation: 9469

Try the code below with some small changes… it works as expected.

string WorkBookPath = @"D:\Test\Book1.xlsx";  //@"E:\students.xlsx";
string SheetName = "Sheet1$"; // <--- this is the name of the WORKSHEET in the workBOOK
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + WorkBookPath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection con = new OleDbConnection(constr)) {
  OleDbDataAdapter sda = new OleDbDataAdapter("Select * From [" + SheetName + "]", con);
  DataTable data = new DataTable();
  sda.Fill(data);
  dataGridView1.DataSource = data;
}

Upvotes: 1

Related Questions