简体   繁体   English

无法在 C# 项目中打开绑定的 excel 文件

[英]Can't open bound excel file in C# project

I have an excel file in my project which is listed as resource.我的项目中有一个 excel 文件,它被列为资源。

Now I try to open it with a button click like this:现在我尝试用这样的按钮点击打开它:

private void Button_Click_Blist(object sender, RoutedEventArgs e)
{
    Excel.Application xl = new Excel.Application();
    Excel.Workbook wb = xl.Workbooks.Open("Blist.xlsx");
}

My problem is that it says that it can't find the file and throws this exception:我的问题是它说它找不到文件并抛出这个异常:

System.Runtime.InteropServices.COMException System.Runtime.InteropServices.COMException

We couldn't find 'Blist.xlsx'.我们找不到“Blist.xlsx”。 Was the object perhaps moved, renamed, or deleted?对象是否可能被移动、重命名或删除?

This code uses OLE Automation to start Excel and tell it to open a file in the relative path Blist.xlsx .此代码使用 OLE 自动化来启动 Excel 并告诉它在相对路径Blist.xlsx打开一个文件。 The executable in this case is Excel , not your own application.在这种情况下,可执行文件是Excel ,而不是您自己的应用程序。 The relative path will be resolved using Excel's working directory.将使用 Excel 的工作目录解析相对路径。

To avoid this problem, pass the absolute file path to Excel :为避免此问题,请将绝对文件路径传递给 Excel :

var fullPath=Path.GetFullPath("Blist.xlsx");
Excel.Workbook wb = xl.Workbooks.Open(fullPath);

Another possibility, which gives no control of (or dependency on) Excel, is to just "start" the file with Process.Start , eg :另一种不控制(或依赖)Excel 的可能性是仅使用Process.Start来“启动”文件,例如:

Process.Start("Blist.xlsx");

Or或者

var fullPath=Path.GetFullPath("Blist.xlsx");
Process.Start(fullPath);

The Windows Shell will find the application that can open this document based on its extension and start it, passing the file path as an argument. Windows Shell 将根据其扩展名找到可以打开此文档的应用程序并启动它,将文件路径作为参数传递。 This can start Excel, Libre Calc or any other application registered to open this particular file extension.这可以启动 Excel、Libre Calc 或任何其他注册的应用程序以打开此特定文件扩展名。

So I tried this and apparently the .Open() method some extra complexety with relative paths (see @PanagiotisKanavos comment).所以我尝试了这个,显然.Open()方法与相对路径有些额外的复杂性(见@PanagiotisKanavos 评论)。 You can make a work around, by getting the current directory path, and pre-pending it, giving the absolute path of the file:您可以通过获取当前目录路径并预先挂起它,给出文件的绝对路径来解决这个问题:

string filename = "Blist.xlsx";
string currentPath = Directory.GetCurrentDirectory();

var xl = new Microsoft.Office.Interop.Excel.Application();            
var wb = xl.Workbooks.Open(currentPath + "\\" + filename);

xl.Visible = true;

However, you should (almost) never use hardcoded file names in your code.但是,您应该(几乎)永远不要在代码中使用硬编码的文件名。 So the above solution is just an example, not something to copy into production code...所以上面的解决方案只是一个例子,而不是复制到生产代码中的东西......

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

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