Batch XLSX Conversion: A Safe CLI and Automation Workflow

November 08, 2026 · XLSX.now Editorial · XLSX Essentials

Design a repeatable XLSX batch process with canaries, logs, validation and rollback.

The Batch Conversion Problem

Converting a single XLSX is trivial. Converting thousands—each potentially corrupt, differently structured, or containing hidden data—requires a process that fails gracefully and logs precisely. An .xlsx file is a ZIP archive containing XML files per the OOXML standard. Any conversion tool must handle both ZIP-level corruption and malformed internal XML.

This guide covers converting XLSX to another format (CSV, JSON, a newer OOXML revision) or normalizing a batch into a uniform schema. It does not address one-off conversions.

The Three-Phase Pipeline

A safe batch conversion has three distinct phases. Never collapse them into a single script.

Phase 1: Pre-Flight Canary Checks

Before any conversion runs, validate every input file:

  • ZIP integrity check: unzip -t file.xlsx must return exit code 0. Files that fail are quarantined. Do not attempt repair.
  • Required file presence: Every XLSX must contain [Content_Types].xml, _rels/.rels, xl/workbook.xml, and at least one xl/worksheets/sheet*.xml. Missing any of these means the file is structurally invalid.
  • XML well-formedness: Run xmllint --noout on each internal XML file. A single malformed XML node—unescaped ampersands in shared strings, for example—will crash downstream parsers.

Only files passing all three checks proceed. Log the exact failure reason for each rejected file.

Phase 2: Conversion with Checkpoint Logging

Run the conversion tool per-file, never as a glob. Each file conversion must produce exactly one row in a conversion log:

2024-01-15 14:22:01 | invoice_2023.xlsx | SUCCESS | 0.34s | output/invoice_2023.csv
2024-01-15 14:22:03 | budget_2023.xlsx | FAILURE | 0.12s | Error: Missing cell data in row 47
2024-01-15 14:22:05 | report_alpha.xlsx | SKIPPED | 0.00s | Pre-flight: corrupt ZIP

The log format is CSV-compatible so you can audit it in a spreadsheet. Every failure must include an error message from the conversion tool, not a generic string.

Phase 3: Post-Conversion Validation

Converted files are not trusted until validated:

  • Row count match: The output must have the same number of data rows as the source XLSX. For CSV output, compare wc -l against the sheet's <row> count in xl/worksheets/sheet1.xml.
  • Checksum pair: Generate an MD5 hash of the source XLSX and store it alongside the output filename. This lets you re-run only files whose source hashes changed.
  • Schema enforcement: If the target format requires specific columns, validate that every output row has the correct number of delimiters or fields.

Tool Selection and Safety Boundaries

Python with openpyxl

openpyxl reads the internal XML directly and does not rely on LibreOffice or Excel. It detects corrupt shared strings tables and missing cell data before conversion begins.

from openpyxl import load_workbook
from openpyxl.utils.exceptions import InvalidFileException

def safe_convert(input_path, output_path):
    try:
        wb = load_workbook(input_path, read_only=True, data_only=True)
    except InvalidFileException as e:
        log_failure(input_path, "InvalidFileException", str(e))
        return False
    except zipfile.BadZipFile:
        log_failure(input_path, "BadZipFile", "Not a valid ZIP archive")
        return False

The read_only=True flag prevents loading the entire workbook into memory. This is essential for batches containing files with hundreds of thousands of rows.

LibreOffice CLI

soffice --headless --convert-to csv --outdir ./output/ ./input/*.xlsx

This works but lacks error granularity. A single corrupt file can cause the entire batch to fail. Always wrap it in a per-file loop with a timeout of 30 seconds per file. If a file hangs, terminate the process and log the filename.

What Not to Use

  • Pandas read_excel with default engine: Silently coerces errors and can produce outputs with shifted columns when cells contain line breaks.
  • Microsoft Excel macros (VBA): No batch log, no rollback, and no canary checks.

Rollback Strategy

Rollback does not mean undoing the conversion. You cannot un-convert a CSV back to XLSX. Rollback means restoring the state of the output directory to match the input directory before the batch ran.

Implementation

  1. Before any conversion, create a manifest file listing every input file with its SHA256 hash and last-modified timestamp.
  2. Write all output to a staging directory, not the final output directory.
  3. After all conversions complete, compare the conversion log against the manifest:
    • Any input file without a corresponding SUCCESS log entry means the conversion did not complete.
    • Any output file created where the source file had a pre-flight failure is deleted.
  4. Only then move the staging directory to the final output location.
# Staging workflow
for f in input/*.xlsx; do
    if canary_check "$f"; then
        convert "$f" staging/$(basename "$f" .xlsx).csv >> conversion.log 2>&1
    else
        echo "FAILED_CANARY: $f" >> conversion.log
    fi
done

# Post-run: delete outputs for failed canaries
grep "FAILED_CANARY" conversion.log | while read line; do
    filename=$(echo "$line" | awk '{print $2}')
    rm -f "staging/$(basename "$filename" .xlsx).csv"
done

Failure Logging That Enables Debugging

A conversion log must be machine-parseable and human-readable. Use a tab-separated format with exactly these columns:

Field Example Purpose
timestamp 2024-01-15T14:22:01Z Sort order
filename invoice_2023.xlsx Unique identifier
status SUCCESS / FAILURE / SKIPPED Quick triage
duration_ms 340 Performance tracking
error_detail Missing cell data in row 47 Root cause
output_path output/invoice_2023.csv Verification

Files with status SKIPPED must not appear in the output directory. Files with FAILURE must have their source XLSX preserved in a quarantine/ subdirectory.

Hard Limits of XLSX Batch Automation

No batch conversion process can handle:

  • Files with macros (.xlsm disguised as .xlsx): The internal structure is identical, but the VBA project binary is present. Conversion tools silently drop macros. This is a data loss event that validation cannot detect.
  • Files exceeding 1,048,576 rows: Excel's hard row limit. If your batch contains such files, they must be split before conversion. The only reliable detection method is counting <row> elements in the sheet XML before conversion.
  • External references to other workbooks: A cell containing =[budget.xlsx]Sheet1!A1 will fail during conversion if budget.xlsx is not in the batch. Log these as warnings, not errors, but flag them for manual review.

A 99% success rate with clear logs and zero silent data corruption is better than a 100% pass rate that shifts columns. The safest batch conversion refuses to convert files it cannot guarantee.