这是我的问题:我正在尝试使用 OpenXml 和 C# 执行邮件合并。为此,我必须创建一个 Word 文档,该文档的页数与数据集中的行数相同(我的数据集是 CSV 文件)。
我创建了一个新文档,并尝试在此文档的每一页上复制我的模板。不幸的是,只有第一页具有正确的格式(我的模板被复制在上面)。若要复制,我使用尝试从模板复制到新 Word 文档的每一页的InnerXml
。
我知道我的问题来自我的指示,但我不知道如何解决它。
这是我的代码:
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();
}
}
好吧,如果有人遇到同样的问题,我找到了解决方案,这里是代码:
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();
}
}