#include "xlsx.extendscript.js";

function main_parse() {
  /* Show File Picker */
  var thisFile = File.openDialog("Select a spreadsheet");
  if(!thisFile) { alert("File not found!"); return; }

  /* Read file from disk */
  var workbook = XLSX.readFile(thisFile.absoluteURI);
  var wsname = workbook.SheetNames[0];
  var data = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], { header: 1, raw: false });

  /* Set title */
  app.activeDocument.textFrames.itemByName("Title").texts.item(0).contents = wsname;

  /* Set table */
  var tabeller = app.activeDocument.textFrames.itemByName("Table Frame");
  var columns = data[0].length;
  for(var R = 0; R < data.length; ++R) columns = Math.max(columns, data[R].length);
  var table = tabeller.tables.add({
    headerRowCount: 1,
    bodyRowCount: data.length - 1,
    columnCount: columns
  });
  for(R = 0; R < data.length; ++R) {
    if(data[R] == null) continue;
    for(var C = 0; C < data[R].length; ++C) {
      if(data[R][C] == null) continue;
      table.rows.item(R).cells.item(C).contents = data[R][C];
    }
  }

}

main_parse();