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

结果

相关推荐
bjxiaxueliang14 分钟前
一文掌握Python aiohttp:异步Web开发从入门到部署
开发语言·前端·python
想搞艺术的程序员17 分钟前
Go RWMutex 源码分析:一个计数器,如何把“读多写少”做得又快又稳
开发语言·redis·golang
吴声子夜歌21 分钟前
JavaScript——JSON序列化和反序列化
开发语言·javascript·json
cui_ruicheng40 分钟前
C++11新特性(中):右值引用与移动语义
开发语言·c++·c++11
2401_8732046541 分钟前
C++与Node.js集成
开发语言·c++·算法
小小张自由—>张有博44 分钟前
【深度解析】从 claude 命令到 cli.js 的完整执行链路
开发语言·javascript·ecmascript
阿kun要赚马内1 小时前
Python——异常捕获
开发语言·python
☆5661 小时前
基于C++的区块链实现
开发语言·c++·算法
于先生吖1 小时前
JAVA 本地生活服务项目实战 家政 5.0 系统前后端分离部署
java·开发语言·生活
计算机安禾1 小时前
【数据结构与算法】第5篇:线性表(一):顺序表(ArrayList)的实现与应用
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio