外部表格不是预期的格式OLEDB 12.0与Excel 2007

时间:2016-08-09 08:11:47

标签: c# excel oledb

我开发了一个WEB API服务,当用户上传时,它将从excel文件中读取数据。

我使用OLEDB如下:

if (Path.GetExtension(filePath).ToUpper() == ".XLS")
{
    oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;\"");
}
else
{
    oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";");
}
oledbConn.Open();  //Exception thrown at here
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
cmd.Connection = oledbConn;
cmd.CommandText = "SELECT DISTINCT(["+mo_field+"]),["+model_field+"],["+content_filed+"] FROM ["+ecn_field+"] WHERE ["+mo_field+"] IS NOT NULL AND ["+active_field+"] ='1'";
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds,"NewMO");

但它抛出异常:

  

外部表格不是预期的格式

我的服务器安装了Window Server 2012 RC2 64位,所以我尝试安装Microsoft Database Engine 2010重新分发32位/ 64位。和Microsoft Database Engine 2007 32位。但它仍然无效。我搜索了3天,每个帖子都说安装Microsoft Database Engine会修复错误。此代码适用于Office 2010/2013。

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

var ds = new DataSet();
var da = new OleDbDataAdapter("SELECT DISTINCT(["+mo_field+"]),["+model_field+"],["+content_filed+"] FROM ["+ecn_field+"] WHERE ["+mo_field+"] IS NOT NULL AND ["+active_field+"] ='1'", 
                              "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1'");
da.Fill(ds,"NewMO");

并通过在Excel中打开文件确保该文件确实是Excel文件。

<强>更新

以下是从https://www.connectionstrings.com/excel/尝试

的更多连接字符串
foreach (var cs in new string[] {
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=YES';",
    "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0; HDR = Yes; IMEX = 1';" })
    try { using (var con = new System.Data.OleDb.OleDbConnection(cs)) con.Open(); MessageBox.Show(cs + " worked bro!!"); } catch { }

foreach (var cs in new string[] {
    "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + filePath + ";",
    "Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=" + filePath + ";",
    "Driver={Microsoft Excel Driver (*.xls)};Dbq=" + filePath + ";ReadOnly=0;"})
    try { using (var con = new System.Data.Odbc.OdbcConnection(cs)) con.Open(); MessageBox.Show(cs + " worked bro!!"); } catch { }