错误,而使用C#代码打开一个Excel工作簿 [英] Error while opening an excel workbook using C# code
问题描述
我试图打开一个Excel工作簿,并试图在它得到一个工作表。从HRESULT Excelapp.workbooks.Open行抛出一个异常,如
I'm trying to open an excel workbook and trying to get a worksheet in it. Excelapp.workbooks.Open line is throwing an Exception as
System.Runtime.InteropServices.COMException:0x800A03EC在Microsoft.Office.Interop .Excel.Workbooks.Open
System.Runtime.InteropServices.COMException from HRESULT: 0x800A03EC at Microsoft.Office.Interop.Excel.Workbooks.Open
下面是我的代码:
Excel.Application excelApp = new Excel.ApplicationClass();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(strWBPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, Type.Missing, true);
StrWbPath是我的Excel位置。我指的是2007年Excel和补充的12.0.0.0版本的Microsoft.Office.Interop.Excel。
StrWbPath is my Excel location. I'm refering to 2007 excel and added Microsoft.office.interop.excel of version 12.0.0.0.
推荐答案
(对不起,回答这个老问题,但它是谷歌的结果#1这个问题,正确的答案是丢失)。
(Sorry for answering this old question, but it's google result #1 for this problem and the correct answer is missing).
因为Excel认为工作簿已损坏时,会出现错误。当打开Excel文件,最后一个参数告诉Excel如何处理这种情况。通 Microsoft.Office.Interop.Excel.XlCorruptLoad.xlExtractData code>来指示它检索数据(这将打开一个弹出窗口告诉用户的Excel试图提取该文件中的数据已损坏)。
The error occurs because excel thinks the Workbook has been corrupted. When opening the Excel file, the last parameter tells excel how to handle this situation. Pass Microsoft.Office.Interop.Excel.XlCorruptLoad.xlExtractData
to instruct it to retrieve the data (This will open a popup telling the user excel tried to extract the data if the file is corrupted).
不过,我注意到这个问题,也可以,如果你试图打开工作簿具有不同的区域设置比你的Excel文件(保存在机器上造成的用另一种语言设置)或不具有EN-US区域设置。
However, I noticed this problem can also be caused if the workbook you are trying to open has a different locale than your excel (was saved on a machine using another language setting) OR your system not having the en-us locale set.
虽然这是愚蠢至极,很容易克服。对我来说,解决方案是当前语言环境中打开文件之前,只是设置为EN-US:
While this is extremely stupid, it's easy to overcome. For me the solution was to just set the current locale to en-us before opening the file:
static System.Globalization.CultureInfo oldCI;
oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
xlWorkBook = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlExtractData);
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
信贷去的此页面
这篇关于错误,而使用C#代码打开一个Excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!