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

结果

相关推荐
常利兵几秒前
Kotlin 助力 Android 启动“大提速”
android·开发语言·kotlin
黎梨梨梨_几秒前
C++入门基础(上)(namespace和缺省参数)
开发语言·c++
卢锡荣14 分钟前
单芯双 C 盲插,一线通显电 ——LDR6020P 盲插 Type‑C 显示器方案深度解析
c语言·开发语言·ios·计算机外设·电脑
legendary_16314 分钟前
PD显示器方案新维度:Type-C充电,投屏,显示技术革新
c语言·开发语言·计算机外设
ic爱吃蓝莓15 分钟前
美团测开一面
java·开发语言
sghuter15 分钟前
AI赋能CI/CD:Gemini实战脚本生成
开发语言·人工智能·ci/cd·青少年编程·r语言
me83215 分钟前
【深入java语句】关于System.out.println();的底层逻辑
java·开发语言
呆萌很19 分钟前
【GO】goroutine 协程练习题
golang
1candobetter20 分钟前
JAVA后端开发——多模块 Maven 项目 POM 管理规范实践
java·开发语言·maven
光电笑映23 分钟前
深入C++异常:栈展开、异常安全与工程规范
开发语言·c++·c