xlsx.njs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #!/usr/bin/env node
  2. /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  3. /* eslint-env node */
  4. /* vim: set ts=2 ft=javascript: */
  5. var n = "xlsx";
  6. var X = require('../');
  7. try { X = require('../xlsx.flow'); } catch(e) {}
  8. require('exit-on-epipe');
  9. var fs = require('fs'), program;
  10. try { program = require('commander'); } catch(e) {
  11. [
  12. "The `xlsx` command line tool is deprecated in favor of `xlsx-cli`.",
  13. "",
  14. "For new versions of node, we recommend using `npx`:",
  15. " $ npx xlsx-cli --help",
  16. "",
  17. "For older versions of node, explicitly install `xlsx-cli` globally:",
  18. " $ npm i -g xlsx-cli",
  19. " $ xlsx-cli --help"
  20. ].forEach(function(m) { console.error(m); });
  21. process.exit(1);
  22. }
  23. program
  24. .version(X.version)
  25. .usage('[options] <file> [sheetname]')
  26. .option('-f, --file <file>', 'use specified workbook')
  27. .option('-s, --sheet <sheet>', 'print specified sheet (default first sheet)')
  28. .option('-N, --sheet-index <idx>', 'use specified sheet index (0-based)')
  29. .option('-p, --password <pw>', 'if file is encrypted, try with specified pw')
  30. .option('-l, --list-sheets', 'list sheet names and exit')
  31. .option('-o, --output <file>', 'output to specified file')
  32. .option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb')
  33. .option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm')
  34. .option('-X, --xlsx', 'emit XLSX to <sheetname> or <file>.xlsx')
  35. .option('-I, --xlam', 'emit XLAM to <sheetname> or <file>.xlam')
  36. .option('-Y, --ods', 'emit ODS to <sheetname> or <file>.ods')
  37. .option('-8, --xls', 'emit XLS to <sheetname> or <file>.xls (BIFF8)')
  38. .option('-5, --biff5','emit XLS to <sheetname> or <file>.xls (BIFF5)')
  39. .option('-4, --biff4','emit XLS to <sheetname> or <file>.xls (BIFF4)')
  40. .option('-3, --biff3','emit XLS to <sheetname> or <file>.xls (BIFF3)')
  41. .option('-2, --biff2','emit XLS to <sheetname> or <file>.xls (BIFF2)')
  42. .option('-i, --xla', 'emit XLA to <sheetname> or <file>.xla')
  43. .option('-6, --xlml', 'emit SSML to <sheetname> or <file>.xls (2003 XML)')
  44. .option('-T, --fods', 'emit FODS to <sheetname> or <file>.fods (Flat ODS)')
  45. .option('--wk3', 'emit WK3 to <sheetname> or <file>.txt (Lotus WK3)')
  46. .option('-S, --formulae', 'emit list of values and formulae')
  47. .option('-j, --json', 'emit formatted JSON (all fields text)')
  48. .option('-J, --raw-js', 'emit raw JS object (raw numbers)')
  49. .option('-A, --arrays', 'emit rows as JS objects (raw numbers)')
  50. .option('-H, --html', 'emit HTML to <sheetname> or <file>.html')
  51. .option('-D, --dif', 'emit DIF to <sheetname> or <file>.dif (Lotus DIF)')
  52. .option('-U, --dbf', 'emit DBF to <sheetname> or <file>.dbf (MSVFP DBF)')
  53. .option('-K, --sylk', 'emit SYLK to <sheetname> or <file>.slk (Excel SYLK)')
  54. .option('-P, --prn', 'emit PRN to <sheetname> or <file>.prn (Lotus PRN)')
  55. .option('-E, --eth', 'emit ETH to <sheetname> or <file>.eth (Ethercalc)')
  56. .option('-t, --txt', 'emit TXT to <sheetname> or <file>.txt (UTF-8 TSV)')
  57. .option('-r, --rtf', 'emit RTF to <sheetname> or <file>.txt (Table RTF)')
  58. .option('--wk1', 'emit WK1 to <sheetname> or <file>.txt (Lotus WK1)')
  59. .option('-z, --dump', 'dump internal representation as JSON')
  60. .option('--props', 'dump workbook properties as CSV')
  61. .option('-F, --field-sep <sep>', 'CSV field separator', ",")
  62. .option('-R, --row-sep <sep>', 'CSV row separator', "\n")
  63. .option('-n, --sheet-rows <num>', 'Number of rows to process (0=all rows)')
  64. .option('--codepage <cp>', 'default to specified codepage when ambiguous')
  65. .option('--req <module>', 'require module before processing')
  66. .option('--sst', 'generate shared string table for XLS* formats')
  67. .option('--compress', 'use compression when writing XLSX/M/B and ODS')
  68. .option('--read', 'read but do not generate output')
  69. .option('--book', 'for single-sheet formats, emit a file per worksheet')
  70. .option('--all', 'parse everything; write as much as possible')
  71. .option('--dev', 'development mode')
  72. .option('--sparse', 'sparse mode')
  73. .option('-q, --quiet', 'quiet mode');
  74. program.on('--help', function() {
  75. console.log(' Default output format is CSV');
  76. console.log(' Support email: dev@sheetjs.com');
  77. console.log(' Web Demo: http://oss.sheetjs.com/js-'+n+'/');
  78. });
  79. /* flag, bookType, default ext */
  80. var workbook_formats = [
  81. ['xlsx', 'xlsx', 'xlsx'],
  82. ['xlsm', 'xlsm', 'xlsm'],
  83. ['xlam', 'xlam', 'xlam'],
  84. ['xlsb', 'xlsb', 'xlsb'],
  85. ['xls', 'xls', 'xls'],
  86. ['xla', 'xla', 'xla'],
  87. ['biff5', 'biff5', 'xls'],
  88. ['ods', 'ods', 'ods'],
  89. ['fods', 'fods', 'fods'],
  90. ['wk3', 'wk3', 'wk3']
  91. ];
  92. var wb_formats_2 = [
  93. ['xlml', 'xlml', 'xls']
  94. ];
  95. program.parse(process.argv);
  96. var filename = '', sheetname = '';
  97. if(program.args[0]) {
  98. filename = program.args[0];
  99. if(program.args[1]) sheetname = program.args[1];
  100. }
  101. if(program.sheet) sheetname = program.sheet;
  102. if(program.file) filename = program.file;
  103. if(!filename) {
  104. console.error(n + ": must specify a filename");
  105. process.exit(1);
  106. }
  107. if(!fs.existsSync(filename)) {
  108. console.error(n + ": " + filename + ": No such file or directory");
  109. process.exit(2);
  110. }
  111. if(program.req) program.req.split(",").forEach(function(r) {
  112. require((fs.existsSync(r) || fs.existsSync(r + '.js')) ? require('path').resolve(r) : r);
  113. });
  114. var opts = {}, wb/*:?Workbook*/;
  115. if(program.listSheets) opts.bookSheets = true;
  116. if(program.sheetRows) opts.sheetRows = program.sheetRows;
  117. if(program.password) opts.password = program.password;
  118. var seen = false;
  119. function wb_fmt() {
  120. seen = true;
  121. opts.cellFormula = true;
  122. opts.cellNF = true;
  123. if(program.output) sheetname = program.output;
  124. }
  125. function isfmt(m/*:string*/)/*:boolean*/ {
  126. if(!program.output) return false;
  127. var t = m.charAt(0) === "." ? m : "." + m;
  128. return program.output.slice(-t.length) === t;
  129. }
  130. workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
  131. wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } });
  132. if(seen) {
  133. } else if(program.formulae) opts.cellFormula = true;
  134. else opts.cellFormula = false;
  135. var wopts = ({WTF:opts.WTF, bookSST:program.sst}/*:any*/);
  136. if(program.compress) wopts.compression = true;
  137. if(program.all) {
  138. opts.cellFormula = true;
  139. opts.bookVBA = true;
  140. opts.cellNF = true;
  141. opts.cellHTML = true;
  142. opts.cellStyles = true;
  143. opts.sheetStubs = true;
  144. opts.cellDates = true;
  145. wopts.cellStyles = true;
  146. wopts.sheetStubs = true;
  147. wopts.bookVBA = true;
  148. }
  149. if(program.sparse) opts.dense = false; else opts.dense = true;
  150. if(program.codepage) opts.codepage = +program.codepage;
  151. if(program.dev) {
  152. opts.WTF = true;
  153. wb = X.readFile(filename, opts);
  154. } else try {
  155. wb = X.readFile(filename, opts);
  156. } catch(e) {
  157. var msg = (program.quiet) ? "" : n + ": error parsing ";
  158. msg += filename + ": " + e;
  159. console.error(msg);
  160. process.exit(3);
  161. }
  162. if(program.read) process.exit(0);
  163. if(!wb) { console.error(n + ": error parsing " + filename + ": empty workbook"); process.exit(0); }
  164. /*:: if(!wb) throw new Error("unreachable"); */
  165. if(program.listSheets) {
  166. console.log((wb.SheetNames||[]).join("\n"));
  167. process.exit(0);
  168. }
  169. if(program.dump) {
  170. console.log(JSON.stringify(wb));
  171. process.exit(0);
  172. }
  173. if(program.props) {
  174. if(wb) dump_props(wb);
  175. process.exit(0);
  176. }
  177. /* full workbook formats */
  178. workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
  179. wopts.bookType = m[1];
  180. if(wb) X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
  181. process.exit(0);
  182. } });
  183. wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) {
  184. wopts.bookType = m[1];
  185. if(wb) X.writeFile(wb, program.output || sheetname || ((filename || "") + "." + m[2]), wopts);
  186. process.exit(0);
  187. } });
  188. var target_sheet = sheetname || '';
  189. if(target_sheet === '') {
  190. if(+program.sheetIndex < (wb.SheetNames||[]).length) target_sheet = wb.SheetNames[+program.sheetIndex];
  191. else target_sheet = (wb.SheetNames||[""])[0];
  192. }
  193. var ws;
  194. try {
  195. ws = wb.Sheets[target_sheet];
  196. if(!ws) {
  197. console.error("Sheet " + target_sheet + " cannot be found");
  198. process.exit(3);
  199. }
  200. } catch(e) {
  201. console.error(n + ": error parsing "+filename+" "+target_sheet+": " + e);
  202. process.exit(4);
  203. }
  204. if(!program.quiet && !program.book) console.error(target_sheet);
  205. /* single worksheet file formats */
  206. [
  207. ['biff2', '.xls'],
  208. ['biff3', '.xls'],
  209. ['biff4', '.xls'],
  210. ['sylk', '.slk'],
  211. ['html', '.html'],
  212. ['prn', '.prn'],
  213. ['eth', '.eth'],
  214. ['rtf', '.rtf'],
  215. ['txt', '.txt'],
  216. ['dbf', '.dbf'],
  217. ['wk1', '.wk1'],
  218. ['dif', '.dif']
  219. ].forEach(function(m) { if(program[m[0]] || isfmt(m[1])) {
  220. wopts.bookType = m[0];
  221. if(program.book) {
  222. /*:: if(wb == null) throw new Error("Unreachable"); */
  223. wb.SheetNames.forEach(function(n, i) {
  224. wopts.sheet = n;
  225. X.writeFile(wb, (program.output || sheetname || filename || "") + m[1] + "." + i, wopts);
  226. });
  227. } else X.writeFile(wb, program.output || sheetname || ((filename || "") + m[1]), wopts);
  228. process.exit(0);
  229. } });
  230. function outit(o, fn) { if(fn) fs.writeFileSync(fn, o); else console.log(o); }
  231. function doit(cb) {
  232. /*:: if(!wb) throw new Error("unreachable"); */
  233. if(program.book) wb.SheetNames.forEach(function(n, i) {
  234. /*:: if(!wb) throw new Error("unreachable"); */
  235. outit(cb(wb.Sheets[n]), (program.output || sheetname || filename) + "." + i);
  236. });
  237. else outit(cb(ws), program.output);
  238. }
  239. var jso = {};
  240. switch(true) {
  241. case program.formulae:
  242. doit(function(ws) { return X.utils.sheet_to_formulae(ws).join("\n"); });
  243. break;
  244. case program.arrays: jso.header = 1;
  245. /* falls through */
  246. case program.rawJs: jso.raw = true;
  247. /* falls through */
  248. case program.json:
  249. doit(function(ws) { return JSON.stringify(X.utils.sheet_to_json(ws,jso)); });
  250. break;
  251. default:
  252. if(!program.book) {
  253. var stream = X.stream.to_csv(ws, {FS:program.fieldSep||",", RS:program.rowSep||"\n"});
  254. if(program.output) stream.pipe(fs.createWriteStream(program.output));
  255. else stream.pipe(process.stdout);
  256. } else doit(function(ws) { return X.utils.sheet_to_csv(ws,{FS:program.fieldSep, RS:program.rowSep}); });
  257. break;
  258. }
  259. function dump_props(wb/*:Workbook*/) {
  260. var propaoa = [];
  261. if(Object.assign && Object.entries) propaoa = Object.entries(Object.assign({}, wb.Props, wb.Custprops));
  262. else {
  263. var Keys/*:: :Array<string> = []*/, pi;
  264. if(wb.Props) {
  265. Keys = Object.keys(wb.Props);
  266. for(pi = 0; pi < Keys.length; ++pi) {
  267. if(Object.prototype.hasOwnProperty.call(Keys, Keys[pi])) propaoa.push([Keys[pi], Keys[/*::+*/Keys[pi]]]);
  268. }
  269. }
  270. if(wb.Custprops) {
  271. Keys = Object.keys(wb.Custprops);
  272. for(pi = 0; pi < Keys.length; ++pi) {
  273. if(Object.prototype.hasOwnProperty.call(Keys, Keys[pi])) propaoa.push([Keys[pi], Keys[/*::+*/Keys[pi]]]);
  274. }
  275. }
  276. }
  277. console.log(X.utils.sheet_to_csv(X.utils.aoa_to_sheet(propaoa)));
  278. }