如何在使用js-xlxs解析xlxs时设置范围(行和列)

时间:2015-06-18 09:20:30

标签: javascript excel

我正在使用 js-xlxs 解析xlsx。

var url = "test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(e) {
  var arraybuffer = oReq.response;

  /* convert data to binary string */
  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
  var bstr = arr.join("");

  /* Call XLSX */
  var workbook = XLSX.read(bstr, {type:"binary"});

    var sheet_name_list = workbook.SheetNames;

        sheet_name_list.forEach(function(y) { /* iterate through sheets */
            var worksheet = workbook.Sheets[y];
            for (z in worksheet) {
                /* all keys that do not begin with "!" correspond to cell addresses */
                if(z[0] === '!') continue;
                console.log(y + "!" + z + "=" + JSON.stringify(worksheet[z].v));
            }
    });
}

oReq.send();

这对我来说很好。我可以遍历每个单元格,但需要在xlsx中解析特定范围,如行:A160-Q160和列:160-202

我在文档中读到了范围,但没有得到它,如何设置与我的示例相同

1 个答案:

答案 0 :(得分:0)

我是这样做的。它现在为我工作

function handleFile(e) {

if(!window.FileReader) {
  console.log("Browser doesn't support FileReader");
  return;
} 

var files = e.target.files, i, f,
rowRange = ["A"],//xls column array
/*setting range in xlsx, to parse and get with in range*/
lowerRangeRow = 160,//xls rows lower range
upperRangeRow = 202,//xls rows upper range
row1;

  for (i = 0, f = files[i]; i != files.length; ++i) {
    var reader = new FileReader();
    var name = f.name;
    reader.onload = function(e) {

    var data = e.target.result;
    var workbook = XLSX.read(data, {type: 'binary'});

    var sheet_name_list = workbook.SheetNames;

    sheet_name_list.forEach(function(y) { /* iterate through sheets */
    var worksheet = workbook.Sheets[y];

    for (z in worksheet){
        /* all keys that do not begin with "!" correspond to cell addresses */
        if(z[0] === '!') continue;

        row1 = z.replace(/[^0-9]/g, '');

        if(rowRange.indexOf(z.charAt(0)) > -1 && (row1>=lowerRangeRow && row1<=upperRangeRow)){
            //console.log(worksheet[z].v.trim());
            li = document.createElement("li");
            li.appendChild(document.createTextNode(worksheet[z].v.trim()));
            document.getElementById("xlsxDataList").appendChild(li);
        }           
    }

    });

    };

    reader.readAsBinaryString(f);
    }
}
document.getElementById("file").addEventListener('change', handleFile, false);