Sheetjs: Sheet to array helper function

Created on 28 Feb 2017  路  1Comment  路  Source: SheetJS/sheetjs

Here is my version of helper function to convert a workbook object to an array of arrays (by a row). In case, I'm not the only one, who needs it.

var sheet_to_row_array = function(workbook, opts) {
  var result = [], y = "", x, val=""; 
  var worksheetName = workbook.SheetNames[0];
  var worksheet = workbook.Sheets[worksheetName];
  var o = opts === null ? {} : opts;
  if(worksheet === null || worksheet["!ref"] === null)  return [];
  var r = safe_decode_range(worksheet['!ref']);
  var rr = "", cols = [], C;
  result = new Array(r.e.r - r.s.r + 1);
  for(C = r.s.c; C <= r.e.c; ++C) cols[C] = XLSX.utils.encode_col(C);
  var row = 0;
  var col = 0;
  var R = 0; 
  for(R = r.s.r; R <= r.e.r; ++R) {
    rr = XLSX.utils.encode_row(R);
    result[row] =  new Array(r.e.c - r.s.c + 1);
    for(C = r.s.c; C <= r.e.c; ++C) {
      y = cols[C] + rr;
      x = worksheet[y];
      val = "";
      if (x === undefined) val = null;
      else if(x.f !== null) val = x.w;
      else if (x.v === undefined ) val = null;
      else val = "" + x.v;
      result[row][col++] = val;       
    }
    row++;
    col = 0;
  } 
  return result;
};

To use separately, safe_decode_range function needs to be added from XLSX.

Most helpful comment

@nagistaja what does this do that the existing XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1}) doesn't do?

>All comments

@nagistaja what does this do that the existing XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1}) doesn't do?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gustavosimil picture gustavosimil  路  3Comments

m-ketan picture m-ketan  路  3Comments

eyalcohen4 picture eyalcohen4  路  3Comments

upasana-shah picture upasana-shah  路  4Comments

DannyRyman picture DannyRyman  路  3Comments