两个试图读取 excel 的程序,一个成功,一个失败,代码相同

Two programs trying to read excel one succeeds one fails with same code

我有两个互不相关的程序,但它们使用相同的方法尝试从 excel 文件中读取行。

计划 1

    public DataTable GetExcelInfo(string filepath)
    {
        DataTable datatab = new DataTable();
        try
        {
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=1;ImportMixedTypes=Text\";
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand("SELECT Format([F1], \"#\"), Format([F2], \"#\"), Format([F3], \"#\") FROM [Sheet1$]", conn);
                OleDbDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    string[] values = new string[3];                        
                    values[0] = reader.GetString(0);
                    values[1] = reader.GetString(1);
                    values[2] = reader.GetString(2);

                    DataRow dr = datatab.NewRow();
                    dr.ItemArray = values;
                    datatab.Rows.InsertAt(dr, i);
                    i++;
                }
            }
        }
    }

计划 2

private static DataTable GetInvoiceItems(string filepath)
{
        DataTable dt = new DataTable();
        string excelConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Excel=8.0;IMEX=1;HDR=NO;TypeGuessRows=1;ImportMixedTypes=Text\";
        using (OleDbConnection conn = new OleDbConnection(excelConString))
        {
            OleDbDataAdapter ada = new OleDbDataAdapter("SELECT [F1], [F2], [F3], [F4], [F5] FROM [Sheet1$]", conn);
            conn.Open();
            ada.Fill(dt);
        }
        return dt;
}

现在奇怪的是第一个程序在同一台电脑上完美运行运行,而第二个程序出现错误,指出电脑上没有可安装的 ISAM。有什么建议吗?

尽管你断言它们是相同的,但如果你仔细观察它们就不是了。查看您的连接字符串...

程序 1

"... Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=1;ImportMixedTypes=Text\"

节目 2

"... Excel=8.0;IMEX=1;HDR=NO;TypeGuessRows=1;ImportMixedTypes=Text\"

程序2的Excel 8.0中应该没有=