繁体   English   中英

打开预先存在的 excel 文件

[英]Opening a pre-existing excel file

我正在尝试从我计算机上的目录中打开一个预先存在的 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”。 检查文件名的拼写,并验证文件位置是否正确。

找到了一个对我有用的解决方案:

     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();

          }

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

试试这个,而不是:

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

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

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

暂无
暂无

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

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