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

标签 c# excel-interop

我的项目中有以下 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/

相关文章:

c# - 如何将值设置为二维 Excel 范围?

c# - 从 foreach 循环获取当前索引

javascript - 单击按钮时运行 Controller 方法 MVC4 C#

C# 修改字符串

c# - 运算符 '==' 不能应用于类型 'System.DBNull' 和 'Int' 的操作数

c# - 阻止 "Formulas have been recalculated, save"对话框?

c# - 找不到windows服务(刚刚安装)

c# - 如何绑定(bind)可观察集合以查看可观察集合中存在的项目数?

.net - 公式与 Excel 互操作

.net - System.Runtime.InteropServices.COMException (0x800A03EC)