Documentation
¶
Overview ¶
Package excel 提供基于模板的 Excel 导入导出:泛型列表导出/导入, 依赖用户预调好的 .xlsx 模板文件(样式/格式/公式),数据区域按行填充。 映射规则:struct tag `excel:"列名"` 匹配模板表头;无 tag 时用字段名匹配。
Index ¶
- func ContentDisposition(filename string) string
- func Export[T any](tpl Template, data []T, writer io.Writer) error
- func ExportBatch[T any](tpl Template, data []T, outputPath string, batch BatchConfig) error
- func ExportBatchToWriter[T any](tpl Template, data []T, writer io.Writer, batch BatchConfig) error
- func ExportMultiSheet[T any](sheets []SheetData[T], outputPath string) error
- func ExportName(name string, suffix ...string) string
- func ExportToFile[T any](tpl Template, data []T, outputPath string) error
- func Import[T any](tpl Template, reader io.Reader) ([]T, error)
- func ImportFromFile[T any](tpl Template, inputPath string) ([]T, error)
- type BatchConfig
- type RowError
- type SheetData
- type Template
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContentDisposition ¶ added in v1.55.0
ContentDisposition 生成 HTTP Content-Disposition 响应头值, 兼容中文文件名(RFC 5987 编码 + ASCII fallback):
attachment; filename="export_20260817.xlsx"; filename*=UTF-8''%E8%AE%A2%E5%8D%95%E5%AF%BC%E5%87%BA_20260817.xlsx
用法:
w.Header().Set("Content-Disposition", excel.ContentDisposition("订单导出_20260817_233700.xlsx"))
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
func Export ¶
Export 将泛型数据列表按模板填充到 writer(返回 .xlsx 字节流)。 模板的数据区域从 DataStartRow 开始,每行对应 data 的一项,列序按模板表头匹配。
func ExportBatch ¶ added in v1.54.0
func ExportBatch[T any](tpl Template, data []T, outputPath string, batch BatchConfig) error
ExportBatch 分批写入大量数据,降低内存峰值。 每批写入 BatchSize 行后调 f.Save() 刷盘;OnProgress 回调进度。 适用于万行以上导出场景(HTTP 请求异步生成文件,前端轮询进度)。
func ExportBatchToWriter ¶ added in v1.54.0
ExportBatchToWriter 分批写入到 io.Writer(流式 HTTP 下载场景)。 与 ExportBatch 类似,但输出到 Writer 而非文件。
func ExportMultiSheet ¶ added in v1.54.0
ExportMultiSheet 将多个 sheet 的数据一次性导出到同一 Excel 文件。 每个 sheet 使用各自的模板配置(可为不同模板文件或同一文件不同 sheet)。
func ExportName ¶ added in v1.55.0
ExportName 构造导出文件名:业务名 + 时间戳后缀 + .xlsx 扩展。 中文安全:Go 字符串原生 UTF-8,HTTP 响应头用 RFC 5987 编码(Content-Disposition)。 防覆盖:时间戳精度到秒(yyyyMMddHHmmss),同一秒内多次导出加序号。
用法:
filename := excel.ExportName("订单导出") // 订单导出_20260817_233700.xlsx
filename := excel.ExportName("orders") // orders_20260817_233700.xlsx
filename := excel.ExportName("订单导出", "2026-08") // 订单导出_2026-08.xlsx(自定义后缀)
func ExportToFile ¶
ExportToFile 将泛型数据列表按模板填充到输出文件。
Types ¶
type BatchConfig ¶ added in v1.54.0
type BatchConfig struct {
// BatchSize 每批写入行数(默认 1000);0 表示不分批。
BatchSize int
// OnProgress 进度回调(已写入行数,总行数),nil 不回调。
OnProgress func(written, total int)
}
BatchConfig 分批写入配置。