我正在使用 C# 中的 openxml 编辑 doc 文件并想保存它。已进行更改但无法保存文件。当我打开文件时,它没有显示所做的任何更改。我用下面的代码做到了。
using (WordprocessingDocument doc = WordprocessingDocument.Open(source, true))
{
using (StreamReader reader = new StreamReader(doc.MainDocumentPart.GetStream()))
{
documentText = reader.ReadToEnd();
}
Body body = doc.MainDocumentPart.Document.Body;
documentText = documentText.Replace("##date##", "02/02/2014");
documentText = documentText.Replace("##saleno##", "2014");
documentText = documentText.Replace("##Email##", "abc");
documentText = documentText.Replace("##PhoneNo##", "9856321404");
doc.MainDocumentPart.Document.Save();
doc.Close();
}
请帮忙。 谢谢。
最佳答案
您永远不会更改文档本身,您只是用其他字符串变量替换从文件中读取的字符串变量。 documentText 变量并没有神奇地连接到文件中的文本。这是基本的 C#。
代码如本tutorial所示.
// To search and replace content in a document part.
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);
}
}
}
请注意,他们在最后使用流编写器将内容保存回文件。
还值得注意的是,虽然这种快速而肮脏的方法通常适用于简单的查找和替换情况,但在更复杂的情况下您实际上需要使用 OOXML API。使用 OOXML API,您可以将文档的每个部分作为元素树(很像 HTML)遍历。您可以在文档中添加和删除项目。此时,对 Save 的简单调用就足够了。为此,您必须遍历各个部分,可能是递归地并修改元素本身。这当然要复杂得多,但它允许多次重复模板之类的事情。可以引用这个SO question有关如何使用实际的 OOXML API 进行替换的示例
关于c# - 保存文档文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27122719/