简体   繁体   English

如何使用 Open XML 密码保护 Excel 文档

[英]How to password protect an Excel document with Open XML

At the moment, I am creating a new Excel document with Open XML's SpreadsheetDocument class by passing a MemoryStream parameter.目前,我正在通过传递MemoryStream参数使用 Open XML 的SpreadsheetDocument类创建一个新的 Excel 文档。 I now need to set a password on this SpreadsheetDocument object, but what I have attempted does not seem to work.我现在需要在这个SpreadsheetDocument对象上设置密码,但我尝试的似乎不起作用。 The Excel document open's up without asking for a password.无需输入密码即可打开 Excel 文档。 Below is what I have tried so far ( mem being the MemoryStream parameter):以下是我到目前为止所尝试的( memMemoryStream参数):

using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(mem, true))
{
    foreach (var sheet in spreadsheet.WorkbookPart.WorksheetParts)
    {
        sheet.Worksheet.Append(new SheetProtection() { Password = "test" });
    }
}

I have also attempted the following with no success:我也尝试了以下但没有成功:

using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(mem, true))
{
    spreadsheet.WorkbookPart.Workbook.WorkbookProtection = new WorkbookProtection
    {
        LockStructure = true,
        LockWindows = true,
        WorkbookPassword = "test"
    }
}

What am I missing please?请问我错过了什么?

Openxml sheet protect Password has input Data type of "HexBinaryValue". Openxml 表保护密码的输入数据类型为“HexBinaryValue”。 so the input password as to be converted from string to hexa binary.所以输入密码要从字符串转换为十六进制二进制。

foreach (var worksheetPart in spreadsheet.WorkbookPart.WorksheetParts)
     {
         //Call the method to convert the Password string "MyPasswordfor sheet" to hexbinary type
         string hexConvertedPassword =  HexPasswordConversion("MyPasswordfor sheet");
//passing the Converted password to sheet protection
          SheetProtection sheetProt = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, Password = hexConvertedPassword };
          worksheetPart.Worksheet.InsertAfter(sheetProt,worksheetPart.Worksheet.Descendants<SheetData>().LastOrDefault());
worksheetPart.Worksheet.Save();
     }


/* This method will convert the string password to hexabinary value */
 protected string HexPasswordConversion(string password)
        {
            byte[] passwordCharacters = System.Text.Encoding.ASCII.GetBytes(password);
            int hash = 0;
            if (passwordCharacters.Length > 0)
            {
                int charIndex = passwordCharacters.Length;

                while (charIndex-- > 0)
                {
                    hash = ((hash >> 14) & 0x01) | ((hash << 1) & 0x7fff);
                    hash ^= passwordCharacters[charIndex];
                }
                // Main difference from spec, also hash with charcount
                hash = ((hash >> 14) & 0x01) | ((hash << 1) & 0x7fff);
                hash ^= passwordCharacters.Length;
                hash ^= (0x8000 | ('N' << 8) | 'K');
            }

            return Convert.ToString(hash, 16).ToUpperInvariant();
        }

Okay, so not entirely what I wanted to do, but I ended up dropping Open XML SDK and using Office.Interop assemblies to protect the document.好吧,这不完全是我想要做的,但我最终放弃了 Open XML SDK 并使用 Office.Interop 程序集来保护文档。 Reason for using Open XML in the first place, was because it seems that an Interop workbook cannot be opened with a stream, it requires an actual file.首先使用 Open XML 的原因是因为似乎无法使用流打开 Interop 工作簿,它需要一个实际文件。

You can try this:你可以试试这个:

using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(mem, true))
{
     foreach (var worksheetPart in spreadsheet.WorkbookPart.WorksheetParts)
     {
          SheetProtection sheetProt = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, Password = "test" };
          worksheetPart.Worksheet.InsertAfter(sheetProt, worksheetPart.Worksheet.Descendants<SheetData>().LastOrDefault());
     }
}

Con openXml es imposible pero existe utra libreria (Libre) tambien llamada EEPlues o (OfficeOpenXml) esta permite proteger con contraseña nuestro documento de excel sin necesidad de tener instalado Excel en la maquina. 禁止在超级图书馆(Libre)中使用坦帕拉姆语(OfficeOpenXml)禁止在任何情况下都可以使用永久性文件保护合同。 a diferencia de openxml no solo lo proteje de edición de archivo si no que tampoco deja abrir el archivo hasta que se le proporcione la Contraseña. OpenXML的独创性和档案管理的差异性,反之亦然。

ejemplo de un pequeño proyecto de prueba con OfficeOpenXml: OfficeOpenXml的pequeñoproyecto产品

using OfficeOpenXml;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new ExcelPackage
            using (ExcelPackage excelPackage = new ExcelPackage())
            {
                //Set some properties of the Excel document
                excelPackage.Workbook.Properties.Author = "VDWWD";
                excelPackage.Workbook.Properties.Title = "Title of Document";
                excelPackage.Workbook.Properties.Subject = "EPPlus demo export data";


                //Create the WorkSheet
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");

                //Add some text to cell A1
                worksheet.Cells["A1"].Value = "My first EPPlus spreadsheet!";
                //You could also use [line, column] notation:
                worksheet.Cells[1, 2].Value = "This is cell B1!";

                //Save your file
                FileInfo fi = new FileInfo(@"D:\PruebasXMLS\File.xlsx");
                excelPackage.SaveAs(fi, "123456789");
            }
        }
    }
}

REF: https://riptutorial.com/epplus 参考: https : //riptutorial.com/epplus

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

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