gpt4 book ai didi

c# - 无法在 C# 中打开 Excel 文件

转载 作者:可可西里 更新时间:2023-11-01 08:50:53 25 4
gpt4 key购买 nike

我的项目中有以下 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 文件。[/编辑]

--- 阿利斯泰尔。

最佳答案

我找到了以下页面:

http://social.msdn.microsoft.com/Forums/en-US/b81a3c4e-62db-488b-af06-44421818ef91/excel-2007-automation-on-top-of-a-windows-server-2008-x64

哪里说的...

it’s not supported to automate office products UI less. It seems that Windows Server 2008 and Excel 2007 enforce the given statement.

然后提问者准确描述了我所处的 Windows 服务无法打开 Excel 文件的情况,尽管命令行程序中的相同代码没有问题。

响应建议创建以下文件夹:

Windows 2008 Server x64: C:\Windows\SysWOW64\config\systemprofile\Desktop

Windows 2008 Server x86: C:\Windows\System32\config\systemprofile\Desktop

我试过了,效果很好!任何人都可以解释为什么需要它以及任何缺点吗?

谢谢,

--- 阿利斯泰尔。

关于c# - 无法在 C# 中打开 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17530797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com