从c#打开Excel文件时出错.净(VS2010)
本文关键字:VS2010 出错 打开 Excel 文件 | 更新日期: 2023-09-27 18:16:53
我试图使用c# (VS2010专业)代码打开excel文件(.xlsx)。当执行/单步执行下面代码的最后2行时,我得到一个(无法追踪的,对我来说)异常。下面提到的是我打开现有excel文件的代码。
string tesfile = "C:''Users''AWaheed3''Desktop''1.xlsx";
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Open(tesfile, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
我还在代码的开始处包含了下面一行。此外,我已经添加了参考的Microsoft.Office.Interop.Excel从项目->添加参考(。净选项卡)
using Microsoft.Office.Interop.Excel;
谁能告诉为什么我的代码失败/抛出一个错误?
的问候Asad
编辑* * * * * * * * * * * * * * * * * * * * * * * * * * *
这是我收到的消息/错误。注意,即使在执行xlApp时,代码也会失败。可见=真实线。错误是
无法强制转换类型为"Microsoft.Office.Interop.Excel"的COM对象。到接口类型"Microsoft.Office.Interop.Excel._Application"的ApplicationClass。此操作失败,因为对IID为"{000208D5-0000-0000-C000-000000000046}"的接口的COM组件的QueryInterface调用失败,原因是以下错误:库未注册。(Exception from HRESULT: 0x8002801D (type_e_libnoregigied)).
尝试删除双反斜杠并将其改为'或者您可以这样做
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Workbook xls = null;
try
{
excel = new Microsoft.Office.Interop.Excel.Application();
object missing = Type.Missing;
object trueObject = true;
try
{
excel.Visible = false; // or true
excel.DisplayAlerts = false;
}
catch(Exception e)
{
Console.WriteLine("-------Error hiding the application-------");
Console.WriteLine("Occured error might be: " + e.StackTrace);
}
xls = excel.Workbooks.Open(excelFile, missing, trueObject, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
//xls = excel.Workbooks.Open(@"file.xls", missing, trueObject, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
}
catch (Exception ex)
{
MessageBox.Show("Error accessing Excel document.'n'n" +
ex.Message);
}
// Must be surrounded by try catch to work.
// http://naimishpandya.wordpress.com/2010/12/31/hide-power-point-application-window-in-net-office-automation/
@消除了路径的任何问题。代码当然与您的类似。我只是用不同的方式重写了一下。寻找系统。反射,我用系统。类型。对于将来的一些建议,如果您使用COM文件,请尝试在最后正确关闭它们。* *编辑。