1

我的应用程序基本上接受一个 excel 文件并将数据上传到我的数据库,该数据库曾经使用以下代码与 Excel 2010 完美配合。但是,我们将系统更新到 Excel 2016 并且由于某种原因停止工作,请您协助我对我的代码进行哪些更新。

这是当前要连接的代码:

 openFileDialog1.ShowDialog();
            var fileName = string.Format(openFileDialog1.FileName);

            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileName, 1, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, null, false);

var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + "; Extended Properties=Excel 12.0;", fileName);
4

3 回答 3

0

这可能是因为安装破坏或更改了ACE已注册驱动程序的现有版本。ACE可能需要重新安装才能使其再次工作。请注意,如果版本更改,您的连接字符串可能需要更新

您应该能够通过注册表查看机器上可用的版本:

HKCR\Microsoft.ACE.OLEDB.XX.0
于 2018-09-01T14:25:28.320 回答
0

我没有 Excel 2016,所以我无法对其进行测试,但这应该可以。

private DataTable ReadExcelFile(string sheetName, string path)
{
    using (OleDbConnection conn = new OleDbConnection())
    {
        DataTable dt = new DataTable();
        string Import_FileName = path;
        string fileExtension = Path.GetExtension(Import_FileName);
        if (fileExtension == ".xls")
        {
            conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
        }
        if (fileExtension == ".xlsx")
        {
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
        }
        using (OleDbCommand comm = new OleDbCommand())
        {
            comm.CommandText = "Select * from [" + sheetName + "$]";
            comm.Connection = conn;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = comm;
                da.Fill(dt);
                return dt;
            }

        }
    }
}

另外,考虑这样做。

OleDb.OleDbConnectionStringBuilder Builder = new OleDb.OleDbConnectionStringBuilder();
Builder.DataSource = "test.xlsx";
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.Add("Extended Properties", "Excel 12.0;HDR=Yes;IMEX=1");
Console.WriteLine(Builder.ConnectionString);

最后,查看有关Excel 连接字符串的网站。

于 2016-06-20T20:43:53.457 回答
0

我在一个相关问题中回答了这个问题,这是由于升级到 Office 16: oledb connection string for excel 2016 in c#

于 2016-06-23T16:31:10.490 回答