首页 > 技术文章 > nodeJS生成xlsx以及设置样式

hellohello 2019-07-24 19:27 原文

参考:

https://www.npmjs.com/package/xlsx-style

https://www.jianshu.com/p/877631e7e411

https://sheetjs.gitbooks.io/docs/#streaming-read

ps:以上第一个链接中的文档是错误的:

文字的水平对齐方式应该是:left center right 三个值才对

 

 安装依赖:npm install xlsx-style node-xlsx xlsx,安装的依赖版本:

  "dependencies": {
    "node-xlsx": "^0.15.0",
    "xlsx": "^0.14.4",
    "xlsx-style": "^0.8.13"
  }

 

把以上三个js文件拷贝到自定义目录,如node-xlsx-c

修改代码node-xlsx-c/index.js: xlsx修改为xlsx-style

编写生成xlsx的代码:

const fs = require("fs");

/**
 * 生成xlsx
 * @param p 生成文件路径
 * @param cols 列名
 * @param data 行,二维数组
 */
function genXlsx(p, cols, data) {
    let nodeXlsx = require('./node-xlsx-c');
    let d = [{
        name: "Sheet1",
        data: [
            cols,
            ...data
        ]
    }];
    // !cols 指定列的宽度
    fs.writeFileSync(p, nodeXlsx.build(d, {
        '!cols': [{wch: 60}, {wch: 20}]
    }), {'flag': 'w'});
}
// 指定单元格内容样式:四个方向的黑边框
let contentCellStyle = {
    border: {
        top: {
            style: "medium", color: "#000"
        },
        bottom: {
            style: "medium", color: "#000"
        },
        left: {
            style: "medium", color: "#000"
        },
        right: {
            style: "medium", color: "#000"
        },
    }
};
// 指定标题单元格样式:加粗居中
let headerStyle = {
    font: {
        bold: true
    },
    alignment: {
        horizontal: "center"
    }
}

genXlsx("1.xlsx", [{
    v: "表头1",
    s: headerStyle
}, {
    v: "表头2",
    s: headerStyle
}], [[{
    v: 123,
    s: contentCellStyle
}, {
    v: 456,
    s: contentCellStyle
}]])

代码运行,在当前目录生成1.xlsx:

 

推荐阅读