【问题标题】:C#: Read Excel file failed with cell format look like numberC#:读取 Excel 文件失败,单元格格式看起来像数字
【发布时间】:2017-11-11 08:44:36
【问题描述】:

我使用这个函数来读取excel文件到数据表:

public static DataTable exceldata(string filePath)
    {
        try
        {
            DataTable dtexcel = new DataTable();
            bool hasHeaders = false;
            string HDR = hasHeaders ? "Yes" : "No";
            string strConn;
            if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\"";
            else
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\"";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            DataRow schemaRow = schemaTable.Rows[0];
            string sheet = schemaRow["TABLE_NAME"].ToString();
            if (!sheet.EndsWith("_"))
            {
                string query = "SELECT  * FROM [" + sheet + "]";
                OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                dtexcel.Locale = CultureInfo.CurrentCulture;
                daexcel.Fill(dtexcel);
            }
            conn.Close();
            return dtexcel;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

我的问题是:当 Excel 文件有一些格式看起来像数字的单元格(例如:301/1、181/3 ....)时,数据表在该单元格中返回空值。
如何将 Excel 文件读取到数据表中,将单元格作为字符串,而不是检测到数字?

【问题讨论】:

  • 尝试将底层excel格式化为文本
  • 你能附上那个电子表格吗(通过 DropBox 或 G-drive 之类的)?我相信你,但我从未见过也无法复制这个问题。

标签: c# excel string datatable numbers


【解决方案1】:

我知道您特别要求使用 Excel 工作表。作为遇到完全相同问题的人,我建议您使用 ClosedXML 而不是使用 Oledb 连接。

封闭式 XML 的读取速度要快得多,并且允许您非常轻松地获取整个工作表或单元格的内容。

我在这里回答了另一个类似的问题

https://stackoverflow.com/a/47235686/6729097

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 2018-06-17
    • 1970-01-01
    • 2017-05-31
    • 2018-11-10
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多