code icon Code

Parse Excel

Read Excel files (xlsx, xls, csv) into JSON

Source Code

import fs from "fs";
import path from "path";
import * as XLSX from "xlsx";

const [inputPath, sheetName = "0", outputPath] = process.argv.slice(2);

if (!inputPath || !outputPath) {
  console.error("Usage: inputPath [sheetName] outputPath");
  process.exit(1);
}

try {
  console.log(`Reading Excel file: ${inputPath}...`);

  const workbook = XLSX.readFile(inputPath);
  const sheetNames = workbook.SheetNames;

  console.log(`  Sheets: ${sheetNames.join(", ")}`);

  let result;

  if (sheetName === "all") {
    // Return all sheets as object
    result = {};
    for (const name of sheetNames) {
      const sheet = workbook.Sheets[name];
      result[name] = XLSX.utils.sheet_to_json(sheet);
      console.log(`  ${name}: ${result[name].length} rows`);
    }
  } else {
    // Return single sheet
    let targetSheet;
    let targetName;

    // Check if sheetName is a number (index)
    const sheetIndex = parseInt(sheetName, 10);
    if (!isNaN(sheetIndex) && sheetIndex >= 0 && sheetIndex < sheetNames.length) {
      targetName = sheetNames[sheetIndex];
      targetSheet = workbook.Sheets[targetName];
    } else if (sheetNames.includes(sheetName)) {
      targetName = sheetName;
      targetSheet = workbook.Sheets[sheetName];
    } else {
      console.error(`Sheet not found: ${sheetName}`);
      console.error(`Available sheets: ${sheetNames.join(", ")}`);
      process.exit(1);
    }

    result = XLSX.utils.sheet_to_json(targetSheet);
    console.log(`  Selected: ${targetName} (${result.length} rows)`);
  }

  // Ensure output directory exists
  const dir = path.dirname(outputPath);
  if (dir && dir !== ".") {
    fs.mkdirSync(dir, { recursive: true });
  }

  fs.writeFileSync(outputPath, JSON.stringify(result, null, 2));

  const totalRows = sheetName === "all" ? Object.values(result).reduce((sum, arr) => sum + arr.length, 0) : result.length;

  console.log(`\nāœ“ Parsed Excel file`);
  console.log(`  Total rows: ${totalRows}`);
  console.log(`  Written to: ${outputPath}`);

  console.log(
    JSON.stringify({
      success: true,
      inputPath,
      outputPath,
      sheetNames,
      selectedSheet: sheetName === "all" ? "all" : sheetName,
      totalRows,
    })
  );
} catch (error) {
  console.error("Error:", error.message);
  process.exit(1);
}