对NodeJS xlsx模块的简单封装

2017-03-17  本文已影响0人  灵魂放逐

本来只是想写个NodeJS爬虫,中间涉及到一点Excel。找了找Excel模块,xlsx模块在npm官网上搜索排名很靠前,就选了它,star数还比较可观。仔细了解了xlsx模块才发现这玩意生成Excel文件实在太麻烦,搜索网上的博客,那些人都是互相抄袭,代码也不够优雅。得了,还是我自己造轮子吧。
  注释很详细,直接上代码:

    const XLSX = require('xlsx');
    
    class WorkBook {
        /**
         * @param {Object} data Excel表格源数据,格式如下:
         * {
         *      Sheet1: [
         *          ['姓名', '学号', '籍贯'],
         *          ['lxz', '10131911', 'hunan']
         *      ]
         * }
         */
        constructor(srcData) {
            this.srcData = srcData;
            this.workbook = {};
            this.workbook.SheetNames = [];
            this.workbook.Sheets = {};
    
            for(let item in srcData) {
                this.workbook.SheetNames.push(item);
                this.addSheet(item, srcData[item]);
            }
        }
    
        /**
         * 往Excel文件添加一个表格
         * @param {string} sheetName 表格名
         * @param {object} sheet 表格数据
         * @returns void
         */
        addSheet(sheetName, sheet) {
            this.workbook['Sheets'][sheetName] = {};
            let row = sheet.length;
            let col = sheet[0].length;
            let to = '';
    
            for(let i=0; i<row; i++) {
                for(let j=0; j<col; j++) {
                    let key = this.ten2twentysix(j+1) + (i+1);
                    this.workbook['Sheets'][sheetName][key] = {'v': sheet[i][j]};
                    to = key;
                }
            }
            this.workbook['Sheets'][sheetName]['!ref'] = 'A1:' + to;
        }
    
    
        /**
         * 10进制转26进制
         * @param {number} num 正整数
         * @returns string
         */
        ten2twentysix(num) {
            let str = '';
            while(num) {
                let rest = num % 26;
                num = (num-rest) / 26;
                str += String.fromCharCode(rest + 64);
            }
    
            let twentysixNumber = '';
            let len = str.length;
            for(let i=len-1; i>=0; i--) {
                twentysixNumber += str[i];
            }
    
            return twentysixNumber;
        }
    
        /**
         * 将数据写入Excel
         * @param {string} filename 文件路径
         */
        writeFile(filename) {
            XLSX.writeFile(this.workbook, filename);
        }
    }
    
    module.exports = WorkBook;
上一篇下一篇

猜你喜欢

热点阅读