golang+gin+vue操作execl返回给客户端

763 阅读1分钟

大家有没有遇到在公司偶尔会出现bs架构的项目导出execl等之类的功能如下图

image.png

话不多说直接上代码,本次代码组合为golang+gin框架做路由,客户端采用vue+element ui。

gin 框架的依赖

go get -u github.com/gin-gonic/gin

execl 的依赖

go get -u github.com/tealeg/xlsx

直接main函数中操作代码就完事了。

package main  
  
import (  
"fmt"  
"github.com/gin-gonic/gin"  
"github.com/tealeg/xlsx"  
)  
  
func main() {  
r := gin.Default()  
r.GET("/downFile", func(c *gin.Context) {  
  
file := xlsx.NewFile()  
sheet, err := file.AddSheet("人员信息收集")  
if err != nil {  
panic(err.Error())  
}  
row := sheet.AddRow()  
cell := row.AddCell()  
cell.Value = "姓名"  
cell = row.AddCell()  
cell.Value = "性别"  
  
row2 := sheet.AddRow()  
cell = row2.AddCell()  
cell.Value = "张三"  
cell = row2.AddCell()  
cell.Value = "男"  
  
row2 = sheet.AddRow()  
cell = row2.AddCell()  
cell.Value = "李四"  
cell = row2.AddCell()  
cell.Value = "女"  
  
err = file.Save("./demo6/demo.xlsx")  
if err != nil {  
panic(err.Error())  
}  
  
c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "demo.xlsx")) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名  
c.Writer.Header().Add("Content-Type", "application/octet-stream")  
c.File("demo.xlsx")  
})  
  
err := r.Run(":18000")  
if err != nil {  
return  
}  
}

下面上前端vue代码

async getOutPutAsset(){  
// 发送GET请求并下载文件  
axios({  
url: '/outPutAsset',  
method: 'GET',  
responseType: 'blob', // 将响应数据视为二进制流  
}).then((response) => {  
console.log("服务器返回的数据:",response)  
if (response.data.size === 0){  
this.$message.info("没有ip资产可以导出")  
}else {  
const url = window.URL.createObjectURL(new Blob([response.data]))  
const link = document.createElement('a')  
link.href = url  
link.setAttribute('download', 'demo.xlsx') // 设置文件名,可以从response中获取  
document.body.appendChild(link)  
link.click()  
}  
  
}).catch(error=>{  
this.$message.info("没有ip资产可以导出")  
})  
  
}

最后上效果图

image.png

ok 以上就是gin框架返回客户端execl操作具体代码。代码量不多·我就不上git地址了。大家自行copy 一下就可以跑起来。