[英]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.