简体   繁体   English

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

[英]Is there a programmatically way for Excels “Protect Workbook”?

I'm moving some legacy code using Office Interop libraries to epplus, one thing I can't figure out is how to set a Workbook to ask the user on open the file to open it read only.我正在使用 Office 互操作库将一些遗留代码移动到 epplus,我不知道的一件事是如何设置工作簿以要求用户在打开文件时以只读方式打开它。 Like if the user clicks on File -> Info -> Protect Workbook -> Always Open Read-Only就像用户点击 File -> Info -> Protect Workbook -> Always Open Read-Only

I've tried to set the DocSecurity property stated here ( https://sno.phy.queensu.ca/~phil/exiftool/TagNames/OOXML.html ), but to no success.我尝试设置此处所述的 DocSecurity 属性( https://sno.phy.queensu.ca/~phil/exiftool/TagNames/OOXML.html ),但没有成功。 excelWorkBook.Properties.SetExtendedPropertyValue("DocSecurity", "2");

I also tried to add the following node to the workbookxml <fileSharing readOnlyRecommended="1"/>我还尝试将以下节点添加到工作簿<fileSharing readOnlyRecommended="1"/>

I even tried to compare the unzipped excel files protected, non protected, but there were too many changes.我什至尝试比较解压后的 excel 文件受保护,不受保护,但更改太多。

It can be done but it is not really straightforward.它可以做到,但它并不是很简单。 Setting DocSecurity can be done by generating the Workbook.Properties object.可以通过生成Workbook.Properties object 来设置DocSecurity But that is only half of it.但这只是其中的一半。 You also need to set the flag inside the Workbook itself which can only be done via XML manipulation.您还需要在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();
    }
}

Which will look like this:看起来像这样:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM