3

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

5
  • 2
    That's the name of the file. What are the names on the tabs inside the file? IIRC that's what the sheets are. Commented Aug 4, 2016 at 14:46
  • I attached the image of the excel sheet Commented Aug 4, 2016 at 14:49
  • What's the name of the tab at the bottom of the sheet. Commented Aug 4, 2016 at 14:51
  • contents is the name there Commented Aug 4, 2016 at 14:52
  • 1
    Then that is the sheet name. See my answer. Commented Aug 4, 2016 at 14:52

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'd put the data in a dataset with command.Fill then work with the dataset like normal
Can you please provide some psudocode I am very new to C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.