繁体   English   中英

从C#.Net(VS2010)打开Excel文件时出错

[英]Error in Opening the Excel file from C#.Net (VS2010)

我正在尝试使用C#(VS2010专业版)代码打开Excel文件(.xlsx)。 在执行/单步执行以下代码的最后两行时,我得到了(对我来说是不可追踪的)异常。 下面提到的是我用于打开现有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);   

另外,我还在代码的开始部分将此行包括在内。 另外,我已经从Project-> Add Reference(.NET选项卡)中添加了Microsoft.Office.Interop.Excel的引用。

 using Microsoft.Office.Interop.Excel;

谁能告诉我为什么我的代码失败/引发错误?

问候阿萨德

编辑* * ** * ** * ** * ** * ** * ** * ** * ** * *

这是我收到的消息/错误。 请注意,即使执行xlApp.Visible = ture行,代码也会失败。 错误是

无法将类型为“ Microsoft.Office.Interop.Excel.ApplicationClass”的COM对象转换为接口类型为“ Microsoft.Office.Interop.Excel._Application”。 此操作失败,因为具有以下错误的IID为“ {000208D5-0000-0000-C000-000000000046}”的接口在COM组件上的QueryInterface调用由于以下错误而失败:库未注册。 (来自HRESULT的异常:0x8002801D(TYPE_E_LIBNOTapped))。


尝试删除双反斜杠并改为写\\,或者您可以做的是

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/

@删除路径的任何问题。 代码与您的代码相似。 我只是用不同的方式重写它。 寻找System.Reflection,我改用System.Type。 还有一些将来的建议,如果您使用COM文件,请尝试在最后正确关闭它们。 **编辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM