【问题标题】:write excel data to datatable将excel数据写入数据表
【发布时间】:2013-01-21 10:57:03
【问题描述】:

我已经编写了下面的代码来将数据从 excel 文件写入数据表,但由于某种原因,在写入数据表时,索引 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();
                }

【问题讨论】:

  • 我刚刚用您的代码进行了测试,它工作正常(尽管我在连接字符串中添加了HDR=NO 以获得第一行)。您的电子表格或其格式化方式一定有什么不寻常之处。

标签: c# excel datatable


【解决方案1】:

您的连接字符串有问题.....................如果您想避免标题或想要包含标题行或从第一行开始,您需要为 excel 添加一个连接字符串的扩展属性。

请查看this

skip first row in read of Excel file

【讨论】:

    【解决方案2】:

    关于来自row[0] 的数据有助于将属性HDR=No; 包含在强连接的扩展属性中。

    【讨论】:

    • 那是因为您缺少引号。 Extended Properties='Excel 12.0;HDR=NO'(使用单引号)。
    • 这仍然不起作用..它仍然会读取行中的数据,但会读取额外的数据
    猜你喜欢
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2021-11-29
    • 2019-01-09
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多