1 Star 0 Fork 0

igo/pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
excel.go 1.98 KB
一键复制 编辑 原始数据 按行查看 历史
layte.xiao 提交于 2023-12-09 19:02 . 加密
package xutils
import (
"encoding/csv"
"errors"
"fmt"
"github.com/xuri/excelize/v2"
"os"
"path/filepath"
)
type ExcelHeader struct {
Index int
Title string
}
func CreateExcel(filename string, data [][]string) error {
if len(data) == 0 {
return errors.New("empty data")
}
ext := filepath.Ext(filename)
if ext == ".csv" {
fh, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0777)
if err != nil {
return err
}
defer fh.Close()
return csv.NewWriter(fh).WriteAll(data)
}
fh := CreateExcelFileWithData(data)
defer fh.Close()
return fh.SaveAs(filename)
}
// CreateExcelFileWithData 生成*excelize.File
func CreateExcelFileWithData[T any](data [][]T) *excelize.File {
fh := excelize.NewFile()
list := fh.GetSheetList()
name := list[0]
i := 0
for _, v := range data {
if len(data) == 0 {
continue
}
i++
for index, vv := range v {
fh.SetCellValue(
name,
fmt.Sprintf("%s%d", index2Char(index), i),
vv,
)
}
}
return fh
}
// CreateExcelFileWithHeader 生成*excelize.File,通过设置头部字段来实现,头部和数据进行分离
func CreateExcelFileWithHeader(headers map[string]*ExcelHeader, rows []map[string]any) *excelize.File {
f := excelize.NewFile()
sheetName := "Sheet1"
index, _ := f.NewSheet(sheetName)
f.SetActiveSheet(index)
// 填充单元格
// 写头
for _, v := range headers {
axis := formatExcelAxis(1, v.Index)
f.SetCellValue(sheetName, axis, v.Title)
}
// 写内容
for r, v := range rows {
for k, vv := range v {
if header, ok := headers[k]; ok {
axis := formatExcelAxis(r+2, header.Index)
f.SetCellValue(sheetName, axis, vv)
}
}
}
return f
}
func index2Char(index int) string {
r := make([]byte, 0)
r = append(r, byte(index%26+65))
index = index / 26
for index > 0 {
index = index - 1
r = append([]byte{byte(index%26 + 65)}, r...)
index = index / 26
}
return string(r)
}
func formatExcelAxis(r, index int) string {
b := index2Char(index)
return fmt.Sprintf("%s%d", b, r)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/igolang/pkg.git
git@gitee.com:igolang/pkg.git
igolang
pkg
pkg
v1.27.0

搜索帮助