c# - 如何使用 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);
}
解决方案
尝试禁用AutoSave
选项。
using (WordprocessingDocument doc =
WordprocessingDocument.Open(document, true, new OpenSettings { AutoSave = false }))
{
...
}
看起来何时启用并调用AutoSave
getterdoc.MainDocumentPart.Document.Body
会导致doc.MainDocumentPart
未正确保存或被原始文档部分覆盖。
推荐阅读
- c# - C# 实体框架(代码优先),在模型上实现 CRUD 操作
- javascript - findPlaceFromQuery 返回错误的“PlacesServiceStatus”
- python - 当另一列中存在 N 个 NaN 时替换 pandas 列中的值
- java - 将事物保存到 java/javafx 中的本地存储?
- javascript - 配置 Webpack 输出包
- java - 如何使用 filename.property() 直接访问资源包属性文件
- jd-eclipse - JD-Eclipse 不工作
- python - 使用 python 和美丽的汤抓取数据
- excel - Excel VBA 错误“438”对象不支持此属性或方法
- python - 如何仅使用 Python(无 matplotlib)制作简单的垂直直方图