无法使用Office.Interop和C#打开受密码保护的Excel文档

时间:2016-11-02 12:18:38

标签: c# office-interop

我有一个用Excel.Interop创建的Excel工作簿。我使用workbook.SaveAs(path, XlFileFormat.xlOpenXMLWorkbook, "password", "password", false, false)保存工作簿,然后需要关闭工作簿,因为新的worksheet将在稍后阶段附加,作为某种自动化的一部分。

当我尝试使用workbooks.Open(path, ReadOnly: false, Password: "password");再次打开工作簿时,该过程只是挂起,没有任何反应,即没有例外,没有任何结果。

以下是我正在尝试的内容的片段:

var excelApplication = new Microsoft.Office.Interop.Excel.Application();
var excelWorkbooks = excelApplication.Workbooks;
var workbook = new object();
//Append means that the a new sheet will be added to the existing workbook, thus the book needs to be opened first.
if (Append)
{
        Exception innerEx = null;
        try
        {
            excelWorkbooks.Open(ExcelOutputPath, ReadOnly: false, Password: "password");
        }
        catch
        {
            innerEx = new Exception("FileNotFound");
        };

}
//Lots of logic follows here
//and here
workbook.SaveAs(ExcelOutputPath, XlFileFormat.xlOpenXMLWorkbook, "password", "password", false, false);
        workbook.Close(0);
        Marshal.FinalReleaseComObject(workbook);
        workbook = null;

我错过了什么?

1 个答案:

答案 0 :(得分:0)

对于遇到同一问题的人,这是因为在尝试打开工作簿时需要为WriteResPassword参数指定相同的密码。这是必需的,因为工作簿最初保存时带有WriteResPassword