ai_scheduler/internal/domain/tools/common/excel_generator/client.go

77 lines
1.6 KiB
Go

package excel_generator
import (
"fmt"
"github.com/go-kratos/kratos/v2/log"
"github.com/xuri/excelize/v2"
)
// Client Excel 生成器
type Client struct{}
func New() *Client {
return &Client{}
}
// Call 根据模板和数据生成 Excel 字节流
// templatePath: 模板文件路径
// data: 二维字符串数组,不再使用反射
// startRow: 数据填充起始行 (默认 2)
// styleRow: 样式参考行 (默认 2)
func (g *Client) Call(templatePath string, data [][]string, startRow int, styleRow int) ([]byte, error) {
if startRow <= 0 {
startRow = 2
}
if styleRow <= 0 {
styleRow = 2
}
f, err := excelize.OpenFile(templatePath)
if err != nil {
return nil, err
}
defer f.Close()
sheet := f.GetSheetName(0)
// 获取样式和行高
styleID, err := f.GetCellStyle(sheet, fmt.Sprintf("A%d", styleRow))
if err != nil {
log.Errorf("获取样式失败: %v", err)
styleID = 0
}
rowHeight, err := f.GetRowHeight(sheet, styleRow)
if err != nil {
log.Errorf("获取行高失败: %v", err)
rowHeight = 31 // 默认高度
}
row := startRow
for i, item := range data {
currentRow := row + i
// 设置行高
f.SetRowHeight(sheet, currentRow, rowHeight)
// 填充数据
for col, value := range item {
cell := fmt.Sprintf("%c%d", 'A'+col, currentRow)
f.SetCellValue(sheet, cell, value)
}
// 设置样式
if styleID != 0 {
endCol := 'A' + len(item) - 1
f.SetCellStyle(sheet, fmt.Sprintf("A%d", currentRow), fmt.Sprintf("%c%d", endCol, currentRow), styleID)
}
}
buf, err := f.WriteToBuffer()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}