Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Excel File using C#

Tags:

c#

excel

I am new to C# and I am trying to read an excel file with the following code

string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + 
                ";Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(conStr))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
    using (OleDbDataReader dr = command.ExecuteReader())
    {
        while (dr.Read())
        {
            var row1Col0 = dr[0];
            Console.WriteLine(row1Col0);
        }
    }
}

I get the following error:

Sheet1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.

Can anyone tell me whats I am doing wrong?

The name of excel sheet is sheet.xlsx

enter image description here Thanks

like image 368
wearybands Avatar asked Jun 15 '26 09:06

wearybands


1 Answers

The sheet name might not be the same as the filename, you can get the first sheet name by doing the following

First, get the schema

DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

Then get the first sheets name

var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();

After you get your command, you can then fill a dataset and work with it's .Rows collection

var myDataSet = new DataSet();
command.Fill(myDataSet);

The sheetname is this enter image description here

like image 140
CaffGeek Avatar answered Jun 16 '26 22:06

CaffGeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!