Excel 文档属性(也称为元数据)能够提供有关文件内容、作者以及创建和修改历史等信息,有助于更高效地管理、分类和检索 Excel 文件。除了向 Excel 文件添加文档属性外,本文还将介绍如何在 C# 中读取或删除 Excel 文档属性。
开始之前,需要在 .NET 项目中添加相应的 Excel 处理库引用。您可以下载所需的 DLL 文件并手动添加到项目中,也可以通过 NuGet 进行安装。
PM> Install-Package Spire.XLSExcel 文档属性主要分为以下两类:
借助 Excel 处理库,可以同时读取 Excel 文件中的标准文档属性和自定义文档属性。具体步骤如下:
完整示例代码如下:
using Spire.Xls;
using Spire.Xls.Collections;
using Spire.Xls.Core;
using System.IO;
using System.Text;
namespace GetExcelProperties
{
class Program
{
static void Main(string[] args)
{
{
//创建 Workbook 实例
Workbook workbook = new Workbook();
//加载示例 Excel 文件
workbook.LoadFromFile("Budget Template.xlsx");
//创建 StringBuilder 实例
StringBuilder sb = new StringBuilder();
//获取所有标准文档属性的集合
BuiltInDocumentProperties standardProperties = workbook.DocumentProperties;
//获取指定的标准属性并追加到 StringBuilder 实例中
sb.AppendLine("Standard Document Properties:");
sb.AppendLine("Title: " + standardProperties.Title);
sb.AppendLine("Subject: " + standardProperties.Subject);
sb.AppendLine("Category: " + standardProperties.Category);
sb.AppendLine("Keywords: " + standardProperties.Keywords);
sb.AppendLine("Comments: " + standardProperties.Comments);
sb.AppendLine();
//获取所有自定义文档属性的集合
ICustomDocumentProperties customProperties = workbook.CustomDocumentProperties;
sb.AppendLine("Custom Document Properties:");
//遍历集合
for (int i = 0; i < customProperties.Count; i++)
{
//获取每个自定义文档属性的名称和值,并追加到 StringBuilder 实例中
string name = customProperties[i].Name;
string value = customProperties[i].Value.ToString();
sb.AppendLine(name + ": " + value);
}
//将 StringBuilder 实例中的内容写入文本文件
File.WriteAllText("GetExcelProperties.txt", sb.ToString());
}
}
}
}您可以通过将标准文档属性的值设置为空来删除 Excel 文件中的标准文档属性。对于自定义文档属性,则可以使用 ICustomDocumentProperties.Remove() 方法将其删除。具体步骤如下:
完整示例代码如下:
using Spire.Xls;
using Spire.Xls.Collections;
using Spire.Xls.Core;
namespace DeleteExcelProperties
{
class Program
{
static void Main(string[] args)
{
{
//创建 Workbook 实例
Workbook workbook = new Workbook();
//加载示例 Excel 文件
workbook.LoadFromFile("Budget Template.xlsx");
//获取所有标准文档属性的集合
BuiltInDocumentProperties standardProperties = workbook.DocumentProperties;
//将每个标准文档属性的值设置为空
standardProperties.Title = "";
standardProperties.Subject = "";
standardProperties.Category = "";
standardProperties.Keywords = "";
standardProperties.Comments = "";
//获取所有自定义文档属性的集合
ICustomDocumentProperties customProperties = workbook.CustomDocumentProperties;
//遍历集合
for (int i = customProperties.Count -1; i >=0; i--)
{
//根据名称从集合中删除每个自定义文档属性
customProperties.Remove(customProperties[i].Name);
}
//保存结果文件
workbook.SaveToFile("DeleteDocumentProperties.xlsx", ExcelVersion.Version2016);
}
}
}
}本文介绍了如何在 C# 中删除 Excel 文件的标准文档属性和自定义文档属性。对于标准文档属性,可以通过将标题、主题、类别、关键词和备注等属性值设置为空来清除相关信息;对于自定义文档属性,则可以遍历属性集合,并根据属性名称逐个删除。
通过这种方式,您可以有效移除 Excel 文件中的元数据,减少不必要的信息暴露,保护文档隐私,并确保文件在共享或发布前不包含敏感的作者信息、历史记录或其他自定义属性。该方法适用于需要清理文档信息、规范文件管理或满足数据安全要求的场景。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。