我的项目中有以下 C# 函数,该函数应该打开并返回现有的 Excel 工作簿对象:
Application _excelApp;
// ...
private Workbook OpenXL(string path, string filename)
{
try
{
if (_excelApp == null)
{
_excelApp = new Application();
}
Workbook workBook = _excelApp.Workbooks.Open(path + filename, // Name
0, // Do not update links
true); // Open read-only
return workBook;
}
catch (Exception e)
{
_excelApp = null;
throw new ArgumentException("Error opening " + path + filename, e);
}
}
但是当我使用“C:\”和“scratch.xlsx”运行它时,Open() 调用会抛出以下错误:
Microsoft Excel cannot access the file 'C:\scratch.xlsx'. There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
文件和路径确实存在:我已复制错误消息中的路径并将其粘贴到命令窗口中,文件将加载到 Excel 中。
该文件未锁定:Excel 可以正常打开它,但我的程序无法打开,即使是在重新启动后也是如此。
我不是想保存它,而是想打开它,所以最后一个选项无关紧要。
我不明白为什么这段简单的代码不起作用。任何建议将不胜感激。
[编辑]
我现在尝试从我的个人网络驱动器 (M:) 和 USB 记忆棒打开该文件。一切都无济于事。
该应用程序实际上是一个Windows服务,在本地系统帐户下运行并生成报告。它目前编写 CSV 报告,没有任何访问问题。我现在试图让它打开一个 Excel 文件作为模板报告并填写各个字段。这是打开Excel文件时失败的原因。我认为每个人都建议的管理员帐户选项只是转移注意力,因为它可以毫无问题地写入 CSV 文件。
[/编辑]
——阿利斯泰尔。