主要是使用第三方的tealeg/xlsx
包来生成excel文件
package main
import (
"bytes"
"fmt"
"github.com/gin-gonic/gin"
"github.com/tealeg/xlsx"
"net/http"
)
type RowData struct {
UserName string
Age int
StuId int
}
func FileDownload(c *gin.Context) {
file := xlsx.NewFile()
sheet, err := file.AddSheet("Sheet1")
if err != nil {
fmt.Printf(err.Error())
}
//表头
row := sheet.AddRow()
titleList := []string{"姓名", "年龄", "学号"}
for _, v := range titleList{
cell := row.AddCell()
cell.Value = v
}
//示例数据
dataList := []*RowData{&RowData{"chasel",03,1001},&RowData{"zyer",04,1002},&RowData{"wangwu",05,1003}}
for _, v := range dataList{
row := sheet.AddRow()
row.WriteStruct(v, -1)
}
filename := "demo.xlsx"
c.Writer.Header().Add("Content-Disposition",fmt.Sprintf("attachment; filename=%s", filename)) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
c.Writer.Header().Add("Content-Type", "application/octet-stream")
var buffer bytes.Buffer
_ = file.Write(&buffer)
fileContent := buffer.Bytes()
c.Data(http.StatusOK, "application/octet-stream", fileContent)
}
func main() {
r := gin.Default()
r.GET("/download", FileDownload)
r.Run(":8080") // listen and serve on :8080
}
启动服务器:
访问http://localhost:8080/download
下载到本地