在檔案屬性中,可以設定諸多關于檔案的資訊,如創建時間、作者、單位、類別、關鍵詞、備注等摘要資訊以及一些自定義的檔案屬性,下面將通過C#程式來演示如何設定,同時對檔案內的已有資訊,也可以實作讀取或洗掉等操作,
示例大綱:
1. 添加檔案屬性
1.1 添加摘要資訊
1.2 添加自定義檔案資訊
2. 讀取檔案屬性
3. 洗掉檔案資訊
3.1 洗掉所有摘要資訊、自定義檔案屬性
3.2 洗掉指定摘要資訊、自定義檔案屬性
使用工具:Spire.XLS for .NET pack
獲取方法1:通過官網下載包,下載后,解壓檔案,安裝Bin檔案夾下的程式,安裝后,將安裝路徑下Bin檔案夾下的Spire.Xls.dll檔案添加參考至vs專案程式,如下所示:

獲取方法2:可通過Nuget下載,
C# 示例
【示例】添加檔案屬性
using Spire.Xls; using System; namespace AddProperties { class Program { static void Main(string[] args) { //加載Excel檔案 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //設定摘要 workbook.DocumentProperties.Author = "Mara"; workbook.DocumentProperties.Title = "摘要"; workbook.DocumentProperties.Keywords = "摘要,屬性"; workbook.DocumentProperties.Category = "展示檔案"; workbook.DocumentProperties.Company = "冰藍科技"; workbook.DocumentProperties.Comments = "請勿修改"; workbook.DocumentProperties.Subject = "測驗"; workbook.DocumentProperties.Manager = "Tom"; //設定自定義屬性 workbook.CustomDocumentProperties.Add("_MarkAsFinal", true); workbook.CustomDocumentProperties.Add("聯系電話", 81705109); workbook.CustomDocumentProperties.Add("更新時間", DateTime.Now); //保存檔案 workbook.SaveToFile("AddProperties.xlsx", FileFormat.Version2010); } } }
檔案屬性添加效果:

【示例2】讀取檔案資訊
using Spire.Xls; using Spire.Xls.Collections; using Spire.Xls.Core; using System; namespace ReadProperties { class Program { static void Main(string[] args) { //加載Excel檔案 Workbook wb = new Workbook(); wb.LoadFromFile("AddProperties.xlsx"); //獲取檔案屬性 Console.WriteLine("摘要資訊:"); Console.WriteLine("標題: " + wb.DocumentProperties.Title); Console.WriteLine("主題: " + wb.DocumentProperties.Subject); Console.WriteLine("作者: " + wb.DocumentProperties.Author); Console.WriteLine("管理者: " + wb.DocumentProperties.Manager); Console.WriteLine("公司: " + wb.DocumentProperties.Company); Console.WriteLine("類別: " + wb.DocumentProperties.Category); Console.WriteLine("關鍵字: " + wb.DocumentProperties.Keywords); Console.WriteLine("備注: " + wb.DocumentProperties.Comments); //獲取自定義屬性 Console.WriteLine("\n自定義屬性:"); for (int i = 0; i < wb.CustomDocumentProperties.Count; i++) { Console.WriteLine(wb.CustomDocumentProperties[i].Name + ": " + wb.CustomDocumentProperties[i].Value); } Console.Read(); } } }
檔案屬性讀取結果:

【示例3】洗掉檔案屬性
using Spire.Xls; namespace DeleteProperties { class Program { static void Main(string[] args) { //加載作業簿 Workbook workbook = new Workbook(); workbook.LoadFromFile("AddProperties.xlsx"); //洗掉摘要及自定義檔案屬性 workbook.DocumentProperties.Clear();//洗掉所有摘要資訊 workbook.CustomDocumentProperties.Clear();//洗掉所有自定義檔案屬性 //保存檔案 workbook.SaveToFile("DeleteProperties.xlsx", FileFormat.Version2013); /*//洗掉指定摘要及自定義檔案屬性 workbook.DocumentProperties.Author = "";//設定指定摘要資訊為空,洗掉摘要內容 workbook.CustomDocumentProperties.Remove("聯系電話");//洗掉指定名稱的自定義檔案屬性 workbook.SaveToFile("DeleteCustomDocumentProperties.xlsx", FileFormat.Version2013);*/ } } }
檔案屬性洗掉結果:

(本文完)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/116646.html
標籤:C#
上一篇:C#8.0 新增功能
