Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# openxml

作者:死亡之神   发布日期:2026-06-12   浏览:134

using System;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;

class Program
{
    static void Main(string[] args)
    {
        string documentPath = "example.docx";
        using (WordprocessingDocument wordDocument = 
            WordprocessingDocument.Create(documentPath, WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
            mainPart.Document = new Document();
            Body body = mainPart.Document.AppendChild(new Body());

            // Create a paragraph and add it to the document.
            Paragraph para = new Paragraph();
            Run run = new Run();
            Text text = new Text("Hello, OpenXML!");
            run.Append(text);
            para.Append(run);
            body.Append(para);
        }

        Console.WriteLine("Document created successfully.");
    }
}

解释说明

  1. 命名空间引用:

    • DocumentFormat.OpenXml.PackagingDocumentFormat.OpenXml.Wordprocessing 是 OpenXML SDK 的核心命名空间,用于处理文档的创建和操作。
  2. 创建文档:

    • 使用 WordprocessingDocument.Create 方法创建一个新的 .docx 文件,并指定其类型为 WordprocessingDocumentType.Document
  3. 添加主文档部分:

    • 使用 AddMainDocumentPart 方法添加主文档部分,并初始化一个空的 Document 对象和 Body 对象。
  4. 创建段落:

    • 创建一个 Paragraph 对象,并在其中添加一个 Run 对象,Run 对象中包含要显示的文本 Text
  5. 将段落添加到文档主体:

    • 将创建的段落添加到文档的主体部分 body 中。
  6. 完成并保存:

    • 完成后,文档会自动保存到指定路径 documentPath

这段代码展示了如何使用 C# 和 OpenXML SDK 创建一个简单的 Word 文档,并向其中添加文本内容。

上一篇:c#列表

下一篇:c#两个list合并

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站