Batch XLS Conversion: A Safe CLI and Automation Workflow
Design a repeatable XLS batch process with canaries, logs, validation and rollback.
Batch XLS Conversion: A Safe CLI and Automation Workflow
Why Batch XLS Requires a Separate Protocol
The .xls format (BIFF8) is a compound binary file with hard limits of 65,536 rows and 256 columns per sheet, multiple embedded workbooks, and legacy VBA macro streams. Unlike .xlsx, it provides no XML transparency. Batch conversion introduces two failure modes rare in modern formats: silent truncation—data beyond row 65,536 or column 256 is dropped without warning—and macro corruption, where VBA code survives conversion but breaks at runtime. A repeatable pipeline for converting dozens or hundreds of .xls files to .xlsx or .csv must prevent data loss, log every failure, and provide a verifiable rollback path.
Canary Files: Pre-Flight Validation
A canary is a representative .xls file from the batch containing every structural feature present in the corpus: multiple sheets, merged cells, formulas, macros, and data near the 65,536-row limit. Convert this file first and inspect the output before touching the rest.
Selecting and Validating a Canary
Identify edge-case files with a quick scan:
for f in *.xls; do
rows=$(python3 -c "import xlrd; wb=xlrd.open_workbook('$f'); print(max(s.nrows for s in wb.sheets()))")
echo "$f: $rows rows"
done
Target files exceeding 60,000 rows, 200 columns, or containing known macros. After converting the canary with the intended tool, verify:
- Row and column counts match exactly.
- Merged cell ranges are preserved.
- Macros are retained (if the target format supports them) or flagged for removal.
- Formula results differ by no more than floating-point rounding tolerance.
If the canary fails—silent truncation, broken formulas, lost macros—halt the batch. Adjust conversion settings, such as switching to .xlsm for macro retention, or replace the source files.
The Conversion Pipeline: Three Stages
Stage 1: Pre-Conversion Audit and Backup
Create a compressed snapshot of the source directory and a checksum manifest:
tar -czf xls_backup_$(date +%Y%m%d).tar.gz ./*.xls
sha256sum ./*.xls > manifest.sha256
The manifest anchors rollback. After conversion, verify every input file has a corresponding output and no source files were modified.
Stage 2: Headless Conversion with Structured Logging
Use a tool that exposes failure details. The following Python pattern reads BIFF8 via xlrd and writes .xlsx via openpyxl, enforcing format limits explicitly:
import xlrd
import openpyxl
import sys, os, logging
logging.basicConfig(filename='conversion.log', level=logging.ERROR,
format='%(asctime)s %(message)s')
source_dir = sys.argv[1]
target_dir = sys.argv[2]
failures = []
for fname in os.listdir(source_dir):
if not fname.endswith('.xls'):
continue
src = os.path.join(source_dir, fname)
dst = os.path.join(target_dir, fname.replace('.xls', '.xlsx'))
try:
wb_old = xlrd.open_workbook(src)
wb_new = openpyxl.Workbook()
for sheet_name in wb_old.sheet_names():
sheet_old = wb_old.sheet_by_name(sheet_name)
sheet_new = wb_new.create_sheet(sheet_name)
for row in range(min(sheet_old.nrows, 65536)):
for col in range(min(sheet_old.ncols, 256)):
sheet_new.cell(row=row+1, column=col+1,
value=sheet_old.cell_value(row, col))
wb_new.save(dst)
except Exception as e:
logging.error(f"Failed to convert {src}: {e}")
failures.append(src)
if failures:
print(f"Conversion completed with {len(failures)} failures. See conversion.log")
sys.exit(1)
Key design decisions:
- Enforces the 65,536-row and 256-column limits defined in the BIFF8 specification (see MS-XLS).
- Logs every failure with a timestamp—no silent passes.
- Exits non-zero so CI/CD pipelines halt on failure.
Stage 3: Post-Conversion Validation and Rollback
Run a validation pass to confirm output completeness and source integrity:
for f in *.xls; do
base="${f%.xls}"
if [ ! -f "$base.xlsx" ]; then
echo "MISSING: $base.xlsx" >> validation_errors.log
fi
done
sha256sum -c manifest.sha256 --quiet 2>&1 | grep -v "OK$"
If validation fails, restore from backup:
tar -xzf xls_backup_*.tar.gz
rm -rf ./converted/
Failure Logging: What to Capture
Each log entry must answer which file failed, why, and at which stage. Use structured text for automated parsing:
{"timestamp": "2025-01-15T14:23:01Z", "file": "invoice_2024.xls", "stage": "read", "error": "Unsupported BIFF version: BIFF3", "action": "skipped"}
{"timestamp": "2025-01-15T14:23:04Z", "file": "payroll_macro.xls", "stage": "write", "error": "Macro not copied", "action": "logged"}
Distinguish these failure categories:
- Unsupported BIFF version: BIFF2–BIFF7 files are not modern
.xlsand may require legacy software. - Corrupt record: Data beyond the expected file length—unrecoverable.
- Row/column overflow: Data truncated; log the original dimensions.
- Macro loss: Not a conversion error, but a data-integrity warning.
Observable Validation Checks for batch xls conversion cli workflow
Structural Validation
- Compare
sheet_names()before and after conversion. - Spot-check cells at data boundaries: first row, last row, first column, last column.
- For merged cells, verify the merged range exists in the output via
openpyxl'smerged_cells.ranges.
Formula Validation
Formulas in .xls use R1C1 references. After conversion to .xlsx (A1 references), relative references may shift. Compare formula strings for a sample:
formula_old = sheet_old.cell_formula(row, col)
formula_new = sheet_new.cell(row, col).value
if formula_old != formula_new:
logging.warning(f"Formula mismatch in {fname}, sheet {sheet_name}, cell ({row},{col})")
Macro Integrity
VBA macros reside in a separate sub-stream within the .xls binary. If targeting .xlsm, verify the VBA project copies correctly. If targeting .xlsx, macros are always lost—log this as expected, not an error.
Hard Limits: When to Stop Converting
Some .xls files cannot be safely converted. Identify them before starting:
- BIFF2–BIFF5 files: These predate the Excel 97–2003
.xlsstandard, lack sheet metadata, and may not open in modern tools. The only safe fallback is a legacy Excel version (2000 or earlier) to re-save as BIFF8. - Encrypted streams:
.xlspassword protection uses RC4 encryption or XOR obfuscation. Without the password, the binary stream cannot be parsed. Log as "encrypted, skipped"—do not attempt brute force. - Files exceeding 2 GB: BIFF8 uses 32-bit offsets internally. Files larger than 2 GB are truncated when read by most libraries. Verify file size before conversion and log as "exceeds format limit."
Rollback Without a Full Backup
If disk space is constrained, maintain a changeset log instead of a full tarball:
stat --format="%s %Y %n" *.xls > pre_conversion_manifest.txt
while read size mtime name; do
current=$(stat --format="%s %Y" "$name")
if [ "$size $mtime" != "$current" ]; then
echo "Modified: $name" >> rollback_needed.txt
fi
done < pre_conversion_manifest.txt
This assumes source files reside on a read-only or snapshot-enabled filesystem. For production workflows, retain the backup tarball—it costs little and saves hours.