【问题标题】:Find string and replace it with HTML content in word document using c#使用c#查找字符串并将其替换为word文档中的HTML内容
【发布时间】:2021-08-11 21:59:33
【问题描述】:

我想用 word 文档中的字符串替换 HTML 内容。我已经将 HTML 内容添加到 word 文档,但我想添加 HTML 内容替换 C# MVC 中的特定字符串。 以下是我的代码:

    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();
        }
    }

假设下面是我的word文件内容:

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

预期输出如下:

test1
你好
测试3

从word文档中查找字符串并用HTML数据替换。

您能帮我找到字符串(test2)并将其替换为 html 内容吗?

【问题讨论】:

    标签: c# .net asp.net-mvc model-view-controller


    【解决方案1】:

    示例代码:

        // 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);
                }
            }
        }
    

    【讨论】:

    • 我试过这段代码。如果我找到 test2 则使用此代码然后我替换为 hello 然后 word 文件将被损坏。这部分代码用于查找和替换docx中的简单字符串。我想将 HTML 内容 替换为 word 文件。你能帮我用替换test2将HTML内容添加到word文件中吗? @juanma
    • 不确定您想要实现什么,但 Words 是 XML 而不是 HTML。只需将您的单词重命名为 .zip,打开它并找到您的文本所在的 document.xml,您将看到节点。如果要替换
      标签,只需尝试使用 RegEx 像这样找到它们: .*?| 并创建一个条件以确保存在是“html”“body”“div”或任何您要查找的内容,否则您会弄乱您的单词,因为 XML 也是用 标签格式化的。
    • 我已经提供了将 HTML 内容添加到 word 文件中的那部分代码。但是在我的代码中,我在页面的最后添加了 HTML 内容,但我希望它在页面的中间。 @juanma
    • 在文档中间添加标签 {htmlcontent} 找到您的 html 并将标签替换为 html。
    • 我已经提供了有问题的预期输出。
    【解决方案2】:

    最后,我在 Nuget 包管理器 中找到了第三方 dll。这是示例代码解决方案。更多信息: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);
    
    • 导入以下命名空间。

       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;
      

    要实现此代码,请按照以下步骤操作:
    步骤 -1:打开 Nuget 包管理器
    步骤-2:在浏览选项卡中搜索 FreeSpire 并安装它。
    步骤-3:现在添加上面的代码。就是这样享受代码。

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签