[英]Merging Documents with OpenXML 2.0
我試圖將一些信息和一些圖片從數據庫插入到Word文檔中。
我已經創建了一個Word文檔作為模板,可以在其中查找並用實際數據和圖片替換關鍵字。
如何打開此模板,替換關鍵字,然后將其放入新文檔中。 然后,我需要重新打開該模板,然后再次進行操作,直到列表中的每個人都在新的Word文檔中。
//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);
}
}
但是,當我在tnlCampers列表上執行foreach循環時,會引發錯誤,因為它試圖復制整個文檔結構而不是僅復制正文部分。 我能做什么?
您可以嘗試使用Word Doc Generator ,它是使用Visual Studio 2010和Open XML 2.0 SDK從模板生成Word文檔的實用程序。
您也可以嘗試使用我們的GemBox.Document組件。
它具有非常用戶友好和高效的郵件合並支持。 請參閱C#Word郵件合並文章和自定義郵件合並示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.