Jim Brad
Jim Brad

Reputation: 393

write excel data to datatable

I have written the code below to write data from an excel file to a datatable, but for some reason when writing to datatable the data for row at index 0 and 1 are not displayed. does anyone have an idea to why this could be..

var excelDataTable = new DataTable();
            var excelAdapter = new OleDbDataAdapter();

            var excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + excelFileName + ";Extended Properties=Excel 12.0;";
            // Create Connection to Excel Workbook
            using (var excelConnection = new OleDbConnection(excelConnectionString))
                {                    
                    excelConnection.Open();

                    var dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    if (dt != null)
                    {
                        var excelSheet =  new String[dt.Rows.Count];
                        int i = 0;
                        foreach (DataRow row in dt.Rows)
                        {
                            excelSheet[i] = row["Table_Name"].ToString();
                            i++;
                        }

                        var command = new OleDbCommand
                            ("Select  * FROM [" + excelSheet[0] + "]", excelConnection); // should be first sheet not the name of the sheet, should be index

                        excelAdapter.SelectCommand = command;
                    }
                    excelAdapter.Fill(excelDataTable);
                    excelConnection.Close();
                }

Upvotes: 1

Views: 711

Answers (2)

andy
andy

Reputation: 6079

There is problem in your connection string .................... If you want to avoid the header or want to include the header rows or start from first row you need to inlcude one more exnteded property of conncetion string for excel.

Please check this

skip first row in read of Excel file

Upvotes: 1

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33391

About data from row[0] can help including the property HDR=No; in extended properties of your connection strong.

Upvotes: 0

Related Questions