首页 > 解决方案 > 如何使用 Openxml 替换 Word 文档中的文本

问题描述

我有一个简单的 word 文档,只有一个单词“$Hello$”。我正在尝试将“$Hello$”更改为“Goodbye”,但没有任何反应,也没有错误。我怎样才能让代码工作?"$Hello$" 在一个段落中。

using System;
using System.IO;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace OpenXMLTests
{
    class Program
    {
        static void Main(string[] args)
        {
            String document = "TestDoc.docx";
            using (WordprocessingDocument doc = WordprocessingDocument.Open(document, true))
            {
                Body body = doc.MainDocumentPart.Document.Body;
                foreach (Table t in body.Descendants<Table>())
                {
                    String tableName = t.GetFirstChild<TableProperties>().TableCaption.Val;
                    Console.WriteLine(tableName);

                }

                string docText = null;  
                using (StreamReader sr = new StreamReader(doc.MainDocumentPart.GetStream()))   //Reads file to string
                {
                    docText = sr.ReadToEnd();
                }
          
                docText = docText.Replace("$Hello$", "Goodbye");

                using (StreamWriter sw = new StreamWriter(doc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }

            }
        }

    }
}

当我删除此表循环时,代码有效。不知道有什么冲突

                    Body body = doc.MainDocumentPart.Document.Body;
                    foreach (Table t in body.Descendants<Table>())
                    {
                        String tableName = t.GetFirstChild<TableProperties>().TableCaption.Val;
                        Console.WriteLine(tableName);
    
                    }

标签: c#openxmldocxopenxml-sdk

解决方案


尝试禁用AutoSave选项。

using (WordprocessingDocument doc = 
        WordprocessingDocument.Open(document, true, new OpenSettings { AutoSave = false }))
{
...
}

看起来何时启用并调用AutoSavegetterdoc.MainDocumentPart.Document.Body会导致doc.MainDocumentPart未正确保存或被原始文档部分覆盖。


推荐阅读