docs.sheetjs.com/docz/docs/03-demos/13-cli.md

3.5 KiB

sidebar_position title
13 Command-Line Tools

import current from '/version.js'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

With the availability of JS engines and the success of server-side platforms, it is feasible to build command-line tools for various workflows.

This demo covers a number of strategies for building standalone processors. The goal is to generate CSV output from an arbitrary spreadsheet file.

Deno

deno compile generates a standalone executable that includes the entire JS runtime as well as user JS code.

When compiling, the --allow-read option must be specified to allow the script to read files from the filesystem with Deno.readFileSync.

Complete Example (click to show)
  1. Save the following script to sheet2csv.ts:
/*! sheetjs (C) 2013-present SheetJS -- http://sheetjs.com */
// @deno-types="https://cdn.sheetjs.com/xlsx-latest/package/types/index.d.ts"
import * as XLSX from 'https://cdn.sheetjs.com/xlsx-latest/package/xlsx.mjs';
import * as cptable from 'https://cdn.sheetjs.com/xlsx-latest/package/dist/cpexcel.full.mjs';
XLSX.set_cptable(cptable);

/* Read and parse workbook */
const filename = Deno.args[0];
if(!filename) {
  console.error("usage: sheet2csv <filename> [sheetname]");
  Deno.exit(1);
}
const workbook = XLSX.readFile(filename);

/* Find worksheet */
const sheetname = Deno.args[1] || workbook.SheetNames[0];
if(!workbook.Sheets[sheetname]) {
  console.error(`error: workbook missing sheet ${sheetname}`);
  Deno.exit(1);
}

/* Generate CSV and print to stdout */
console.log(XLSX.utils.sheet_to_csv(workbook.Sheets[sheetname]));
  1. Build sheet2csv with deno compile:
deno compile -r --allow-read sheet2csv.ts

sheet2csv is a generated executable that you can run.

NodeJS

There are a few popular tools for compiling NodeJS scripts to CLI programs.

The demo script presents a friendly command line interface including flags:

$ ./xlsx-cli -h
Usage: xlsx-cli [options] <file> [sheetname]

Options:
  -V, --version            output the version number
  -f, --file <file>        use specified workbook
  -s, --sheet <sheet>      print specified sheet (default first sheet)
...
  1. Download xlsx-cli.js

  2. Install the dependencies:

{`\
npm i --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz exit-on-epipe commander@2`}
{`\
pnpm install https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz exit-on-epipe commander@2`}
{`\
yarn add https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz exit-on-epipe commander@2`}
  1. Follow tooling steps:
  1. Run nexe and manually specify NodeJS version 14.15.3
npx nexe -t 14.15.3 xlsx-cli.js

This generates xlsx-cli or xlsx-cli.exe depending on platform.

  1. Run pkg:
npx pkg xlsx-cli.js

This generates xlsx-cli-linux, xlsx-cli-macos, and xlsx-cli-win.exe .