前端用js实现预览go接口返回的excel

 go接口中响应一个html页面


// ExcelShow  数据显示为excel
func ExcelShow(ctx context.Context, req ghttp.Request) ghttp.Response {

	return ghttp.NewHTMLResponse(http.StatusOK, []byte(`
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>excel预览</title>
    <link rel="stylesheet" href="/static/js-preview-lib/excel.css" />
    <script src="/static/js-preview-lib/excel.umd.js"></script>
</head>
<body>
<div id="excel" style="width: 100vw; height: 100vh"></div>

<script>
    const myExcelPreviewer = jsPreviewExcel.init(document.getElementById('excel'));
    myExcelPreviewer .preview('/xxx/data?is_show=true&page=1&perPage=99999999&is_weight=0').then(()=>{
        console.log('预览完成');
    }).catch(e=>{
        console.log('预览失败', e);
    })
</script>
</body>
</html>
`))
}

go接口中返回一个excel文件:如果你不 知道怎么生成excel内容,请参考我前面的文章

// GETxxx 获取xxx数据
func GETxxx(ctx context.Context, req ghttp.Request) ghttp.Response {
	params := &roimodel.xxxParams{}

	if err := request.ShouldBind(req, &params); err != nil {
		return response.StdErrorResponseWithMsg(response.InvalidParams, err.Error())
	}

	data, err := xxxservice.GETData(ctx, params)
	if err != nil {
		return response.StdErrorResponseWithMsg(response.Failed, err.Error())
	}
	
	if params.IsShow {
		reader, _ :=xxxdata.ShowExcelTable1(data)
		contentType := mime.TypeByExtension(".xlsx")
		return response.StdResponseStream(contentType, reader)
	}
	return response.StdSuccess(data)

}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值