将excel数据写入datatable

时间:2013-01-21 10:57:03

标签: c# excel datatable

我编写了下面的代码,用于将数据从excel文件写入数据表,但出于某种原因,在写入datatable时,不显示索引0和1的行数据。有没有人知道为什么会这样......

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();
                }

2 个答案:

答案 0 :(得分:1)

你的连接字符串有问题....................如果你想避免标题或想要包含标题行或从第一行开始你需要为excel包含更多的conncetion string属性。

请检查this

skip first row in read of Excel file

答案 1 :(得分:0)

关于来自row[0]的数据可以帮助您在连接的扩展属性中包含属性HDR=No;