温馨提示×

c# office如何处理文档属性

c#
小樊
94
2024-07-26 20:04:17
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

您可以使用C#代码来处理Office文档的属性。以下是一些示例代码,演示如何使用C#读取和设置Office文档的属性:

  1. 读取文档属性:
using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
        Application wordApp = new Application();
        Document doc = wordApp.Documents.Open(@"C:\path\to\your\document.docx");

        // 获取文档的标题属性
        string title = doc.BuiltInDocumentProperties[WdBuiltInProperty.wdPropertyTitle].Value.ToString();
        Console.WriteLine("Title: " + title);

        // 获取文档的作者属性
        string author = doc.BuiltInDocumentProperties[WdBuiltInProperty.wdPropertyAuthor].Value.ToString();
        Console.WriteLine("Author: " + author);

        // 关闭文档并退出Word应用程序
        doc.Close();
        wordApp.Quit();
    }
}
  1. 设置文档属性:
using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
        Application wordApp = new Application();
        Document doc = wordApp.Documents.Open(@"C:\path\to\your\document.docx");

        // 设置文档的标题属性
        doc.BuiltInDocumentProperties[WdBuiltInProperty.wdPropertyTitle].Value = "New Title";

        // 设置文档的作者属性
        doc.BuiltInDocumentProperties[WdBuiltInProperty.wdPropertyAuthor].Value = "John Doe";

        // 保存文档
        doc.Save();

        // 关闭文档并退出Word应用程序
        doc.Close();
        wordApp.Quit();
    }
}

请注意,以上代码示例使用了Microsoft Office的Interop库,因此您需要在项目中添加对"Microsoft.Office.Interop.Word"的引用。另外,确保您已安装了对应版本的Microsoft Office,并且需要在代码中替换实际的文档路径。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C# VSTO如何访问Office文档属性

0