123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package utils
- import (
- "fmt"
- "github.com/xuri/excelize/v2"
- "reflect"
- )
- type ExcelColMapping struct {
- Col string
- Field string
- }
- func ExportExcel[T any](sheetName string, cols map[string]ExcelColMapping, dataList []T) (file *excelize.File, err error) {
- // 创建一个新的 Excel 文件
- file = excelize.NewFile()
- // 创建一个工作表
- index, err := file.NewSheet(sheetName)
- if err != nil {
- FileLog.Error("创建工作表失败:", err)
- }
- err = file.DeleteSheet("Sheet1")
- // 设置工作表的标题行
- for k, v := range cols {
- err = file.SetCellValue(sheetName, fmt.Sprintf("%s%d", k, 1), v.Col)
- if err != nil {
- FileLog.Error("创建column失败:", err)
- return
- }
- }
- // 添加一些示例数据
- row := 2
- for _, item := range dataList {
- for k, v := range cols {
- err = file.SetCellValue(sheetName, fmt.Sprintf("%s%d", k, row), getValue(item, v.Field))
- if err != nil {
- FileLog.Error("创建数据失败:", err)
- return
- }
- }
- row++
- }
- // 设置活动工作表
- file.SetActiveSheet(index)
- return
- }
- func getValue[T any](val T, fieldName string) (value interface{}) {
- obj := reflect.ValueOf(val)
- fmt.Println(fieldName)
- fieldVal := obj.FieldByName(fieldName)
- if !fieldVal.IsValid() {
- FileLog.Error("无效的字段名:", fieldName)
- return
- }
- return fieldVal.Interface()
- }
|