安装excelize库:
go get github.com/xuri/excelize/v2@v2.5.0
logic文件
import (
"bytes"
"context"
"fmt"
"github.com/xuri/excelize/v2"
"io"
"github.com/zeromicro/go-zero/core/logx"
)
type ExportOutStockSummaryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
writer io.Writer
}
type UserData struct {
Name string
Age int
Gender string
}
func NewExportOutStockSummaryLogic(ctx context.Context, svcCtx *svc.ServiceContext, writer io.Writer) *ExportOutStockSummaryLogic {
return &ExportOutStockSummaryLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
writer: writer,
}
}
func (l *ExportOutStockSummaryLogic) ExportOutStockSummary(req *types.OutStockSummaryRequest) error {
// todo: add your logic here and delete this line
data := []UserData{
{Name: "张三", Age: 18, Gender: "男"},
{Name: "李四", Age: 20, Gender: "女"},
{Name: "王五", Age: 22, Gender: "男"},
}
//var res []interface{}
//for _, trip := range data {
// res = append(res, trip)
//}
excel, err := l.ToExcel([]string{"姓名", "年龄", "性别"}, data)
if err != nil {
return err
}
l.writer.Write(excel)
return nil
}
func (l *ExportOutStockSummaryLogic) ToExcel(titleList []string, dataList []UserData) (content []byte, err error) {
file := excelize.NewFile()
// 添加sheet页
sheet := file.NewSheet("Sheet1")
file.SetActiveSheet(sheet)
// 插入表头
for i, v := range titleList {
cellName, _ := excelize.CoordinatesToCellName(i+1, 1)
file.SetCellValue("Sheet1", cellName, v)
}
// 插入内容
for i, v := range dataList {
row := i + 2 //从第二行开始插入数据
//cellName, _ := excelize.CoordinatesToCellName(i+1, 2)
//file.SetCellValue("sheet1", cellName, v)
cells := []interface{}{v.Name, v.Age, v.Gender}
if err := file.SetSheetRow("Sheet1", fmt.Sprintf("A%d", row), &cells); err != nil {
return nil, err
}
}
var buffer bytes.Buffer
_ = file.Write(&buffer)
//content = bytes.NewReader(buffer.Bytes())
return buffer.Bytes(), nil
}
handler.go
import (
"net/http"
"cntt_sort/internal/logic/sorting"
"cntt_sort/internal/svc"
"cntt_sort/internal/types"
"github.com/zeromicro/go-zero/rest/httpx"
)
func ExportOutStockSummaryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.OutStockSummaryRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := sorting.NewExportOutStockSummaryLogic(r.Context(), svcCtx, w)
w.Header().Add("Content-Disposition", "attachment; filename=test.xls")
w.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
err := l.ExportOutStockSummary(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.Ok(w)
}
}
}