无法在C#中打开Excel文件

use*_*013 10 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我用"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.
Run Code Online (Sandbox Code Playgroud)

文件和路径确实存在:我已经从错误消息中复制了路径并将其粘贴到命令窗口中,并且文件在Excel中加载.该文件未锁定:Excel可以打开它,但我的程序不能,甚至直接重启后.我不想保存它,我试图打开它,所以最后一个选项是无关紧要的.

我无法理解为什么这段简单的代码不起作用.任何建议都将非常感激.

[编辑]我现在尝试从我的个人网络驱动器(M :)和USB记忆棒打开该文件.一切都无济于事.

该应用程序实际上是一个Windows服务,在本地系统帐户下运行并生成报告.它目前编写CSV报告,无任何访问问题.我现在正试图让它打开一个excel文件作为模板报告并填写各个字段.打开Excel文件时失败.我认为每个人都建议的管理员帐户选项是红鲱鱼,因为它可以写CSV文件,没问题.[/编辑]

--- Alistair.

use*_*013 33

我找到了以下页面:

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

在哪里说......

它不支持自动化办公产品UI.似乎Windows Server 2008和Excel 2007强制执行给定的语句.

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

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

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

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

我试过这个,它有点好吃!任何人都可以解释为什么需要它和任何缺点?

谢谢,

--- Alistair.

  • 刚刚第二次发现这篇文章,为我的旧 Windows 7 系统修复了它,然后在升级到 Windows 10 后不得不再次执行此操作。但是,在 Windows 10 中,我必须将“Everyone”用户的权限设置为对两个系统都具有完全访问权限文件夹才可以工作。 (2认同)