簡體   English   中英

如何使用 Openxml 替換 Word 文檔中的文本

[英]How to replace text in Word document using Openxml

我有一個簡單的 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);
    
                    }

嘗試禁用AutoSave選項。

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

看起來當啟用AutoSave並調用doc.MainDocumentPart.Document.Body的 getter 時,它會導致doc.MainDocumentPart未正確保存或被原始文檔部分覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM