简体   繁体   中英

OpenXml, Word and C#

Here is my problem: I'm trying to perform a mail merge using OpenXml and C# . To do this, I have to create a Word document which has the same number of pages as lines in my data set (My data set is a CSV file ).

I create a new document, and I'm trying to copy my template on each page of this document. Unfortunately, only the first page has the correct format (my template is copied on it). To copy, I use the InnerXml that I'm trying to copy from my template to each page of my new word document.

I know that my problem comes from my instructions, but I don't know how to fix it.

Here is my code:

string fileName = @"MyTemplate";
using (WordprocessingDocument pkgDoc = WordprocessingDocument.Open(fileName, true))
{
    pkgDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
    var test = (pkgDoc.MainDocumentPart.RootElement.InnerXml);

    string filenamecible = @"@MyNewWordDocument";

    using (WordprocessingDocument package = WordprocessingDocument.Create(filenamecible, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = package.AddMainDocumentPart();

        //Create DOM tree for simple document. 

        mainPart.Document = new Document();

        for (int i = 0; i < csvline.Count; i++)
        {
            mainPart.RootElement.InnerXml = test;
            var x = new Break() { Type = BreakValues.Page };;
            mainPart.Document.Append(x);
            mainPart.Document.Save();
        }

        package.MainDocumentPart.Document.Save();
    }

}

Well i find the solution if someone got the same problem here is the code :

string fileName = @"MyTemplate";
using (WordprocessingDocument pkgDoc = WordprocessingDocument.Open(fileName, true))
{
    pkgDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
    var test = (pkgDoc.MainDocumentPart.RootElement.InnerXml);

string filenamecible = @"@MyNewWordDocument";

using (WordprocessingDocument package = WordprocessingDocument.Create(filenamecible, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = package.AddMainDocumentPart();

    //Create DOM tree for simple document. 

    mainPart.Document = new Document();

    for (int i = 0; i < csvline.Count; i++)
    {
         var x = new Break() { Type = BreakValues.Page };
         Body b = new Body(test);
         mainPart.Document.Append(b);
         mainPart.Document.Append(x);
         mainPart.Document.Save();
    }

    package.MainDocumentPart.Document.Save();
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM