首页 > 解决方案 > C# 无法从只读 Excel 文件中读取

问题描述

我的电脑上有一个文件夹,其中包含多个都标记为只读的 Excel 电子表格。该文件夹通过 OneDrive 同步到我公司的 Sharepoint。

当我尝试通过 Microsoft.Office.Interop.Excel 以编程方式从其中一张表中读取数据时,我不断收到You cannot use this command on a protected sheet错误消息。

这是我用来打开文件的代码:

public ExcelReader(String filePath)
{
        this.filePath = filePath;
        FileName = filePath.Substring(filePath.LastIndexOf("\\")+1);
        app = new Excel.Application();
        app.DisplayAlerts = false;
        workbook = app.Workbooks.Open(filePath, false, true); //open in read only
}

public void openSheet(String sheet)
{
        SheetName = sheet;
        worksheet = workbook.Sheets[sheet];
        Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
        ColumnsTotal = last.Column;
        RowsTotal = last.Row;
}

引发异常的行是Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);.

我认为,由于我明确告诉工作簿以只读模式打开,并且由于我从不修改这些文件的内容,因此文件是只读的这一事实不应该成为问题。

我在这里做错了什么?如何在不取消保护的情况下读取这些文件的内容(出于安全原因,我不能这样做)?

标签: c#excel

解决方案


推荐阅读