kefu/tools/xlsx.go

75 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-12-10 02:50:12 +00:00
package tools
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/xuri/excelize/v2"
"net/url"
"time"
)
// ExportExcelByMap 导出excel 数据源为[]map
func ExportExcelByMap(c *gin.Context, titleList []string, data []map[string]interface{}, fileName, sheetName string) error {
f := excelize.NewFile()
f.SetSheetName("Sheet1", sheetName)
header := make([]string, 0)
for _, v := range titleList {
header = append(header, v)
}
//表格样式
rowStyleID, _ := f.NewStyle(`{"font":{"color":"#666666","size":13,"family":"arial"},"alignment":{"vertical":"center","horizontal":"center"}}`)
_ = f.SetSheetRow(sheetName, "A1", &header)
_ = f.SetRowHeight(sheetName, 1, 30)
length := len(titleList)
headStyle := Letter(length)
var lastRow string
var widthRow string
for k, v := range headStyle {
if k == length-1 {
lastRow = fmt.Sprintf("%s1", v)
widthRow = v
}
}
if err := f.SetColWidth(sheetName, "A", widthRow, 30); err != nil {
return err
}
rowNum := 1
for _, item := range data {
row := make([]interface{}, 0)
//var dataSlice []string
//for key := range value {
// dataSlice = append(dataSlice, key)
//}
//sort.Strings(dataSlice)
for _, v := range header {
if val, ok := item[v]; ok {
row = append(row, val)
}
}
rowNum++
if err := f.SetSheetRow(sheetName, fmt.Sprintf("A%d", rowNum), &row); err != nil {
return err
}
if err := f.SetCellStyle(sheetName, fmt.Sprintf("A%d", rowNum), fmt.Sprintf("%s", lastRow), rowStyleID); err != nil {
return err
}
}
disposition := fmt.Sprintf("attachment; filename=%s-%s.xlsx", url.QueryEscape(fileName), time.Now().Format("2006-01-02"))
c.Writer.Header().Set("Content-Type", "application/octet-stream")
c.Writer.Header().Set("Content-Disposition", disposition)
c.Writer.Header().Set("Content-Transfer-Encoding", "binary")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
return f.Write(c.Writer)
}
// Letter 遍历a-z
func Letter(length int) []string {
var str []string
for i := 0; i < length; i++ {
str = append(str, string(rune('A'+i)))
}
return str
}