打开-XML文档没有内容

Open-XML document has no content

我正在尝试使用 OpenXML 创建最简单的 docx 文件,文件已正确生成,正确打开,但没有内容。我的电脑没有安装 Microsoft Office。

using (WordprocessingDocument doc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                mainPart.Document = new Document(
                    new Body(
                        new DocumentFormat.OpenXml.Drawing.Paragraph(
                            new DocumentFormat.OpenXml.Drawing.Run(
                                new Text("Hello World!!!!!")))));
            }

参考MSDN。 您使用 DocumentFormat.OpenXml.Drawing 命名空间而不是 DocumentFormat.OpenXml.Wordprocessing。 更改 usings 更正一个:

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

using (var doc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = doc.AddMainDocumentPart();
    mainPart.Document = new Document(
      new Body(
        new Paragraph(
          new Run(
            new Text("Hello World!!!!!")))));
}