我有一個包含指定模式文本{pattern}的word文件,我想用從數據庫中讀取的新字符串替換那些模式。所以我用我的docx模板文件打開xml讀取流,替換我的模式字符串,然後返回到流,支持下載文件而不創建臨時文件。但是當我打開它時,我生成了docx文件上的錯誤。下面是我的示例代碼打開xml替換word文件中的文本並使用MVC返回內存流
public ActionResult SearchAndReplace(string FilePath)
{
MemoryStream mem = new MemoryStream(System.IO.File.ReadAllBytes(FilePath));
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
//Instead using this code below to write text back the original file. I write new string back to memory stream and return to a stream download file
//using (StreamWriter sw = new //StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
//{
// sw.Write(docText);
//}
using (StreamWriter sw = new StreamWriter(mem))
{
sw.Write(docText);
}
}
mem.Seek(0, SeekOrigin.Begin);
return File(mem, "application/octet-stream","download.docx"); //Return to download file
}
請給我建議任何解決方案,而不是閱讀的Word文件的文本,並替換那些預期的模式文本,然後將數據寫回原來的文件。有沒有解決方案用WordprocessingDocument庫替換文本?我怎樣才能以驗證docx文件格式返回到內存流?