尝试使用 open xml 从 dot net core mvc 下载 word 文档时出现错误

trying to download the word document using open xml from dot net core mvc getting an error

我正在尝试使用 Dot net core 中的 open XML 插件生成 word 文档,方法是在控制器内的 action result 方法中编写代码,如下所示

    public IActionResult CreateDocument()
    {
        using (MemoryStream mem = new MemoryStream())
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
            {
                wordDoc.AddMainDocumentPart();
                Document doc = new Document();

                //Body body = new Body();

                /// Add header
                MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;

                HeaderPart headerPart1 = mainDocPart.AddNewPart<HeaderPart>("r97");

                Header header1 = new Header();

                Paragraph paragraph1 = new Paragraph() { };
                Run run1 = new Run();
                Text text1 = new Text();
                text1.Text = "This is Header Part";

                run1.Append(text1);
                paragraph1.Append(run1);
                header1.Append(paragraph1);

                headerPart1.Header = header1;

                // getting an error here in this line
                SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants<SectionProperties>().FirstOrDefault();  
                if (sectionProperties1 == null)
                {
                    sectionProperties1 = new SectionProperties() { };
                    mainDocPart.Document.Body.Append(sectionProperties1);
                }
                HeaderReference headerReference1 = new HeaderReference() { Type = HeaderFooterValues.Default, Id = "r97" };
                sectionProperties1.InsertAt(headerReference1, 0);
             .......
            ........
            .........
           }
        }
     }

但一些如何在这一行出现错误 SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants<SectionProperties>().FirstOrDefault();

**Error:** DocumentFormat.OpenXml.Packaging.MainDocumentPart.Document.get returned null.

我不确定这段代码哪里做错了,有人可以就此提出任何想法吗

非常感谢

您在这一行实例化 mainDocPart 变量:
MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;

那你没有在里面添加任何文件。这就是您收到错误的原因:DocumentFormat.OpenXml.Packaging.MainDocumentPart.Document.get returned null.

如何解决:

mainDocPart.Document = doc; //you define earlier but do not used.
doc.Body = new Body();
SectionProperties sectionProperties1 = 
mainDocPart.Document.Body.Descendants<SectionProperties>()?.FirstOrDefault();  
if (sectionProperties1 == null)
{
    sectionProperties1 = new SectionProperties() { };
    mainDocPart.Document.Body.Append(sectionProperties1);
}

您可以在此文档页面中获取有关它的更多信息:https://docs.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.document?redirectedfrom=MSDN&view=openxml-2.8.1

要补充 Lutti 的答案,您需要了解最小 WordprocessingDocumentMainDocumentPart 组成,其内容至少为以下内容:

<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body />
</w:document>

因此,当您创建一个"empty"文档时,您至少应该有以下代码:

using (var stream = new MemoryStream())
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainDocumentPart = wordDocument.AddMainDocumentPart();
    mainDocumentPart.Document = new Document(new Body());
}

注意 w:documentw:body 元素与 DocumentBody 实例的对应关系。

以创建 header 为例,您通常可以通过组合构造函数来简化代码,从而创建 XML markup-like 结构,如下所示:

var headerPart = mainDocumentPart.AddNewPart<HeaderPart>();
headerPart.Header =
    new Header(
        new Paragraph(
            new Run(
                new Text("This is the Header Part"))));

在上面的代码示例中,我按照您格式化相应的 Open XML 标记的方式布置了代码:

<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:p>
    <w:r>
      <w:t>This is the Header Part</w:t>
    </w:r>
  </w:p>
</w:hdr>

在我看来,这更容易阅读,如果您了解创建所需结果所需的 Open XML 标记,有助于避免错误。