C# 保護Excel文檔
說到保護excel文檔,我們首先想到的是密碼保護的方式,但excel與word有點不一樣,一般情況下,每個excel工作薄都或多或少地含有一定數量的工作表,因此保護excel文檔又分為了兩類,保護工作薄和保護工作表。在Excel 2013中,點擊左上角的FILE->Info就可以找到保護工作簿和保護當前工作表這兩個選項,通過它們給文件設置密碼保護,我們就可以保護文檔的隱私或防止別人隨意更改文件的內容。當然啦,方法可以有很多種,今天我主要寫的是如何使用C#編程的方式來保護Excel文檔。
第一部分:保護工作薄
詳細步驟:
步驟1:使用命名空間:
新建一個visual C#項目,添加引用並使用如下命名空間:
using Spire.Xls;
步驟2:創建一個新的Workbook對象並加載待保護的excel文檔。
Workbook book = new Workbook(); book.LoadFromFile(@"E:\Program Files\貨品情況統計表.xlsx");
步驟3:設置密碼保護工作薄。
book.Protect("abc-123");
第二部分:保護工作表
在該例中,保護工作表分為密碼保護和密碼及操作方式保護兩類。
密碼保護:設置密碼保護以后用戶不能對該worksheet做任何修改,相當於只讀。如果要修改,需要先輸入密碼取消保護。
密碼及操作方式保護:該方式允許用戶做部分操作修改。
下表是保護excel工作表的18種方式:
None |
Represents none flags. |
Object |
Protects shapes. |
Scenarios |
Protects scenarios. |
FormattingCells |
Allows users to format any cells on a protected worksheet. |
FormattingColumns |
Allows users to format any columns on a protected worksheet. |
FormattingRows |
Allows users to format any rows on a protected worksheet. |
InsertingColumns |
Allows users to insert columns on a protected worksheet. |
InsertingRows |
Allows users to insert rows on a protected worksheet. |
InsertingHyperlinks |
Allows users to insert hyperlinks on a protected worksheet. |
DeletingColumns |
Allows users to delete columns on a protected worksheet. |
DeletingRows |
Allows users to delete rows on a protected worksheet. |
LockedCells |
Protects locked cells. |
Sorting |
Allows users to sort on a protected worksheet. |
Filtering |
Allows users to set filters on a protected worksheet. |
UsingPivotTable |
Allows users to use pivot table reports on a protected worksheet. |
UnlockedCells |
Protects users interface, but not macros. |
Contents |
Represents all flags. |
All |
Represents default protection. |
步驟4:與保護工作薄類似,獲取需要保護的工作表,並給它設置密碼及操作保護(這里我選擇的是第一個工作表及密碼保護的方式)。
Worksheet sheet = book.Worksheets[0]; sheet.Protect("def-345", SheetProtectionType.None);
步驟5:保存並重啟文檔。
book.SaveToFile("ProtectExcel.xlsx", ExcelVersion.Version2010); System.Diagnostics.Process.Start("ProtectExcel.xlsx");
保護工作薄的效果圖:
保護工作表的效果圖:
全部代碼:
using Spire.Xls; namespace Protect_Excel_Document { class Program { static void Main(string[] args) { //Load Workbook Workbook book = new Workbook(); book.LoadFromFile(@"E:\Program Files\貨品情況統計表.xlsx"); //Protect Workbook book.Protect("abc-123"); //Protect Worksheet with Password Worksheet sheet = book.Worksheets[0]; sheet.Protect("def-345", SheetProtectionType.None); //Save and Launch book.SaveToFile("ProtectExcel.xlsx", ExcelVersion.Version2010); System.Diagnostics.Process.Start("ProtectExcel.xlsx"); } } }
總結:
從上面的例子中可以看出,用這種方式來保護excel文檔其實並不難,這里我使用的是Free Spire.XLS,而且在設置密碼保護excel工作薄的同時也設置了密碼保護excel工作表,在實際應用中可以根據不同的需求來選擇保護對象。
感謝您的觀看!