1.依赖包
import (
"github.com/tealeg/xlsx"
)
2.示例
func (o *orderController) Export(request *restful.Request, response *restful.Response) {
username := request.Attribute(filters.UserName).(string)
orderService := service.NewOrderService(o.Db)
orders, _ := orderService.ListUserOrders(username)
file := xlsx.NewFile()
sheet, _ := file.AddSheet("订单信息")
titles := []string{"服务类型", "订单号", "创建时间", "订单类型", "订单金额(元)", "订单状态", "原因"}
row := sheet.AddRow()
var cell *xlsx.Cell
for _, title := range titles {
cell = row.AddCell()
cell.Value = title
}
for _, order := range *orders {
values := []string{
getServiceTypeStr(*order.ServiceType),
order.Id,
order.CreateTime.Format("2006-01-02 15:04:05"),
getOrderTypeStr(*order.OrderType),
"1",
getOrderStatusStr(*order.Status),
order.Reason,
}
row = sheet.AddRow()
for _, value := range values {
cell = row.AddCell()
cell.Value = value
}
}
filename := "订单信息" + ".xlsx"
response.AddHeader("Content-Type", "application/octet-stream")
response.AddHeader("Content-Disposition", "attachment; filename="+filename)
response.AddHeader("Content-Transfer-Encoding", "binary")
//回写到web 流媒体 形成下载
_ = file.Write(response.ResponseWriter)
}
3.分析
3.1先根据需求查询需要的list对象
3.2新建文件,设置文件名,跟列名
3.3设置单元格
3.4设置内容单元格
3.5流媒体返回web
这个示例是没有封装过的,如果想要封装,可以参考我的另一篇文章,下面是链接,喜欢小编的点点关注
到此这篇关于golang实现浏览器导出excel文件功能的文章就介绍到这了,更多相关golang excel文件导出内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!