简体   繁体   English

OpenXml,Word和C#

[英]OpenXml, Word and C#

Here is my problem: I'm trying to perform a mail merge using OpenXml and C# . 这是我的问题:我正在尝试使用OpenXmlC#执行邮件合并。 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 ). 为此,我必须创建一个Word文档,该文档的页数与数据集中的行数相同(我的数据集是CSV文件 )。

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. 要进行复制,我使用要从模板复制到新Word文档每一页的InnerXml

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();
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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