使用 OpenXML 创建第一个 Word 文档
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
public class OpenXmlSample
{
public void CreateWordDoc(string filepath, string msg)
{
using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = doc.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
// String msg contains the text, "Hello, Word!"
run.AppendChild(new Text(msg));
}
}
}
主程序
using System;
namespace sample1
{
class Program
{
static void Main(string[] args)
{
var sample = new OpenXmlSample();
var path = "hello.docx";
var content = "Hello, OpenXML.";
sample.CreateWordDoc(path, content);
}
}
}
生成的文件内容:
<?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="https://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
<w:p>
<w:r>
<w:t>Hello, Word!</w:t>
</w:r>
</w:p>
</w:body>
</w:document>