准备工作:
首先需要下载需要的对应包
echo框架包:github.com/labstack/echo
excel包:github.com/tealeg/xlsx
代码部分:
package main
import(
"bytes"
"fmt"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/tealeg/xlsx"
)
func main(){
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
//路由设置
e.GET("/download", fileDownload)
//设置启动端口
e.Logger.Fatal(e.Start(":8080"))
}
//文件下载
func fileDownload(c echo.Context) error {
name := "test.xlsx"
xFile := xlsx.NewFile()
sheet, err := xFile.AddSheet("test")
if err != nil {
panic(err)
}
header := []string{"姓名", "性别", "年龄"}
r := sheet.AddRow()
var ce *xlsx.Cell
for _, v := range header {
ce = r.AddCell()
ce.Value = v
}
for i:=1;i<5;i++{
r = sheet.AddRow()
ce = r.AddCell()
ce.Value = "张三"
ce = r.AddCell()
ce.Value = "男"
ce = r.AddCell()
ce.Value = fmt.Sprintf("%d",23)
}
//将数据存入buff中
var buff bytes.Buffer
if err = xFile.Write(&buff); err != nil {
panic(err)
}
//设置请求头 使用浏览器下载
c.Response().Header().Set(echo.HeaderContentDisposition, "attachment; filename="+name)
return c.Stream(http.StatusOK, echo.MIMEOctetStream, bytes.NewReader(buff.Bytes()))
}
技术不精,如有不当之处,请告知