0

I simply tried to take data from excel and show them in excel.When I click the button the data in excel will be listed in datagridview.

My codes:

private void btn_load_Click(object sender, EventArgs e) { try { System.Data.OleDb.OleDbConnection MyConnection; System.Data.DataSet DtSet; System.Data.OleDb.OleDbDataAdapter MyCommand; MyConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Dell\Desktop\kitap.xlsx';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'"); MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection); MyCommand.TableMappings.Add("Table", "TestTable"); DtSet = new System.Data.DataSet(); MyCommand.Fill(DtSet); dataGridView1.DataSource = DtSet.Tables[0]; MyConnection.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } 

Error:

Error When I tried to import

2
  • have you checked that sheet1 exists in your excel workbook? Commented Jul 30, 2015 at 9:00
  • yes I have checked and I created one more excel file and still error Commented Jul 30, 2015 at 9:02

1 Answer 1

1

Try this

private void button1_Click(object sender, EventArgs e) { String name = "sheet1"; String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Sample.xlsx" + ";Extended Properties='Excel 12.0 XML;HDR=YES;';"; OleDbConnection con = new OleDbConnection(constr); OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con); con.Open(); OleDbDataAdapter sda = new OleDbDataAdapter(oconn); DataTable data = new DataTable(); sda.Fill(data); grid_items.DataSource = data; } 
Sign up to request clarification or add additional context in comments.

2 Comments

@Nalaka Its just a basic code that every one follows while writing code (names especially).. I cant help if some one write the same code before me... Do you follow any other convention while writing this pic of code then do let me Know.. i will also Learn From U.. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.