在C#中使用OLEDB连接字符串连接Excel 2016

8

我一直在尝试使用C#访问2016年的MS Excel文件,但是连接字符串只适用于2013 MS Excel。

我的当前连接字符串:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx; Extended Properties="Excel 12.0 Xml;HDR=YES";

是否有适用于MS Excel 2016的修改后的oledb连接字符串?

2个回答

13

我在本地安装Office 13后通过Office 365升级到Office 16后出现了这个问题。我遇到了这个异常:The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

我无法找到一种方法通过office 365安装过程来安装驱动程序。

我不得不安装https://www.microsoft.com/en-us/download/details.aspx?id=13255 - x64版本无法解决问题,必须使用32位版本。

我的App.config中的连接字符串

    <add key="Excel07ConnectionString" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

使用它的代码:
            var excelConnectionString = ConfigurationSettings.GetExcelConnection(fileLocation);
            var dataTable = new DataTable();

            using (var excelConnection = new OleDbConnection(excelConnectionString))
            {
                excelConnection.Open();
                var dataAdapter = new OleDbDataAdapter("SELECT * FROM [Users$]", excelConnection);
                dataAdapter.Fill(dataTable);
                excelConnection.Close();
            }
            Console.WriteLine("OpenExcelFile: File successfully opened:" + fileLocation);
            return dataTable;

1
重要的是提到了x64位。这就是我的问题所在。 - celerno
1
还有值得注意的是:如果您安装了 64 位的 Excel,要安装32位引擎,您需要添加 /passive 选项! - TaW

5
这对我很有效:
private string ExcelConnection(string fileName)
{
    return @"Provider=Microsoft.Jet.OLEDB.4.0;" +
           @"Data Source=" + fileName + ";" +
           @"Extended Properties=" + Convert.ToChar(34).ToString() +
           @"Excel 8.0" + Convert.ToChar(34).ToString() + ";";
}

1
它对我也起作用了。虽然我不明白为什么。那不是一个旧的连接吗?它怎么能在新的Excel上工作呢?但还是谢谢你。 - user890332

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接