【发布时间】:2015-02-27 04:38:16
【问题描述】:
我正在尝试将数据库中的一些信息和一些图片插入到 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 循环时,它会引发错误,因为它试图复制完整的文档结构而不仅仅是正文部分。我能做什么?
【问题讨论】:
-
@TravisJ 我以前从未真正做过这样的事情。所以任何帮助表示赞赏。我不一定要求解决方案。只是方向正确的一点。
-
如果您有 Visual Studio,请先查看他们的 word 2007 模板项目。 (还有一个word 2003模板项目)。我认为这应该是“正确方向的一点”