![](/img/trans.png)
[英]Why does Microsoft.Office.Interop.Excel corrupts my excel file?
[英]Why does Microsoft.Office.Interop.Excel require a full path name to open a file?
我一直在尝试在 Visual Studio 2012 中创建的 C# 应用程序中打开 Excel 文件。我终于发现我需要提供 ZC1D81AF5835844B4E9D936910DED8 的完整路径名,尽管它与 FDCZZ 可执行文件存在于同一个文件夹中, . 这是为什么?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application ExcelApp = new Excel.Application();
try
{
MessageBox.Show("Current directory: " + Directory.GetCurrentDirectory());
if (File.Exists("PLC01.xls"))
{
MessageBox.Show("Target file exists.");
}
else
{
MessageBox.Show("Target file does not exist.");
}
Excel.Workbook workbook = ExcelApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\PLC01.xls");
// Excel.Workbook workbook = ExcelApp.Workbooks.Open("PLC01.xls");
workbook.Close();
MessageBox.Show("Book opened and closed.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
这个版本有效。 但是,如果我注释掉对 Open() 的第一个调用并取消注释第二个,它只给出文件名而不是完整路径,我被告知找不到文件,即使“文件存在”消息框出现,验证了它的存在。
Directory.GetCurrentDirectory
-
"获取应用程序的当前工作目录"
这里的“应用程序”是您的 C# 可执行文件:启动的 Excel 应用程序实例未在与您的 C# 可执行文件相同的上下文中运行,因此它的“当前目录”不一定相同。
如果您知道完整路径,只需将其传递给 Excel - 无需尝试仅传递文件名。
仅供参考 - GetCurrentDirectory
可能不是找到 Excel 文件的最可靠方法
似乎是 Microsoft 的某种“隐藏”实现, Workbooks.Open()
需要完整路径。 老实说,这很奇怪,因为 VBA 中的这个很好用,而 Excel object 应该是一样的(除非我没记错):
Sub TestMe()
Dim wb As Workbook
Set wb = Workbooks.Open("test.xlsx")
End Sub
对于.NetFramework,我尝试在同一个文件夹中保存一个文件,其中Excel.exe
是:
C:\Program Files (x86)\Microsoft Office\Office14
我仍然收到找不到文件的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.