最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#代碼實(shí)現(xiàn)根據(jù)模板快速生成Word文檔

 更新時(shí)間:2026年04月07日 11:41:43   作者:LSTM97  
在日常開發(fā)中,我們經(jīng)常遇到需要批量生成合同、通知書、報(bào)告等Word文檔的場景,今天小編就來分享如何使用?Free Spire.Doc for .NET?輕松實(shí)現(xiàn)根據(jù)模板快速生成Word文檔吧

在日常開發(fā)中,我們經(jīng)常遇到需要批量生成合同、通知書、報(bào)告等Word文檔的場景。最優(yōu)雅的方式莫過于準(zhǔn)備一個(gè)模板文件,然后通過代碼替換其中的占位符,快速生成最終文檔。今天就來分享如何使用 Free Spire.Doc for .NET 輕松實(shí)現(xiàn)這一功能。

為什么選擇 Free Spire.Doc?

Free Spire.Doc 是一款免費(fèi)、易用的 Word 操作組件,無需安裝 Microsoft Office 即可完成文檔的創(chuàng)建、讀取、編輯和保存。它支持 .NET Framework 和 .NET Core,非常適合服務(wù)端批量處理場景。

通過 NuGet 安裝:

PM> Install-Package FreeSpire.Doc

實(shí)現(xiàn)思路

預(yù)先設(shè)計(jì)一個(gè) Word 模板(如 template.docx),用特定占位符標(biāo)記需要填充的內(nèi)容

在代碼中加載模板,將占位符替換為實(shí)際數(shù)據(jù)

支持文本替換,也支持插入圖片(如證件照)

保存為新的 Word 文檔

完整代碼

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace CreateWordByReplacingPlaceholders
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new Document object
            Document document = new Document();

            // Load the template Word file
            document.LoadFromFile("C:\Users\Administrator\Desktop\template.docx");

            // Dictionary to hold placeholders and their replacements
            Dictionary<string, string> replaceDict = new Dictionary<string, string>
            {
                { "#name#", "李四" },
                { "#gender#", "男" },
                { "#birthdate#", "1990年3月20日" },
                { "#address#", "西安北路街道" },
                { "#city#", "成都" },
                { "#province#", "四川" },
                { "#postal#", "610000" },
                { "#country#", "中國" }
            };

            // Replace placeholders in the document with corresponding values
            foreach (KeyValuePair<string, string> kvp in replaceDict)
            {
                document.Replace(kvp.Key, kvp.Value, true, true);
            }

            // Path to the image file
            String imagePath = "C:\Users\Administrator\Desktop\portrait.png";

            // Replace the placeholder for the photograph with an image
            ReplaceTextWithImage(document, "#photo#", imagePath);

            // Save the modified document
            document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);

            // Release resources
            document.Dispose();
        }

        // Method to replace a placeholder in the document with an image
        static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
        {
            // Load the image from the specified path
            Image image = Image.FromFile(imagePath);
            DocPicture pic = new DocPicture(document);
            pic.LoadImage(image);
            pic.Width = 130;

            // Find the placeholder in the document
            TextSelection selection = document.FindString(stringToReplace, false, true);

            // Get the range of the found text
            TextRange range = selection.GetAsOneRange();
            int index = range.OwnerParagraph.ChildObjects.IndexOf(range);

            // Insert the image and remove the placeholder text
            range.OwnerParagraph.ChildObjects.Insert(index, pic);
            range.OwnerParagraph.ChildObjects.Remove(range);
        }
    }
}

代碼詳解

1. 文本替換

首先準(zhǔn)備一個(gè)字典,存儲占位符與替換文本的對應(yīng)關(guān)系:

Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
    { "#name#", "李四" },
    { "#gender#", "男" },
    // ... 其他字段
};

然后遍歷字典,調(diào)用 document.Replace 方法完成替換。該方法的后兩個(gè)參數(shù)分別表示是否區(qū)分大小寫和是否僅替換整個(gè)單詞。

2. 圖片替換

圖片替換稍微復(fù)雜一些,核心步驟如下:

  • 使用 Image.FromFile 加載圖片文件
  • 創(chuàng)建 DocPicture 對象并加載圖片,設(shè)置圖片寬度
  • 通過 FindString 定位占位符的位置
  • 獲取占位符所在段落及索引
  • 在相同位置插入圖片,然后移除占位符文本

3. 保存文檔

最后調(diào)用 SaveToFile 方法保存為新文檔,并釋放資源。

模板準(zhǔn)備建議

在 Word 模板中,將需要?jiǎng)討B(tài)填充的位置用占位符標(biāo)記,例如:

字段占位符
姓名#name#
性別#gender#
出生日期#birthdate#
照片#photo#

使用注意事項(xiàng)

  • 確保模板文件路徑和圖片路徑正確
  • 占位符建議使用獨(dú)特標(biāo)識(如 #字段名#),避免誤替換
  • 圖片替換時(shí)可調(diào)整 Width 和 Height 屬性控制顯示尺寸
  • 處理完成后記得調(diào)用 Dispose() 釋放資源

總結(jié)

通過 Free Spire.Doc,我們只需維護(hù)一套模板文件,即可快速生成成千上萬份個(gè)性化文檔,大幅提升工作效率。該組件還支持合并單元格、設(shè)置字體樣式、添加頁眉頁腳等高級功能

到此這篇關(guān)于C#代碼實(shí)現(xiàn)根據(jù)模板快速生成Word文檔的文章就介紹到這了,更多相關(guān)C#模板生成Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

广元市| 上高县| 高陵县| 博野县| 河源市| 托克逊县| 集贤县| 原平市| 蒙自县| 望城县| 漾濞| 合江县| 凌海市| 龙州县| 平遥县| 来凤县| 奇台县| 土默特右旗| 察雅县| 溧水县| 莒南县| 康平县| 滕州市| 平舆县| 荣昌县| 鄂州市| 那坡县| 台北市| 新安县| 长岛县| 潜山县| 友谊县| 北辰区| 思南县| 射阳县| 合阳县| 霍州市| 六盘水市| 小金县| 阳朔县| 大同县|