我正在使用Open XML SDK創建Excel文件。使用Open XML SDK進行Excel文件密碼保護
我想用密碼保護它們。
無論如何,您是否知道通過使用Open XML SDK來保護帶密碼的excel文件?
我知道「com」對象的方式來保護它們,但它不適合我的應用程序。我需要使用Open XML SDK或其他方式來保護文件。
我正在使用Open XML SDK創建Excel文件。使用Open XML SDK進行Excel文件密碼保護
我想用密碼保護它們。
無論如何,您是否知道通過使用Open XML SDK來保護帶密碼的excel文件?
我知道「com」對象的方式來保護它們,但它不適合我的應用程序。我需要使用Open XML SDK或其他方式來保護文件。
通過打開xml,可以創建用於保護woorkbook或工作表的Excel密碼。
下面的代碼示例是文森特(http://spreadsheetlight.com/about/)(https://stackoverflow.com/users/12984/vincent-tan)的建議(我再次感謝他很多:)
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docname,true))
{
foreach (var worksheet in spreadSheet.WorkbookPart.WorksheetParts)
{
worksheet.Worksheet.Append(new SheetProtection(){ Password = 「CC」});
// add this in case it still doesn’t work. This makes sure the data is saved.
//worksheet.Worksheet.Save();
}
}
如果你有一個圖表或東西然後
下面的代碼示例是建議文森特(http://spreadsheetlight.com/about/)(https://stackoverflow.com/users/12984/vincent-tan)的(再次感謝他很多:)
bool bFound;
OpenXmlElement oxe;
SheetProtection prot;
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open("OtoPark.xlsx", true))
{
foreach (var worksheet in spreadSheet.WorkbookPart.WorksheetParts)
{
prot = new SheetProtection();
prot.Password = "CC";
// these are the "default" Excel settings when you do a normal protect
prot.Sheet = true;
prot.Objects = true;
prot.Scenarios = true;
// Open up Excel and do a password protect yourself and use the
// Productivity Tool to see the property values of the resulting Excel file.
// Consider not using the Password property and use:
//prot.AlgorithmName = "SHA-512";
//prot.HashValue = "somehashvaluebythealgorithm";
//prot.SaltValue = "somesalt";
//prot.SpinCount = 100000;
bFound = false;
oxe = worksheet.Worksheet.FirstChild;
foreach (var child in worksheet.Worksheet.ChildElements)
{
// start with SheetData because it's a required child element
if (child is SheetData || child is SheetCalculationProperties)
{
oxe = child;
bFound = true;
}
}
if (bFound)
{
worksheet.Worksheet.InsertAfter(prot, oxe);
}
else
{
worksheet.Worksheet.PrependChild(prot);
}
worksheet.Worksheet.Save();
}
}
這些方法可以保護任何用戶無法意外更改數據。但是,如果你不希望出現這種情況不知道密碼才能看到數據的任何用戶,那麼你可以使用以下庫:
http://dotnetzip.codeplex.com/
你必須保護的壓縮文件密碼,通過包含您excel.xlsx文件使用dotnetzip庫。
一個例子:
public void RNCreateZipFile(string ExcelDocName,string PassWord, string ZipDocName)
{
// create a zip
using (var zip = new ZipFile())
{
zip.Password = PassWord;
zip.AddFile(ExcelDocName, "");
zip.Save(ZipDocName);
}
}