Oledb 跳过 excel 文件的第一列

Oledb skips the first column of excel file

当我尝试使用 OLEDB 将 Excel 文件保存到 C# 上的数据表中时遇到问题。

DataTable 没有我的 Excel 文件的第一列,但有一个额外的空列作为最后一列。我不知道我做错了什么。如果我的 Excel 文件有这样的东西:

身份证、姓名、地址

DataTable 列是:

姓名、地址、F3(空)

这是我的函数:

    public DataTable GetExcel(string[] files, string sheetName, string pathName)
    {
        for (int i = 0; i < files.Length; i++)
        {
            string strConn = string.Empty;
            if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
            FileInfo file = new FileInfo(files[i]);
            if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
            string extension = file.Extension;
            switch (extension)
            {
                case ".xls":
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
                case ".xlsx":
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                    break;
                default:
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                    break;
            }
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
            oda.Fill(dataTable);
        }
        return dataTable;
    }

谢谢!

最终问题出在 Excel 文件上,我只是使用另一台计算机将所有内容复制到另一个 Excel 文件中并开始工作。我不知道怎么了。

我希望我能帮助到别人。

感谢您的回答。

我不知道这是否发生在你身上,但我希望能帮助到其他人。 当我有这个错误时,是因为我的 csv 文件在它的开头有一个空格,这使得 Excel 忽略它之后的所有内容 - 这是我想要使用的整个字符串(出于某种原因,Excel 忽略 C# 中空格后的所有内容。

您可以使用 Trim,或者如果您想要更安全,请使用此 Regex 仅定位单词、数字和更多字符:

string s = file.ToString().Trim();
string s = new Regex(@"(\w|[0-9]|\|\/|\.|\:)+").Match(file.ToString()).Value;

在 excel 的第一列写入一个值后它起作用了。当在第一列中找不到数据时,它似乎会跳过它们。