docs.sheetjs.com/docz/static/extendscript/write.idjs

48 lines
1.3 KiB
Plaintext
Raw Normal View History

2023-05-03 03:40:40 +00:00
const UXP = require("uxp");
const XLSX = require("./xlsx.full.min.js");
const storage = UXP.storage, ufs = storage.localFileSystem;
function workbook_add_table(wb, table) {
/* Collect Data */
var data = [];
var cnt = table.rows.count();
for(var R = 0; R < cnt; ++R) {
var row = table.rows.item(R);
data[R] = [];
var ccnt = row.cells.count();
for(var C = 0; C < ccnt; ++C) {
var value = row.cells.item(C).contents;
data[R][C] = value;
}
}
if(data.length == 0) return;
/* Create Worksheet */
var ws = XLSX.utils.aoa_to_sheet(data);
/* Create new Workbook and add worksheet */
XLSX.utils.book_append_sheet(wb, ws);
}
/* Create new Workbook */
var wb = XLSX.utils.book_new();
/* Find all tables and add them to workbook */
var tfcnt = app.activeDocument.textFrames.count();
for(var i = 0; i < tfcnt; ++i) {
var tf = app.activeDocument.textFrames.item(i);
var tcnt = tf.tables.count();
if(tcnt == 0) continue;
for(var j = 0; j < tcnt; ++j) workbook_add_table(wb, tf.tables.item(j));
}
/* generate XLSX with type: "buffer" */
const buf = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
/* show file picker */
const file = await ufs.getFileForSaving("SheetJSUXP.xlsx");
/* write data */
await file.write(buf, { data: storage.formats.binary });