简体   繁体   English

使用 c# 在 word 文档中查找字符串并将其替换为 HTML 内容

[英]Find string and replace it with HTML content in word document using c#

I want to replace HTML content with string in word document.我想用 word 文档中的字符串替换 HTML 内容。 I've already add HTML content to the word document but I want to add HTML content replacing specific string in C# MVC.我已经将 HTML 内容添加到 word 文档,但我想添加 HTML 内容替换 C# MVC 中的特定字符串。 Below is my code:下面是我的代码:

    public static void addhtmltodocx() //This function add HTML content end of the the word document
    {
        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(@"C:\Users\1527858\Desktop\test.docx", true))
        {
            string html =
            @"<html>
                <head/>
                <body>
                    <b>Hello</b>
                </body>
            </html>";

            string altChunkId = "AltChunkId"+21;
            MainDocumentPart mainPart = myDoc.MainDocumentPart;
            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);

            using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
            using (StreamWriter stringStream = new StreamWriter(chunkStream))
                stringStream.Write(html);

            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;

            mainPart.Document.Body
                .InsertAfter(altChunk, mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
            
            mainPart.Document.Save();
        }
    }

Suppose below is my word file content:假设下面是我的word文件内容:

test1
test2  // I want to replace test2 with the html content.
test3

Expected Output like:预期 Output 像:

test1测试1
Hello你好
test3测试3

Find the string from word document and replace it with HTML data.从 word 文档中查找字符串并将其替换为 HTML 数据。

Could you help me with find string(test2) and replace it html content.你能帮我找到字符串(test2)并将其替换为 html 内容吗?

Sample code:示例代码:

    // To search and replace content in a document part.
    public static void SearchAndReplace(string document)
    {
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, 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!");

            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }
        }
    }

Finally, I found the third party dll which is available in Nuget package manager .最后,我在Nuget package manager中找到了第三方 dll 。 Here is the sample code solution.这是示例代码解决方案。 More Info: VISIT更多信息: 访问

        string filename = @"C:\test.docx";
        Document document = new Document();
        document.LoadFromFile(filename);

        TextSelection[] selections1 = document.FindAllString("test2", true, true);
        //Here in first parameter you need pass the string which you want to replace.
        foreach (TextSelection selection1 in selections1)
        {
            TextRange range1 = selection1.GetAsOneRange();
            Paragraph paragraph = range1.OwnerParagraph;
            int index1 = paragraph.ChildObjects.IndexOf(range1);
            paragraph.AppendHTML("<b>Hello</b>");
            range1.OwnerParagraph.ChildObjects.Remove(range1);
        }
        document.SaveToFile(filename, FileFormat.Docx);
  • Import below namespaces.导入以下命名空间。

     using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Document = Spire.Doc.Document; using Paragraph = Spire.Doc.Documents.Paragraph;

For Implementation of this code please follow below step:要实现此代码,请按照以下步骤操作:
Step -1: Open the Nuget Package Manager .步骤-1:打开Nuget Package 管理器
Step -2: Search FreeSpire in browse tab and install it.步骤-2:在浏览选项卡中搜索FreeSpire并安装它。
Step -3: Now add the above code.步骤-3:现在添加上面的代码。 That's it Enjoy the Code.就是这样享受代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM