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

结果

相关推荐
端庄的战斗机23 分钟前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
开发小程序的之朴38 分钟前
认识安企CMS-安装安企CMS的环境要求
nginx·golang·系统架构
Full Stack Developme1 小时前
Java LRU 与 LFU 算法及应用
java·开发语言·算法
C语言小火车2 小时前
C++ 堆排序深度精讲:基于完全二叉树的选择排序进化,最坏情况 O(n log n) 的稳定王者
开发语言·c++·算法·排序算法·堆排序
北冥you鱼3 小时前
abigen 最佳实践:从入门到精通,高效生成 Go 语言合约绑定
开发语言·golang·区块链
ALex_zry3 小时前
C++26 std::complex 结构化绑定详解:auto [re, im] = c
c语言·开发语言·c++
她说..4 小时前
Java 默认值设置方式
java·开发语言·后端·springboot
忧郁的紫菜5 小时前
基础实现:单篇 Markdown 转 Word
开发语言·c#·word
甜美的小天鹅5 小时前
Swifter C#之inline还是不inline,这是个问题
开发语言·c#
小短腿的代码世界5 小时前
Qt Bluetooth源码深度解析:从HCI协议到跨平台API的完整架构
开发语言·qt·架构