如何在C#中替换.docx文件中的文本

3

我正在创建一个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);
                        }
                    }
}

在上面的文本中,一些值如##账户号码##、##当前日期##等没有被替换。任何帮助都将不胜感激。

1
这个能帮到你吗?http://netword.codeplex.com/ - Izikon
如果某些元素被替换而其他元素没有被替换,可能是大小写问题... - Gonzix
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接