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.");
}
}
命名空间引用:
DocumentFormat.OpenXml.Packaging 和 DocumentFormat.OpenXml.Wordprocessing 是 OpenXML SDK 的核心命名空间,用于处理文档的创建和操作。创建文档:
WordprocessingDocument.Create 方法创建一个新的 .docx 文件,并指定其类型为 WordprocessingDocumentType.Document。添加主文档部分:
AddMainDocumentPart 方法添加主文档部分,并初始化一个空的 Document 对象和 Body 对象。创建段落:
Paragraph 对象,并在其中添加一个 Run 对象,Run 对象中包含要显示的文本 Text。将段落添加到文档主体:
body 中。完成并保存:
documentPath。这段代码展示了如何使用 C# 和 OpenXML SDK 创建一个简单的 Word 文档,并向其中添加文本内容。
上一篇:c#列表
下一篇:c#两个list合并
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站