I am trying to generate the word document using open XML plugin in Dot net core by writing code in action result method inside controller like this below
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);
.......
........
.........
}
}
}
but some how getting an error at this line SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants<SectionProperties>().FirstOrDefault();
**Error:** DocumentFormat.OpenXml.Packaging.MainDocumentPart.Document.get returned null.
i am not sure where i am doing wrong with this code, Could any one please suggest any idea on this one
many thanks in advance
MainDocumentPart.Document == null
, so maybe you must add youdoc
to themainDocPart
? – Frank Nielsen