【发布时间】:2012-05-17 14:23:17
【问题描述】:
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("@@username@@");
docText = regexText.Replace(docText, "john thomas ");
using (StreamWriter sw =
new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
这应该用代码中的名称替换 doctext 上的匹配项。我检查了文档文本,要替换的单词 (@@username@@) 已拆分。有时有 XML 内容之间
@@ 和 username@@。有时单词本身格式不正确。
如何替换@@username@@?
【问题讨论】:
-
你为什么不使用文字处理合并功能来为字段提供内容而不是滥用正则表达式?
-
不是 DOCX 文件格式专家,我真的怀疑您是否可以对 DOCX 文件的内容使用字符串函数。我建议使用 Aspose.Words 或 Spire.