[英]ASP.NET + C#. Creating word document from template
我有一个Word文档,其中仅包含一页文字和图形。 该页面还包含一些占位符,例如[Field1],[Field2],...等。我从数据库中获取数据,我想打开此文档并用一些数据填充占位符。 对于要打开此文档的每个数据行,请在占位符中填充该行的数据,然后将所有创建的文档连接到一个文档中。 最佳和最简单的方法是什么?
您可能需要使用第三方库。
您可能需要查看http://www.codeproject.com/Articles/660478/Csharp-Create-and-Manipulate-Word-Documents-Progra
下一节将专门讨论在Word文档中替换值。
而不是第三方,我建议您使用openXML
添加以下名称空间System.Text.RegularExpressions; DocumentFormat.OpenXml.Packaging; 和DocumentFormat.OpenXml.Wordprocessing;
public static void SearchAndReplace(string document)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.