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

结果

相关推荐
superman超哥1 分钟前
Rust Link-Time Optimization (LTO):跨边界的全局优化艺术
开发语言·后端·rust·lto·link-time·跨边界·优化艺术
superman超哥2 分钟前
Rust 编译优化选项配置:释放性能潜力的精细调控
开发语言·后端·rust·rust编译优化·精细调控·编译优化选项
yyy(十一月限定版)3 分钟前
C++基础
java·开发语言·c++
月巴月巴白勺合鸟月半5 分钟前
用AI生成一个简单的视频剪辑工具 的后续
c#
玄同76511 分钟前
Python 异常捕获与处理:从基础语法到工程化实践的万字深度指南
开发语言·人工智能·python·自然语言处理·正则表达式·nlp·知识图谱
巴塞罗那的风13 分钟前
golang协程泄漏排查实战
开发语言·后端·golang
派大鑫wink18 分钟前
【Day21】NIO入门:通道、缓冲区与非阻塞IO基础
java·开发语言
quant_198618 分钟前
BTC 行情预警系统实战教程
开发语言·后端·python·websocket·程序人生·金融
世转神风-23 分钟前
qt-基础打印-不换行打印
开发语言·qt
DYS_房东的猫27 分钟前
学习总结笔记三:让网站“活”起来——处理静态文件、表单验证与用户登录(第3章实战版)
笔记·学习·golang