大家好,我只是用c#编程,正如我在标题中所问的那样,我希望获得帮助。 我有一个.docx文件,想阅读它,更改某些单词,最后将修改后的内容重写为另一个.docx文件。谢谢大家的帮助!
我将发布我的代码。代码会生成损坏的文件。
public void SearchAndReplace(string documentInput, string pathOutput)
{
string docText = null;
//Read
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(documentInput, true))
{
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
}
//change word
Regex regexText = new Regex("#DIREZIONECAP");
docText = regexText.Replace(docText, "PROVAAAAA");
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(pathOutput, WordprocessingDocumentType.Document))
{
using (StreamWriter sw = new StreamWriter(pathOutput, false))
{
sw.Write(docText);
}
}
}