How to read an excel file and map

Asked

Viewed 86 times

2

I would like to know how to read an excel file and then map to a datagridview.

Code I tried on :

var fileName = @"C:\Users\HP8200\Desktop\test.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
  using (var conn = new OleDbConnection(connectionString)) {
    conn.Open();
    var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "PARAC1" });
    using (var cmd = conn.CreateCommand()) {
      cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["PARAC1"].ToString() + "] ";
      var adapter = new OleDbDataAdapter(cmd);
      var ds = new DataSet();
      adapter.Fill(ds);
  • And have you tried filling gridview with this dataset? : Grivew1.datasource= ds.Table[0];

  • @Renatoafonso this does not work

  • "This does not work". Very explicit. Error? Shows where you put the line of code I suggested.

1 answer

2


    private void preencherDataGridView()
    {

        var fileName = @"C:\Desenv\Pasta1.xlsx";
        var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;

        var conexao = new System.Data.OleDb.OleDbConnection(connectionString);

        var sql = "SELECT * FROM [Plan1$]";

        var cmm = new System.Data.OleDb.OleDbCommand(sql, conexao);
        var dt = new System.Data.DataTable();

        conexao.Open();

        System.Data.OleDb.OleDbDataReader dr = cmm.ExecuteReader();
        dt.Load(dr);

        conexao.Close();

        dataGridView1.DataSource = dt;
    }
  • Where it says "Plan1$" I put what in my code ?

  • Put the name of the worksheet tab that contains the data. If you don’t know, open the spreadsheet in Excel and look at the tab name in the bottom left corner.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.