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

结果

相关推荐
冷雨夜中漫步4 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
暖馒6 小时前
Modbus应用层协议的深度剖析
网络·网络协议·c#·wpf·智能硬件
m0_736919106 小时前
C++代码风格检查工具
开发语言·c++·算法
2501_944934736 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖7 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472468 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ8 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly2024068 小时前
C++ 文件和流
开发语言
m0_706653238 小时前
分布式系统安全通信
开发语言·c++·算法
2501_941982059 小时前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信