我有创建 Asp.net MVC 项目。我需要在其中上传一个 .docx 文件,并且必须用用户当前详细信息和一些动态值替换文本。我在 Assembly DocumentFormat.OpenXml.dll 的帮助下完成了这项任务. 问题是它正在替换一些文本,但有些不是。我的代码是这样的-
if (document.DocumentName.Contains(".doc") || document.DocumentName.Contains(".docx"))
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(File, true))
{
using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
documentText = reader.ReadToEnd();
}
documentText = documentText.Replace("##Username##", user.Username);
documentText = documentText.Replace("##Email##", user.Email);
documentText = documentText.Replace("##TSF Number##", convert(NewAccount_210.TSFILE_NUMBER).ToString());//check
documentText = documentText.Replace("##A3PThirdPartyId##", convert(NewAccount_210.A3P_THIRD_PARTY_ID));
documentText = documentText.Replace("##Location Code##", convert(NewAccount_210.LOCATION_CODE));
documentText = documentText.Replace("##AccountNumber##", convert(NewAccount_210.ACCT_NUMBER));//check
documentText = documentText.Replace("##Transaction Number##", convert(NewAccount_210.TRANSACTION_NUMBER));
documentText = documentText.Replace("##Current Date##", convert(NewAccount_210.CURRENT_DATE).ToString());
documentText = documentText.Replace("##Customer Name##", convert(NewAccount_210.CUSTOMER_NAME));
documentText = documentText.Replace("##SocialSecuirityNumber##", convert(NewAccount_210.SOCIAL_SECURITY_NUM));//check
documentText = documentText.Replace("##A3PAmountPlaced##", (convert(NewAccount_210.A3P_AMT_PLACED)).ToString());
documentText = documentText.Replace("##Interest Rate##", (convert(NewAccount_210.INTEREST_RATE)).ToString());//check
using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
writer.Write(documentText);
}
}
}
在上面的文本中,一些值如##AccountNumber##、##Current Date## 等没有被替换。任何帮助将不胜感激。
最佳答案
您好,您的问题可能不是外壳问题。好像和那个问题一样:
Why Office OpenXML splits text between tags and how to prevent it?
确实,docx 中的文本可能会被拆分:
##Interest Rate##
-> split
<w:t>##Interest</w:t>
<w:t> Rate##</w:t>
替换不会找到该字符串(查看链接)
关于c# - 如何在 C# 中替换 .docx 文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19538080/