Search code examples
c#.netopenxml

Open-XML document has no content


I am trying to create the most simple docx file using OpenXML, the file is correctly generated, open correctly, but has no content. My PC does not have Microsoft Office installed.

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!!!!!")))));
            }

Solution

  • Refer to MSDN. You using DocumentFormat.OpenXml.Drawing namespace instead of DocumentFormat.OpenXml.Wordprocessing. Change usings to correct one:

    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!!!!!")))));
    }