环境:asp.net c# openxml
好的,所以我已经阅读了大量片段并尝试重新创建轮子,但我希望有人能帮助我更快地到达目的地。我有多个文档需要合并在一起...检查...我可以使用 openxml sdk 做到这一点。鸟儿在歌唱,阳光明媚。现在我已经按照我想要的方式获得了文档,我需要搜索和替换文本和/或内容控件。
我尝试使用自己的文本 - {replace this} 但是当我查看 xml(将 docx 重命名为 zip 并查看文件)时,{ 离文本很远。所以我要么需要知道如何在文档中保护它,以免它们发生分歧,要么我需要找到另一种搜索和替换的方法。
如果它是一个 xml 文件,我可以搜索/替换,但是我又回到了无法轻松组合文档的状态。
下面的代码......正如我提到的......文档合并工作正常......只需要替换东西。
* 更新 * 将我的替换调用更改为在标记之后而不是正则表达式之后。我现在有了正确的信息,但是 .Replace 调用似乎不起作用。最后四行用于验证我是否看到了正确的标签内容。我现在只想替换这些内容。
protected void exeProcessTheDoc(object sender, EventArgs e)
{
string doc1 = Server.MapPath("~/Templates/doc1.docx");
string doc2 = Server.MapPath("~/Templates/doc2.docx");
string final_doc = Server.MapPath("~/Templates/extFinal.docx");
File.Delete(final_doc);
File.Copy(doc1, final_doc);
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(final_doc, true))
{
string altChunkId = "AltChunkId2";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(doc2, FileMode.Open))
chunk.FeedData(fileStream);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
exeSearchReplace(final_doc);
}
public static void GetPropertyFromDocument(string document, string outdoc)
{
XmlDocument xmlProperties = new XmlDocument();
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, false))
{
ExtendedFilePropertiesPart appPart = wordDoc.ExtendedFilePropertiesPart;
xmlProperties.Load(appPart.GetStream());
}
XmlNodeList chars = xmlProperties.GetElementsByTagName("Company");
chars.Item(0).InnerText.Replace("{ClientName}", "Penn Inc.");
StreamWriter sw;
sw = File.CreateText(outdoc);
sw.WriteLine(chars.Item(0).InnerText);
sw.Close();
}
}
最佳答案
如果我没看错的话,您会在 .docx 中找到类似“{replace me}”的内容,然后当您循环遍历 XML 时,您会发现类似 <t>{replace</t><t> me</><t>}</t>
的内容。或一些这样的破坏。现在,使用这样的 XML,不可能创建一个例程来替换“{replace me}”。
如果是这种情况,那么它非常非常可能与它被认为是校对错误这一事实有关。也就是说,就 Word 而言,它拼错了。原因是您在 Word 中打开了文档并打开了校对。因此,文本被标记为“isDirty”并分成不同的运行。
解决这个问题的两种方法是:
- 客户端。在 Word 中,只需确保所有校对错误都已更正或忽略。
- 格式方面。使用 MarkupSimplifier 工具(Open XML Package Editor Power Tool for Visual Studio 2010 的一部分)在客户端外修复此问题。埃里克·怀特 (Eric White) 在这里写了一篇很棒的文章(对你来说很及时——才几天):Getting Started with Open XML PowerTools Markup Simplifier
关于c# - YASR - 另一个搜索和替换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5278804/