zoukankan      html  css  js  c++  java
  • nodeJS生成xlsx以及设置样式

    参考:

    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:

  • 相关阅读:
    JSTL XML标签库 使用
    JSTL SQL标签库 使用
    JSTL I18N 格式标签库
    基于struts2的ajaxfileupload异步上传插件的使用
    Spring 使用注解方式进行事务管理
    vi编辑器的使用方式
    js基础知识介绍
    选择语句
    数组
    0411作业
  • 原文地址:https://www.cnblogs.com/hellohello/p/11240326.html
Copyright © 2011-2022 走看看