1

我正在尝试使用https://github.com/SheetJS/js-xlsx将一些数组数据导出到文件中。

我举了一个例子,在这里放了一个jsfiddle:https ://jsfiddle.net/connyake/y8a9nb7r/

没有requirejs甚至可以做到这一点吗?如果是,怎么做?

HTML:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.core.min.js"></script>
<button onclick="arrayToXlsx()">Export</button>

JS:

function arrayToXlsx() {
    /* original data */
    var data = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar","0.3"], ["baz", null, "qux"]];
    var ws_name = "SheetJS";

    /* set up workbook objects -- some of these will not be required in the future */
    var wb = {};
    wb.Sheets = {};
    wb.Props = {};
    wb.SSF = {};
    wb.SheetNames = [];

    /* create worksheet: */
    var ws = {};

    /* the range object is used to keep track of the range of the sheet */
    var range = {s: {c:0, r:0}, e: {c:0, r:0 }};

    /* Iterate through each element in the structure */
    for(var R = 0; R !== data.length; ++R) {
      if(range.e.r < R) range.e.r = R;
      for(var C = 0; C !== data[R].length; ++C) {
        if(range.e.c < C) range.e.c = C;

        /* create cell object: .v is the actual data */
        var cell = { v: data[R][C] };
        if(cell.v === null) continue;

        /* create the correct cell reference */
        var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

        /* determine the cell type */
        if(typeof cell.v === 'number') cell.t = 'n';
        else if(typeof cell.v === 'boolean') cell.t = 'b';
        else cell.t = 's';

        /* add to structure */
        ws[cell_ref] = cell;
      }
    }
    ws['!ref'] = XLSX.utils.encode_range(range);

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    /* write file */
    XLSX.writeFile(wb, 'test.xlsx');
};
4

1 回答 1

2

xlsx库有两个函数用于写入文件writewriteFile. 该等式writeFile实现了节点fs模块,因此旨在用于节点环境中。或者write是使用客户端 javascript 实现的,因此在您的情况下可能会更有用。IE: write(wb, {bookType: 'xlsx' , bookSST: false, type: 'binary'});

于 2017-04-03T10:08:13.247 回答