我有一个Excel文件,客户从他们的财务软件中提取并上传到我的网络应用程序。我需要通过ADO连接到文件并将其内容读入SQL数据库。
问题是来自财务软件的文件是一个独立的Excel工作表,而不是工作簿,因此我发现的任何软件(除Excel之外)都不能连接/打开它。无论我在OleDB连接器中使用什么连接字符串,我都无法使其工作。
如果我在Excel中打开文件,那么只需保存它,我就可以连接并正确读取。我编写了一些代码来自动化Excel,使用Office互操作,打开/保存文件,它可以工作,但我已经得出结论,这是在服务器上做的不好的做法,基于测试和阅读。
有谁知道我可以解决这个问题的方法?我见过一些第三方库,但它们非常昂贵。
提前致谢。
HttpPostedFile jvFile = FileUpload1.PostedFile;
string jvPath = Path.Combine(Server.MapPath("~"), Path.GetFileName(jvFile.FileName));
jvFile.SaveAs(jvPath);
string[] begins = {
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=",
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=",
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=",
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=",
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=",
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=",
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=",
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
};
string[] ends = {
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"",
";Extended Properties=\"Excel 8.0;HDR=Yes;\"",
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"",
";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"",
";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"",
";Extended Properties=\"Excel 12.0;HDR=YES\"",
";Extended Properties=\"Excel 12.0 Macro;HDR=YES\"",
";Extended Properties=\"text;HDR=Yes;FMT=Delimited\"",
";Extended Properties=\"text;HDR=Yes;FMT=Fixed\";"
};
for(int i = 0; i < begins.Length; i++)
{
StringBuilder sbExcelFileConnStr = new StringBuilder();
sbExcelFileConnStr.Append(begins[i]);
sbExcelFileConnStr.Append(jvPath);
sbExcelFileConnStr.Append(ends[i]);
OleDbConnection dbConn = new OleDbConnection(sbExcelFileConnStr.ToString());
string[] excelSheets = { };
try
{
dbConn.Open();
}
catch (Exception ex)
{
// fails here with "System.Data.OleDb.OleDbException:
// External table is not in the expected format."
//
//
}
}
我无法将问题文件放在任何地方,因为它包含敏感数据。