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

结果

相关推荐
格林威10 分钟前
工业视觉检测:两大主流异常检测开源框架深度对比(PatchCore vs SPADE)
开发语言·人工智能·深度学习·数码相机·计算机视觉·视觉检测·工业相机
2zcode15 分钟前
基于Matlab元胞自动机模拟(CA)静态再结晶过程
开发语言·matlab·静态再结晶
研究点啥好呢19 分钟前
滴滴Go后端开发工程师面试题精选:10道高频考题+答案解析
java·开发语言·golang
Levin__NLP_CV_AIGC20 分钟前
py文件中文件复制方法
开发语言·python
yong999024 分钟前
EKF-SLAM在MATLAB上的仿真实现
开发语言·matlab
广州山泉婚姻27 分钟前
C语言三种基本程序结构详解
c语言·开发语言
xiaohe0728 分钟前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
上弦月-编程31 分钟前
【C语言】函数栈帧的创建与销毁(底层原理)
c语言·开发语言
eqwaak034 分钟前
PyTorch张量操作全攻略:从入门到精通
开发语言·人工智能·pytorch·python
辞旧 lekkk35 分钟前
【Qt】初识(上)
开发语言·数据库·qt·学习·萌新