使用axios+koa+exceljs下载excel文件完整示例

环境

  • node: v12.16.1
    • “koa”: “^2.8.1”
    • “koa-body”: “^4.1.1”
    • “exceljs”: “^4.0.1”

示例

koa_excel.js

const koa = require('koa');
const koaBody = require('koa-body');
const fs = require('fs');
const ExcelJS = require('exceljs')

const APP = new koa();

APP.use(koaBody({
    jsonLimit: "8MB", // default: 56kb, change: 8MB
    textLimit: "8MB", // default: 56kb, change: 8MB
    formLimit: "8MB", // default: 56kb, change: 8MB
    multipart: true
}));

const PAGE = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>下载示例</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0-0/axios.min.js"></script>
</head>
<body>
    <div>
        <a href="/download">GET下载</a>
        <span>引起地址栏变更的GET方式请求,不能用ajax的GET请求</span>
    </div>
    <div>
        <button type="button" οnclick="download('blob')">POST下载(返回blob)</button>
        <span>ajax POST请求,返回blob</span>
    </div>
    <div>   
        <button type="button" οnclick="download('json')">POST下载(返回json)</button>
        <span>ajax POST请求,返回json</span>
    </div>
    <script>
        function download(response_type){
            
            axios({
                method: "post",
                url: "/download",
                data: {
                    response_type: response_type
                },
                responseType: response_type
            }).then(response => {
                console.log(response)
                let url=null;

                if ('blob'===response_type) {

                    url = window.URL.createObjectURL(response.data);
                    console.log(url);

                } else if('json'===response_type) {

                    url = window.URL.createObjectURL(new Blob([new Uint8Array(response.data.content.data)]));
                    console.log(url);
                }

                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'excel_demo.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

            }).catch(function (error) { // 请求失败处理
                alert(error);
              });
        }
    </script>
</body>
</html>`


APP.use(async ctx => {

    console.log(ctx)

    if (ctx.path === '/' && ctx.request.method === 'GET') {

        ctx.body = PAGE

    } else if (ctx.path === '/download') {

        if (ctx.request.method === 'GET') {

            ctx.response.attachment("excel_demo.xlsx")
            ctx.body = fs.createReadStream('excel_demo.xlsx')

        } else if (ctx.request.method === 'POST') {

            const workbook = new ExcelJS.Workbook() //creating workbook
            const worksheet = workbook.addWorksheet('sheet1') //creating worksheet

            // add column headers
            worksheet.columns = [
                { header: 'Album', key: 'album' },
                { header: 'Year', key: 'year' }
            ];

            // add row using keys
            worksheet.addRow({ album: "Taylor Swift", year: 2006 });

            // add rows the dumb way
            worksheet.addRow(["Fearless", 2008]);

            // add an array of rows
            const rows = [
                ["Speak Now", 2010],
                { album: "猎户星座", year: 2017 }
            ];

            worksheet.addRows(rows);

            // Write to local, File
            await workbook.xlsx.writeFile("excel_demo.xlsx")

            // Write to memory, buffer
            const buffer = await workbook.xlsx.writeBuffer()

            console.log('ctx.request.body: ', ctx.request.body)

            if ('blob' === ctx.request.body.response_type) {

                ctx.body = buffer

            } else if ('json' === ctx.request.body.response_type) {

                // object will be convert to json
                ctx.body = {
                    status: 'success',
                    content: buffer
                }
            }
            console.log('done')
        }
    }
});


APP.listen(5000)
console.log('start')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值