Entity framework Read an Excel file and show in datagrid in c #

0

Good afternoon I am trying to read an excel file with entity framework, I have a class which I want to be filled with the data from the excel file and at the end show me the excel in a datagrid c #. What is the way to do it? xfavor

  private void btnAbrir_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog doc = new OpenFileDialog() { Filter = "Microsoft Excel (*.xlsx)|*.xlsx|Todos los archivos (*.*)|*.*", ValidateNames = true })
        {
            if (doc.ShowDialog() == DialogResult.OK)
            {
                StreamReader fs = File.OpenText(doc.FileName);
                string s;
                while (!fs.EndOfStream)
                {
                    s = fs.ReadLine();
                    dataGridView1.Rows.Add(s); //Aqui me genera error ya que me dice que primero debe agregar columnas
                }
                fs.Close();
            }
        }
    
asked by Alejandro hernandez guzman 21.04.2017 в 02:15
source

1 answer

1

Entity Framework in principle has no relation to the reading of an excel, unless you get the implementation of a provider that can be used, it exists but is not free to use, is licensed.

That's why you would use simple ado.net, or maybe some library based on open xml

If it's with ado.net it could be something like

Read Data From an Excel File (.xls)

The idea is to define the connection string

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sample1.xls;Extended Properties=Excel 8.0

To then perform the query to excel as if it were a db

OleDbConnection oledbConn = new OleDbConnection(connString);
oledbConn.Open();

OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
oleda.Fill(dt);

dataGridView1.DataSource = dt;

but you would not be using entity framework but just ado.net

If ado.net does not convince you and you want to evaluate a library I would recommend

ClosedXML

    
answered by 21.04.2017 в 08:32