Home » excel » Importing Any Excel Spreadsheet into a DataGridView – C#

Importing Any Excel Spreadsheet into a DataGridView – C#

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a program that imports an excel spreadsheet into a datagridview. I have written the code as follows:

try
                {
                    OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
                    connStringBuilder.DataSource = file;
                    connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
                    connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");

                    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

                    DbDataAdapter adapter = factory.CreateDataAdapter();

                    DbCommand selectCommand = factory.CreateCommand();
                    selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";

                    DbConnection connection = factory.CreateConnection();
                    connection.ConnectionString = connStringBuilder.ConnectionString;

                    selectCommand.Connection = connection;

                    adapter.SelectCommand = selectCommand;

                    data = new DataSet();

                    adapter.Fill(data);

                    dataGridView1.DataSource = data.Tables[0].DefaultView;

                }
                catch (IOException)
                {

                }

The line “selectCommand.CommandText = “SELECT * FROM [All Carpets to Excel$]”;” takes the data from the sheet with that name. I was wondering how I could get this program to open an excel document with any sheet name. One that I may not know.

How to&Answers:

You can get all the sheets’ names like so..

public string[] GetExcelSheetNames(string excelFileName)
{
        OleDbConnection con = null;
        DataTable dt = null;
        String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
        con= new OleDbConnection(conStr);
        con.Open();
        dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if (dt == null)
        {
            return null;
        }

        String[] excelSheetNames = new String[dt.Rows.Count];
        int i = 0;

        foreach (DataRow row in dt.Rows)
        {
            excelSheetNames[i] = row["TABLE_NAME"].ToString();
            i++;
        }

        return excelSheetNames;
}