我有一个C#程序,可以打开一个Excel文件,读取数据,并将其导出为其他格式的Excel文件。
当我要打开的Excel文件为* .xlsx时,程序运行正常,但是当我要打开的Excel文件为* .xlsx时,出现异常(如下)。这两个文件都在Excel中打开,只有当我尝试在C#程序中打开* .xlsx文件时,才会出现异常。
代码
private List readExcel(OleDbConnection connection, string filePath, ExcelReportType rptType)
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
try
{
//Open connection to spreadsheet
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
//open excel and open the workbook
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(filePath); //exception is thrown here
//more code to read the contents of the workbook
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
finally
{
if (workbook != null)
{
workbook.Close();
}
}
}
这里是创建连接的代码,该代码在调用readExcel()之前被调用,并且不会产生任何异常。
private OleDbConnection openExcelConnection(OleDbConnection connection, string filePath)
{
try
{
//establish connection to spreadsheet
connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");
}
catch (Exception e)
{
//code to handle exception
}
return connection;
}
异常消息
“ Excel无法打开文件'51 .0.19.01(export).xlsx',因为文件格式或文件扩展名无效。请验证文件未损坏,并且文件扩展名与文件格式匹配。 “
堆栈跟踪
Microsoft.Office.Interop.Excel.Workbooks.Open中的(字符串文件名,对象更新链接,对象只读,对象格式,对象密码,对象WriteResPassword,对象IgnoreReadOnlyRecommended,对象起源,对象定界符,对象可编辑,对象通知,对象转换器,对象AddToMru,对象本地,对象CorruptLoad)
我尝试过的事情