You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Spire.Doc基于Template.docx生成Word并替换Key为HTML?

Hey there! I see you're using Spire.Doc to generate Word documents from a template, and you need to replace template keys with actual HTML content instead of plain text. Let's break down how to implement this properly—Spire.Doc has built-in methods to handle HTML insertion, so we just need to pair that with placeholder replacement.

Step-by-Step Solution

First, make sure your template (Template.docx) uses clear, unique placeholders for the HTML content—something like {{HTML_PLACEHOLDER}} works well (you can name it whatever makes sense for your use case).

Then, update your btnSubmit_Click event to find these placeholders and replace them with rendered HTML instead of just string text. Here's how to modify your existing code:

// 示例文件路径
string samplePath = Application.StartupPath + Path.DirectorySeparatorChar + "Template.docx";
// 结果文档路径
string docxPath = Application.StartupPath + Path.DirectorySeparatorChar + "Result.docx";

private void btnSubmit_Click(object sender, EventArgs e)
{
    // Initialize the Spire.Doc Document object
    Document document = new Document();
    document.LoadFromFile(samplePath);

    // Define your placeholder and the HTML content to insert
    // Replace these with your actual placeholder key and HTML source (e.g., from a RichTextBox or database)
    string htmlPlaceholder = "{{HTML_PLACEHOLDER}}";
    string targetHtml = "<h3>Generated Content</h3>" +
                        "<p>This is a <strong>formatted paragraph</strong> with a bullet list:</p>" +
                        "<ul>" +
                        "<li>First list item</li>" +
                        "<li>Second list item with <em>italic text</em></li>" +
                        "</ul>";

    // Find all instances of the placeholder in the document
    TextSelection[] placeholderMatches = document.FindAllString(htmlPlaceholder, true, true);
    
    foreach (TextSelection match in placeholderMatches)
    {
        TextRange placeholderRange = match.GetAsOneRange();
        Paragraph parentParagraph = placeholderRange.OwnerParagraph;
        
        // Get the position of the placeholder in its parent paragraph
        int placeholderIndex = parentParagraph.ChildObjects.IndexOf(placeholderRange);
        
        // Remove the placeholder text from the paragraph
        parentParagraph.ChildObjects.Remove(placeholderRange);
        
        // Insert the HTML content at the exact position where the placeholder was
        parentParagraph.AppendHTML(targetHtml);
    }

    // Save the modified document
    document.SaveToFile(docxPath, FileFormat.Docx);
    
    // Clean up resources
    document.Close();
    
    MessageBox.Show("Word document generated successfully!");
}

Key Notes to Keep in Mind

  • HTML Support: Spire.Doc supports most standard HTML tags (headings, paragraphs, lists, basic styling, links), but complex CSS or advanced HTML features might not render perfectly. Test your specific HTML content to ensure it looks right in the output Word doc.
  • Placeholder Placement: Make sure your placeholder is contained within a single paragraph—if it spans multiple paragraphs, FindAllString might not detect it correctly.
  • Image Handling: If your HTML includes images, use absolute file paths or base64-encoded images for best results relative paths can break if the output doc is moved.
  • Spire.Doc Version: Ensure you're using the latest version of Spire.Doc—older versions have limited HTML rendering capabilities.

内容的提问来源于stack exchange,提问作者user1372430

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:40:03