简体   繁体   中英

Merging Documents with OpenXML 2.0

I'm trying to insert some information and some pictures from a database into a Word Document.

I have created a Word document to serve as a template where I want to find and replace the keywords with the actual data and picture.

How do I open this template, replace the keywords, and put it into the new document. Then I need to re-open that template and do it again until everyone in the List is inside the new Word document.

//The template file exists, so open it and use it to set up the main Word document
using (WordprocessingDocument templatePackage = WordprocessingDocument.Open(templateDocPath, false))
{
    //Read the template file
    string docText = null;
    using (StreamReader sr = new StreamReader(templatePackage.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }

    string tempString = docText;
    Regex regexText = new Regex("<name>");
    docText = regexText.Replace(docText, tnlCampers[0].FirstName + " " + tnlCampers[0].LastName);

    regexText = new Regex("<address>");
    docText = regexText.Replace(docText, tnlCampers[0].Address1 + " " + tnlCampers[0].Address2 + " " + tnlCampers[0].City + ", " + tnlCampers[0].State + " " + tnlCampers[0].ZipCode);

    regexText = new Regex("<phone>");
    docText = regexText.Replace(docText, tnlCampers[0].CellPhone);

    regexText = new Regex("<email>");
    docText = regexText.Replace(docText, tnlCampers[0].Email);

    //Write to the newly created Word Document
    using (StreamWriter sw = new StreamWriter(package.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
}

But when I do a foreach loop on my tnlCampers list it throws an error because it's trying to copy the full document structure instead of just the body part. What can i do?

您可以尝试使用Word Doc Generator ,它是使用Visual Studio 2010和Open XML 2.0 SDK从模板生成Word文档的实用程序。

you might also try our GemBox.Document component.

It has very user friendly and efficient support for mail merge. See C# Word mail merge article and customize mail merge sample.

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