Golang 创建 Excel 文件
package excel
import (
"fmt"
"github.com/xuri/excelize/v2"
)
type SheetData struct {
SheetName string
Headers []string
Rows [][]interface{}
}
// GenerateExcelBySheets 生成 excel 表格
func GenerateExcelBySheets(sheets []SheetData) (*excelize.File, error) {
f := excelize.NewFile()
for _, sheet := range sheets {
if _, err := f.NewSheet(sheet.SheetName); err != nil {
return nil, err
}
for i, header := range sheet.Headers {
if err := f.SetCellValue(sheet.SheetName, GetCellName(i, 1), header); err != nil {
return nil, err
}
}
baseIndex := 2
if len(sheet.Headers) == 0 {
baseIndex = 1
}
for i, row := range sheet.Rows {
for j, val := range row {
if err := f.SetCellValue(sheet.SheetName, GetCellName(j, baseIndex+i), val); err != nil {
return nil, err
}
}
}
}
if len(sheets) > 0 {
f.SetActiveSheet(0)
}
return f, nil
}
// GetColumnName 获取列名 A-Z, AA-ZZ, AAA-ZZZ
func GetColumnName(col int) string {
if col < 26 {
return string(rune('A' + col))
}
return GetColumnName(col/26-1) + GetColumnName(col%26)
}
// GetCellName 获取单元格名称 A1, B2, AA1, AB1
func GetCellName(col, row int) string {
return fmt.Sprintf("%s%d", GetColumnName(col), row)
}