



























最近在做一个项目需要生成 Word 报告,试了几个库都不太满意,要么功能太简单,要么需要付费不完全开源。索性自己撸了一个,现在分享给大家。
市面上的 Go Word 库要么只能做简单的文本插入,要么需要安装 Office 或者 LibreOffice 。我需要的是:
// 创建表格很简单
table := doc.AddTable(&document.TableConfig{
Rows: 3, Columns: 4,
})
// 设置内容和样式
table.SetCellText(0, 0, "姓名")
table.MergeCells(0, 0, 0, 1) // 合并单元格
// 还有迭代器,方便批量处理
table.ForEach(func(info *document.CellInfo) {
if info.Row == 0 {
info.Cell.SetBackgroundColor("E6F3FF")
}
})
支持模板继承,可以定义基础模板然后扩展:
baseTemplate := `{{companyName}} 报告
{{#block "content"}}默认内容{{/block}}`
salesTemplate := `{{extends "base"}}
{{#block "content"}}
销售额:{{sales}}
新客户:{{customers}}
{{/block}}`
做了个简单的基准测试,生成同样的文档:
Go 确实快不少。
API 设计比较直观,支持链式调用:
doc := document.New()
doc.AddParagraph("标题").
SetStyle(style.StyleHeading1).
SetAlignment(document.AlignmentCenter)
doc.AddParagraph("正文内容").
SetFontFamily("微软雅黑").
SetFontSize(12).
SetColor("333333")
doc.Save("report.docx")
GitHub: https://github.com/ZeroHawkeye/wordZero
Gitee: https://gitee.com/Zmata_admin/WordZero
有详细的文档和示例,examples 目录下有各种使用场景的 demo 。
目前还在持续更新中,如果有需求或者 bug 欢迎提 issue 。
纯 Go 实现,零依赖,开箱即用。如果对你有帮助记得给个 star ⭐
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。