45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
package app
|
|
|
|
import (
|
|
"bytes"
|
|
"code.hoteas.com/golang/hotime/common"
|
|
"fmt"
|
|
"github.com/tealeg/xlsx"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func DataToExcel(w http.ResponseWriter, r *http.Request, titleList []string, dataList []common.Map, fileName string) {
|
|
// 生成一个新的文件
|
|
file := xlsx.NewFile()
|
|
// 添加sheet页
|
|
sheet, _ := file.AddSheet("Sheet1")
|
|
// 插入表头
|
|
titleRow := sheet.AddRow()
|
|
for _, v := range titleList {
|
|
cell := titleRow.AddCell()
|
|
cell.Value = v
|
|
cell.GetStyle().Font.Color = "00FF0000"
|
|
}
|
|
for _, v1 := range dataList {
|
|
row := sheet.AddRow()
|
|
// 插入内容
|
|
for _, v := range titleList {
|
|
cell := row.AddCell()
|
|
cell.SetValue(v1.Get(v))
|
|
}
|
|
|
|
}
|
|
//file.Save("D:\\temp\\vip_excel"+fileName)
|
|
|
|
fileName = fmt.Sprintf("%s.xlsx", fileName)
|
|
//_ = file.Save(fileName)
|
|
w.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
|
|
w.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
|
|
|
var buffer bytes.Buffer
|
|
_ = file.Write(&buffer)
|
|
content := bytes.NewReader(buffer.Bytes())
|
|
http.ServeContent(w, r, fileName, time.Now(), content)
|
|
}
|