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

结果

相关推荐
毒鸡蛋几秒前
绘制火山图 R、python
开发语言·python·r语言
听风吟丶1 分钟前
Java 响应式编程实战:Spring WebFlux+Reactor 构建高并发电商系统
java·开发语言·spring
Aerelin4 分钟前
爬虫图片采集(自动化)
开发语言·前端·javascript·爬虫·python·html
枫叶丹47 分钟前
浙人医信创实践:电科金仓异构多活架构破解集团化医院转型难题
开发语言·数据库·架构
野生技术架构师7 分钟前
Kafka深度剖析:Topic-Partition-Segment 关系、分区策略与数据可靠性实现
kafka·c#·linq
小李小李快乐不已8 分钟前
图论理论基础(2)
java·开发语言·c++·算法·图论
Sheffi669 分钟前
Objective-C 黑魔法:Method Swizzling 的正确姿势与滥用风险
开发语言·macos·objective-c
AI_567814 分钟前
MES+物联网传感器重塑设备管理体系
开发语言·php
gc_229914 分钟前
学习C#调用AspNetCoreRateLimit包限制客户端访问次数(3:动态配置)
c#·限流·动态配置·coreratelimit