保存doc文件的问题

时间:2014-11-25 09:17:34

标签: 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();
}

请帮忙。 感谢。

2 个答案:

答案 0 :(得分:2)

您永远不会更改文档本身,而是使用其他字符串变量替换从文件中读取的字符串变量。 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进行替换的示例

答案 1 :(得分:1)

您需要将documentText字符串(带有更改)写回文档,您可以使用StreamWriter执行此操作,如下所示:

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");

    // Write text to document.
    using (StreamWriter writer = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        writer.Write(documentText);
    }
}
相关问题