c# - 保存文档文件的问题

标签 c# asp.net openxml-sdk doc

我正在使用 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/

相关文章:

c# - 从类库加载资源时出现问题

c# - NHibernate - 通过代码/Conformist 映射接口(interface)或抽象组件

ASP.NET AJAX 控件工具包 HTMLEditor 显示不正确

c# - SQLDataReader 运行速度太慢取决于标准

c# - 从 ASP.NET 页面下载 EXCEL 文件,无需在服务器上生成物理文件(动态)

C# 打开 XML : empty cells are getting skipped while getting data from EXCEL to DATATABLE

c# - 我的 WPF 自定义控件 Datacontext 正在取代父控件

c# - 部分类中同一源文件的可变范围

asp.net - 如何设置 SelectedIndexChanged 和普通面板更新事件之间的处理时间事件?

.net - OpenXML 每行的文件越大越慢?