Golang实现Word模板内容填充导出

这里我们使用一个广泛使用且免费处理 .docx 文件的库,github.com/nguyenthenguyen/docx.

安装 github.com/nguyenthenguyen/docx

首先,确保你已经安装了 docx 库:

sh 复制代码
go get github.com/nguyenthenguyen/docx

使用 docx 库处理 Word 模板

以下是如何实现的完整示例:

示例模板内容

假设我们的模板 template.docx 的内容如下:

plaintext 复制代码
张三:{{TASK_NAME}}
李四:{{DETAILS}}

实现代码逻辑

go 复制代码
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/nguyenthenguyen/docx"
)

func replacePlaceholder(text, placeholder, value string) string {
	return strings.ReplaceAll(text, "{{"+placeholder+"}}", value)
}

func main() {
	// 打开 Word 模板
	r, err := docx.ReadDocxFile("/Users/songfayuan/GolandProjects/dsms-admin/template/template.docx")
	if err != nil {
		log.Fatalf("failed to open word template: %v", err)
	}
	doc := r.Editable()

	// 填充数据
	taskName := "Sample Task"
	details := "This is a sample task detail."

	content := doc.GetContent()
	content = replacePlaceholder(content, "TASK_NAME", taskName)
	content = replacePlaceholder(content, "DETAILS", details)
	doc.SetContent(content)

	// 保存为新文件
	outputFilePath := "/Users/songfayuan/GolandProjects/dsms-admin/template/filled_template.docx"
	err = doc.WriteToFile(outputFilePath)
	if err != nil {
		log.Fatalf("failed to save word document: %v", err)
	}

	fmt.Printf("Document saved to %s\n", outputFilePath)
}

结果

相关推荐
时光追逐者11 小时前
C# 哈希查找算法实操
算法·c#·哈希算法
wanzhong233311 小时前
学习triton-第1课 向量加法
开发语言·python·高性能计算
三千道应用题11 小时前
C#语言入门详解(18)传值、输出、引用、数组、具名、可选参数、扩展方法
开发语言·c#
micoos11 小时前
C#-LinqToObject-Element
c#
忧郁的蛋~12 小时前
使用.NET标准库实现多任务并行处理的详细过程
开发语言·c#·.net
dragon_perfect12 小时前
全流程基于Yolov8实现在Label-Studio实现半自动标注,已经把整个流程理清楚,把所有的坑解决。
开发语言·python·yolo·labelstudio
kalvin_y_liu12 小时前
四款主流深度相机在Python/C#开发中的典型案例及技术实现方案
开发语言·python·数码相机
劲镝丶12 小时前
malloc概述
c语言·开发语言·c++
1373i12 小时前
【Python】pytorch数据操作
开发语言·pytorch·python
努力努力再努力wz13 小时前
【C++进阶系列】:万字详解红黑树(附模拟实现的源码)
java·linux·运维·c语言·开发语言·c++