簡體   English   中英

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

[英]how to replace text in .docx file in c#

我有一個創建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 ##等的某些值未替換,任何幫助將不勝感激。

您好,您的問題可能不是外殼問題。 似乎與該問題相同:

為什么Office OpenXML在標簽之間拆分文本,以及如何防止文本拆分?

實際上,docx中的文本可能會被拆分:

##Interest Rate##

->分裂

<w:t>##Interest</w:t>

<w:t> Rate##</w:t>

替換找不到該字符串(請看一下鏈接)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM