是否有Excel的“保护工作簿”编程方式?

问题描述 投票:-2回答:1

我正在使用Office Interop库将一些旧代码移至epplus,我不知道的一件事是如何设置工作簿以要求用户打开文件以只读方式打开它。就像用户单击文件->信息->保护工作簿->始终以只读方式打开

我尝试设置此处说明的DocSecurity属性(https://sno.phy.queensu.ca/~phil/exiftool/TagNames/OOXML.html),但没有成功。 excelWorkBook.Properties.SetExtendedPropertyValue("DocSecurity", "2");

我还试图将以下节点添加到workbookxml <fileSharing readOnlyRecommended="1"/>

我什至试图比较受保护的,未受保护的,未压缩的excel文件,但是更改太多。

c# epplus
1个回答
0
投票

可以完成,但并不是很简单。可以通过生成DocSecurity对象来设置Workbook.Properties。但这只是其中的一半。您还需要在Workbook本身内部设置标志,这只能通过XML操作来完成。

[TestMethod]
public void DocSecurity_Test()
{
    //https://stackoverflow.com/questions/58335624/is-there-a-programmatically-way-for-excels-protect-workbook
    var fi = new FileInfo(@"c:\temp\DocSecurity_Test.xlsx");
    if (fi.Exists)
        fi.Delete();

    using (var package = new ExcelPackage(fi))
    {
        //Create a simple workbook
        var workbook = package.Workbook;
        var worksheet = workbook.Worksheets.Add("Sheet1");
        worksheet.Cells["A1"].Value = "Test";

        //Extended properties is a singleton so reference it to generate the app.xml file
        //needed and add the security setting
        var extProps = workbook.Properties;
        extProps.SetExtendedPropertyValue("DocSecurity", "2");

        //Also need to tell the workbook itself but can only do it via XML
        var xml  = workbook.WorkbookXml;
        var att = xml.CreateAttribute("readOnlyRecommended");
        att.Value = "1";

        const string mainNs = @"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
        var fileSharing = xml.CreateElement("fileSharing", mainNs);
        fileSharing.Attributes.Append(att);

        //Element must be at the beginning of the tree
        xml.DocumentElement.PrependChild(fileSharing);
        package.Save();
    }
}

哪个看起来像这样:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.