【问题标题】:Opening a pre-existing excel file打开预先存在的 excel 文件
【发布时间】:2016-03-25 14:09:57
【问题描述】:

我正在尝试从我的计算机上的目录中打开一个预先存在的 excel 文件。但是,当我的代码到达 Workbooks.Open 方法时,我收到了 COMexception。我不确定我做错了什么。任何帮助表示赞赏。

using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Xml;

namespace Excel_Create
{
    class Program
    {

        static void Main(string[] args)
        {


            string mySheet = @"‪‪‪‪C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls";
              Excel.Application xlApp = new Excel.Application();
              xlApp.Visible = true;


              if (xlApp == null)
              {
                  MessageBox.Show("Excel is not properly installed!!");
                  return;
              }



         Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(mySheet,
          0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
          true, false, 0, true, false, false              );

        }
    }
}

以下是异常的含义:Excel_Create.exe 中发生了“System.Runtime.InteropServices.COMException”类型的未处理异常

其他信息:找不到“C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls”。检查文件名的拼写,并验证文件位置是否正确。

【问题讨论】:

  • 如果文件在那里,它是否在另一个应用程序(例如 Excel)中打开?
  • 是的,它就在那里。这是一个 Microsoft Excel 97-2003 工作表 (.xls),保存在:C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls 从属性视图复制/粘贴文件。

标签: c# excel automation excel-interop


【解决方案1】:

找到了适合我的解决方案:

     var mySheet = Path.Combine(Directory.GetCurrentDirectory(), "Sample.xlsx");
          Excel.Application xlApp = new Excel.Application();
          xlApp.Visible = true;


          if (xlApp == null)
          {
              MessageBox.Show("Excel is not properly installed!!");
              return;
          }

          try
          {
              Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(mySheet);

          }
          catch(Exception ex)
          {
              xlApp.Quit();

          }

【讨论】:

    【解决方案2】:

    我认为您的文件路径中的空格有问题。

    试试这个吧:

    string mySheet = @"""C:\Users\Danny\Documents\Visual Studio 2013\Projects\MWS\MWS\bin\Debug\csharp-Excel.xls""";
    

    【讨论】:

    • 没有工作复制并粘贴你的代码在我的并运行 - 仍然是同样的错误
    • @DanielTaki 你确定文件扩展名吗?较新版本的 Excel 使用 .xlsx 而不是 .xls。你确定是.xls
    • 不,我不确定 Excel 是否来自 Microsoft Office 2010。我是否应该尝试将文件另存为 .xlsx 并尝试再次运行程序?
    • 我不知道这是否是相关信息,但我可能有一个破解的副本 excel
    【解决方案3】:

    你可以试试这个......

    Excel.Application excelApp = 
    System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2019-08-02
      • 2019-12-29
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多