后端接收前端导入或者导出的请求

let bl = require('../bl/user.js')
//导出
        async download_user(){
            try {
                let result = await model.User.findAll({
                    attributes: ['username','address','telephone','email']
                })
                let arr = []
                for(var i=0 ;i<result.length;i++){
                    let username = result[i].username
                    let address = result[i].address
                    let telephone = result[i].telephone
                    let email = result[i].email
                    arr.push([username,address,telephone,email])
                }
                await bl.createWorkBook(arr)
                let src = path.join(__dirname, '../user.xlsx');
                let str = fs.readFileSync(src);
                let b = Buffer.from(str);
                let base64 = 'data:' + mineType.lookup(src) + ';base64,' + b.toString('base64');
                return {
                    filename: 'user.xlsx',
                    mimetype: mineType.lookup(src),
                    encoding: '',
                    content: base64
                }
            } catch (error) {
                return error
            }
        },

 //导入
        async upload_user(root,{fileContent}){
            try {
            let filePath = path.join(__dirname,'../router','user.xlse');//上传路径
            let reg = /data:(.*)base64,(.*)/;
            let base64 = reg.exec(fileContent); //提取文件内容
            let dataBuffer = Buffer.from(base64[2], 'base64'); //把base64码转成buffer对象,
            //二进制文件存在服务器
            fs.writeFileSync(filePath, dataBuffer);
            let result = await bl.analysisWorkBook(filePath)
                result.map(async function(item){
                   let userdata = item[0].split(',')
                   await model.User.create({id:tbit.id(),username:userdata[0],address:userdata[1],telephone:userdata[2],email:userdata[3]})
                })
                return true
            } catch (error) {
                return error
            }

        },

bl.user里面这么写获取xlsx文件
引用的包 npm i xlsx

//导出表格
const xlsx = require('xlsx');
async function createWorkBook(arrayData){
    try {
        arrayData.unshift(['Name','Address','Telephone','Email'])
        let arrayWorkSheet = xlsx.utils.aoa_to_sheet(arrayData);
        let workBook = {
            SheetNames: ['user'],
            Sheets: {
              'user': arrayWorkSheet,
            }
          };
          // 将workBook写入文件
          xlsx.writeFile(workBook, "./user.xlsx");
    } catch (error) {
        return error
    }
}
//解析xlsx
async function analysisWorkBook(path){
    try {
        let workbook = xlsx.readFile(path);
        let sheetNames = workbook.SheetNames;
        // 获取第一个workSheet
        let sheet1 = workbook.Sheets[sheetNames[0]];
        // console.log(sheet1);
    
        let range = xlsx.utils.decode_range(sheet1['!ref']);
    
        //循环获取单元格值
        let arr = []
        for (let R = range.s.r; R <= range.e.r; ++R) {
        let row_value = '';
        for (let C = range.s.c; C <= range.e.c; ++C) {
            let cell_address = {c: C, r: R}; //获取单元格地址
            let cell = xlsx.utils.encode_cell(cell_address); //根据单元格地址获取单元格
            //获取单元格值
            if (sheet1[cell]) {
            // 如果出现乱码可以使用iconv-lite进行转码
            // row_value += iconv.decode(sheet1[cell].v, 'gbk') + ", ";
            row_value += sheet1[cell].v + ", ";
            } else {
            row_value += ", ";
            }
        }
        arr.push([row_value])
        }
        arr.shift()
        return arr
    } catch (error) {
        return error
    }
}

module.exports = {
    createWorkBook,
    analysisWorkBook
}

思路:
1.导入:将文件传入代码文件夹下,然后调用 analysisWorkBook()方法解析xlsx,解析完处理数据存入数据库
2.导出:将数据库查询出来的数据调用 createWorkBook()方法生成一个user.xlsx文件,然后导出

你可能感兴趣的:(后端接收前端导入或者导出的请求)