Skip to content

excel 是结构体 tag 驱动的通用 xlsx 导出(excel:"表头" + 可选 excelDict);tree 是树形结构构建工具,复刻 hutool Tree 的扁平 JSON 形态。两者都不涉及业务逻辑,只做数据形态转换。

关键导出

  • excel.Write[T any](rows []T, opts Options) (*bytes.Buffer, error) 生成 xlsx 字节流
  • excel.Export(c *gin.Context, rows, sheetName) error 直接写出下载响应
  • excel.Options{SheetName, MaxRows};常量 MaxRows=100000
  • tree.Tree[K comparable] struct{ID, ParentID K; Name string; Weight int; Extra map[string]any; Children []*Tree[K]}MarshalJSON 把固定字段与 Extra 拍平成单层)
  • tree.Build[T,K](list, rootID, parse) []*Tree[K] 单根,按 Weight 稳定升序
  • tree.BuildMultiRoot[T,K](list, getID, getParentID, parse) []*Tree[K] 多根(悬空父级当根)
  • tree.BuildInPlace[T,K](items, rootID, getID, getParentID, setChildren) []T 就地构树不排序

典型用法

go
// internal/system/handler/client_handler.go:68
rows, err := systemservice.ClientSvcApp.QueryList(c.Request.Context(), q, excel.MaxRows+1)
if err := excel.Export(c, rows, "客户端管理"); err != nil { /* ... */ }

// internal/system/service/dept_service.go:110
tree.BuildMultiRoot(rows, func(d *vo.SysDeptVo) int64 { return d.DeptID }, /* ... */)

// internal/system/service/menu_service.go:93
tree.BuildInPlace(menus, constant.ConstantTopParentID, getID, getParentID, setChildren)

坑/约定

WARNING

  • excel 超限返回业务异常而非截断(静默少行的审计表比失败危险);表头按文本格式存(避免 1-2 被识别成日期);列宽按内容自适应,中日韩字符双宽;工作簿全程在内存里建满再落笔,超大导出需改用 StreamWriter(但与自适应列宽冲突)。
  • tree children 为空时省略该键(前端靠键有无判断叶子,必须照搬 hutool);Extra 按键名字典序输出(Go map 无序,否则 golden 测试无从做);MarshalJSON 内部走 pkg/jsonx(雪花 id 要走全局 int64 编码器,否则树接口的 id 形态与别处不一致); BuildInPlace 不排序,依赖 SQL ORDER BY parent_id, order_num。 :::

相关页:/pkg-reference/jsonx-snowflake/pkg-reference/oss/modules/system

基于 MIT 协议开源