Search code examples
c#.netoledbimport-from-excel

import excel file error


I found a video on youtube that shows how to import an excel file to a datagridview. I'm getting an error: Could not find installable ISAM.

Here is my code, what am I doing wrong?

private void button1_Click(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Nick\Desktop\Pricing2.xlsx" + @";Exended Properties=""Excel 8.0;HDR=No;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";

        OleDbCommand command = new OleDbCommand
        (
            "SELECT PartNumber,ShortDescription,RetailPrice,JobberPrice,BasePrice,YourDiscount,YourPrice,LongDescription FROM [Pricing$]",conn
        );
        DataSet ds = new DataSet();
        OleDbDataAdapter adapter = new OleDbDataAdapter(command);
        adapter.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0];
    }

Solution

  • You have a typo in your connection string:

    Exended Properties=
    

    Should be:

    Extended Properties=
    

    Also I would recommend you a slight improvement of your code which consist in properly disposing disposable resources:

    using (var conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Nick\Desktop\Pricing2.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "SELECT PartNumber,ShortDescription,RetailPrice,JobberPrice,BasePrice,YourDiscount,YourPrice,LongDescription FROM [Pricing$]";
        using (var adapter = new OleDbDataAdapter(cmd))
        {
            adapter.Fill(ds);
        }
    }