• 后端用node-xlsx生成excel表格,通过Buffer返回给前端,文件无效或文件损坏问题


    此问题没有修复前的效果,直接通过 res.end(xlsxBuffer),返回前端

    具体完整解决方案:见下

    服务端:
    1.node-xlsx的安装

    npm install node-xlsx --save


    2.单独抽出一个文件 写导表的逻辑
    附:https://www.npmjs.com/package/node-xlsx npm文档

    const xlsx = require('node-xlsx');
    // const fs = require('fs');
    
    /**
     * 创建表格
     * @param excelData
     * @param config 
     */
    function createExcel(excelData, config = {}){
        let xlsxBuildArr = [
            {
                name:'一班',
                data:[
                    ['姓名', '年龄'],
                    ['张三', 18],
                    ['李四', 19]
                ]
            },
            {
                name:'二班',
                data:[
                    ['姓名', '年龄'],
                    ['王五', 18],
                    ['刘六', 18]
                ]
            }
        ];
        let buffer = xlsx.build( xlsxBuildArr );
        // const filename = config.filename || 'fileName.xlsx';
        // //write  default utf-8
        // fs.writeFileSync(
        //     filename,
        //     buffer
        // );
        // console.log( filename + ' 文件已生成 √√√');
        return buffer;
    }
    
    module.exports = {
        createExcel
    }

    问题 解决方向:

    正如Luke在注释中提到的,您必须在发送缓冲区之前进行base64编码。下面是一个使用NPM模块node-xlsx的代码片段。

    后端路由 部分(我这里用的 express )

    const {createExcel} = require('../data-create/excel.js');
    
    // 导出 excel
    router.get('/downloadXlsx', function (req, res){
        // 这里根据 你的情况 来写 createExcel 
        const xlsxBuffer = createExcel(jimiJson, {});
        // res.setHeader('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8');
        // res.setHeader("Content-Disposition", "attachment; filename=aaa.xlsx");
        // res.send( xlsxBuffer );
        // res.end( xlsxBuffer, 'binary' );
        res.end( xlsxBuffer.toString('base64') );
    });

    前端页面 (以jquery 为例):

    $.ajax({
        url: UTILS.serverUrl + '/hash/downloadJimiXlsx',
        method: 'GET',
        data: {
            shopName: "xxxx"
        },
        success: (res)=>{
            function base64ToArrayBuffer(base64) {
                var binary_string = window.atob(base64);
                var len = binary_string.length;
                var bytes = new Uint8Array(len);
                for (var i = 0; i < len; i++) {
                    bytes[i] = binary_string.charCodeAt(i);
                }
                return bytes.buffer;
            }
            const blob = new Blob([base64ToArrayBuffer(res)], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
            });
            let downloadElement = document.createElement('a');
            let href = window.URL.createObjectURL(blob);
            downloadElement.href = href;
            downloadElement.download = `测试表格.xlsx`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement);
            window.URL.revokeObjectURL(href);
        }
    })

     参考:

    https://blog.csdn.net/qq_33890442/article/details/107090818

    https://www.it1352.com/1799083.html

  • 相关阅读:
    How to extract msu/msp/msi/exe files from the command line
    Windbg and resources leaks in .NET applications 资源汇总
    [c# 20问] 3.String和string的区别
    [c# 20问] 2.如何转换XML文件
    [c# 20问] 1. 何时使用class与struct
    安装配置BITS上传服务
    The J-Link hardware debugging Eclipse plug-in
    swift material
    SCLButton
    ChatCell
  • 原文地址:https://www.cnblogs.com/taohuaya/p/14310307.html
Copyright © 2020-2023  润新知