xlsx-manager
v2.1.0
Published
A powerful TypeScript library for Excel file manipulation with advanced table detection, formatting, and data extraction
Maintainers
Readme
XLSX Manager
A powerful TypeScript library for Excel file manipulation with advanced table detection, formatting, and data extraction capabilities.
Features
- Smart Table Detection - Automatically detect table boundaries and structure
- Multi-level Header Support - Handle complex headers with merged cells
- Schema-based Data Extraction - Transform Excel data to JSON with custom schemas
- Conditional Formatting - Preserve and reapply Excel conditional formatting rules
- Cell Operations - Get/set cells by value, index, or address
- Row/Column Operations - Read, clear, and manipulate rows and columns
- Meta Data Extraction - Extract related cell values (left/right neighbors)
- Merge Cell Handling - Detect and work with merged cells
- Workbook Fidelity - Load prefixed Open XML SDK files; preserve workbook protection and print-area anchors
- Data Validation - Read, set, extend, and clear validation ranges
Installation
npm install xlsx-managerUpgrading
2.1
Files with prefixed SpreadsheetML elements (including Open XML SDK exports)
now open. Saves keep workbook protection and the original print-area anchors
when their cells have not changed. New APIs load buffers, edit data validations,
and select worksheets. Existing removeProtection still removes sheet
protection only; use removeWorkbookProtection separately.
The exceljs round trip may deduplicate styles, change hidden-column widths,
add default page-setup attributes, rename XML parts, and drop SDK extras such
as x15ac:absPath. These differences do not change the tested cell formatting,
locks, validation rules, or print area.
From 1.x
2.0 fixes several bugs, and some fixes change results:
toJsonreturns typed values: numbers, booleans,Dates, formula results, andnullfor an empty cell. 1.x returned strings ("85","null","[object Object]"for formulas).- Generated keys:
'ID'becomesid(wasiD), and punctuation is dropped. - A grouped schema reads the group's first sub-column. To pick one, add it as
a third element:
grades: ['subject', 'grade', 'النقطة']. clearRow('x')clears the first match only;clearRows('x')clears all.getCellis typedCell | null; in strict TypeScript writegetCell('A1')!.value.
Also fixed: conditional formatting no longer doubles on every save, the ESM
build loads in plain Node, short headers like 'ID' are found as headers,
and reading never adds empty cells to the sheet.
Quick Start
import { XlsxTable } from 'xlsx-manager';
// Load an Excel file
const xlsx = new XlsxTable();
await xlsx.loadXlsx('data.xlsx');
// Detect table structure starting from a cell
const table = xlsx.detectTable('A1');
console.log(table.range); // { startRow, endRow, startCol, endCol }
// Convert to JSON with auto-detection
const data = xlsx.toJson('A1');
console.log(data);API Reference
XlsxTable
The main class for table operations.
Constructor
new XlsxTable(options?: DetectTableOptions)Options:
maxEmptyRows(default: 2) - Max consecutive empty rows before table endmaxEmptyCols(default: 1) - Max consecutive empty columns before table endmaxRows(default: 1000) - Maximum rows to scanmaxCols(default: 100) - Maximum columns to scaninitialRowScan(default: 20) - Initial rows to scan for quick boundary detection
Methods
loadXlsx(source, options?)
Load an Excel file from path or File object.
await xlsx.loadXlsx('path/to/file.xlsx');
// or
await xlsx.loadXlsx(fileObject);
// Remove sheet protection while loading
await xlsx.loadXlsx('locked.xlsx', { removeProtection: true });loadBuffer(source, options?)
Load an ArrayBuffer, Uint8Array, or Node Buffer. Views load only their
own bytes. Accepts the same LoadOptions as loadXlsx.
await xlsx.loadBuffer(await upload.arrayBuffer());
await xlsx.loadBuffer(buffer, { removeWorkbookProtection: true });useSheet(nameOrIndex)
Select a sheet by name or zero-based position in workbook order, including hidden sheets. Loading selects the first sheet. Invalid selections throw.
xlsx.useSheet('Data');
xlsx.useSheet(0);getValidations() / setValidation(range, rule) / clearValidation(range?)
Validation methods operate on the selected sheet. getValidations() returns
Array<{ range: string; rule: ValidationRule }> with matching cells grouped
into rectangles. setValidation returns the number of cells whose rule
changed; clearValidation returns how many cells had a rule removed.
import type { ValidationRule } from 'xlsx-manager';
const rule: ValidationRule = {
type: 'decimal', operator: 'between', formulae: [0, 10],
allowBlank: true, showErrorMessage: true
};
xlsx.setValidation('G18:G45', rule);
const validations = xlsx.getValidations();
xlsx.clearValidation('H18:H45');
xlsx.clearValidation(); // all on the selected sheetRanges use A1 notation (A1 or A1:B10). New cells keep empty values;
adjacent identical rules are compacted on save. Cross-sheet list formulas
such as Data!$A$1:$A$2 stay as text.
hasWorkbookProtection() / removeWorkbookProtection()
hasWorkbookProtection() reports the loaded workbook protection.
removeWorkbookProtection() removes it from subsequent saves. Sheet
protection is independent.
if (xlsx.hasWorkbookProtection()) xlsx.removeWorkbookProtection();
// Or remove it while loading:
await xlsx.loadXlsx('locked.xlsx', { removeWorkbookProtection: true });detectTable(startCell)
Detect table structure from a starting cell.
const table = xlsx.detectTable('A1');
// Returns: { range, headerRows, dataStartRow, columns }toJson(startCell, schema?)
Convert table data to JSON array.
// Auto-detect structure
const data = xlsx.toJson('A1');
// With custom schema
const schema = {
studentId: "Student ID",
name: "Name",
grades: ["Subject", "Grade"] // Nested array
};
const data = xlsx.toJson('A1', schema);Schema Format:
- Simple mapping:
{ outputKey: "Header Name" } - Nested arrays:
{ outputKey: ["GroupHeader", "ItemHeader"] } - Pick a sub-header when a group has several:
{ outputKey: ["GroupHeader", "ItemHeader", "Grade"] }
Values keep their type: numbers, booleans, Dates, formula results, trimmed
text, and null for an empty cell.
Xlsx (XlsxManager)
Lower-level Excel operations.
Cell Operations
// Get cell by address (always the address, so new cells can be written)
const cell = xlsx.getCell('A1');
// Get cell by value (null when not found)
const cell = xlsx.getCell('Student Name');
// A header that looks like an address
const cell = xlsx.getCell('S1', { by: 'value' });
// Get cell with merge info
const cell = xlsx.getCell('A1', { includeMergeInfo: true });Row Operations
// Get row by index
const row = xlsx.getRow(1);
// Get row by value
const row = xlsx.getRow('Student Name');
// Get row values only
const values = xlsx.getRowValues(1);
// Clear row
xlsx.clearRow(1);
xlsx.clearRow('Total'); // the first row labelled 'Total'
xlsx.clearRows('Total'); // every row labelled 'Total'A letter or address inside the used range is a position; outside it, a cell
with that text wins, so getCol('ID') finds the 'ID' header rather than
column 238. Force either reading with { by: 'value' } or { by: 'address' }.
See docs/usage.md for every option.
Column Operations
// Get column by letter
const col = xlsx.getCol('A');
// Get column by index
const col = xlsx.getCol(1);
// Get column values
const values = xlsx.getColValues('A');
// Clear column
xlsx.clearCol('A');Meta Data Extraction
Extract values from neighboring cells:
// Get value to the right
const value = xlsx.meta('Label:'); // Returns value next to "Label:"
// Get value to the left
const value = xlsx.metaR('Value');
// With custom distance
const value = xlsx.meta('Label:', { maxDistance: 10 });Range Operations
// Get range of cells
const range = xlsx.getRange('A1:C10');
range.eachCell((cell) => {
console.log(cell.value);
});XlsxCore
Core worksheet operations.
// Check if row/column is empty
const isEmpty = xlsx.isRowEmpty(1);
const isEmpty = xlsx.isColEmpty('A');
// Check within range
const isEmpty = xlsx.isRowEmptyInRange(1, 1, 5);XlsxFormatting
Handle Excel formatting and styles.
// Save with formatting preserved
await xlsx.saveXlsx('output.xlsx');
// Get buffer
const buffer = await xlsx.writeBuffer();Utility Functions
import {
isCellAddress,
isColumnLetter,
extractRowNumber,
extractColNumber,
parseRange,
toCamelCase,
nStr
} from 'xlsx-manager';
// Check if string is a cell address
isCellAddress('A1'); // true
// Extract components
extractRowNumber('A10'); // 10
extractColNumber('AB5'); // 28
// Parse range
parseRange('A1:C10', rowCount, colCount);
// Utilities
toCamelCase('Student Name'); // "studentName"
nStr(' text '); // "text" (normalized)Advanced Examples
Complex Table with Nested Headers
const xlsx = new XlsxTable();
await xlsx.loadXlsx('grades.xlsx');
const schema = {
studentId: "Student ID",
name: "Name",
birthDate: "Birth Date",
grades: ["Subject", "Score"] // Will create array of {Subject, Score}
};
const students = xlsx.toJson('A1', schema);
// Output:
// [
// {
// studentId: "001",
// name: "John Doe",
// birthDate: "2000-01-01",
// grades: [
// { Subject: "Math", Score: 95 },
// { Subject: "English", Score: 88 }
// ]
// }
// ]Custom Table Detection
const xlsx = new XlsxTable({
maxEmptyRows: 3,
maxEmptyCols: 2,
maxRows: 5000,
initialRowScan: 50
});
await xlsx.loadXlsx('large-file.xlsx');
const table = xlsx.detectTable('B5'); // Start from specific cellWorking with Merged Cells
const cell = xlsx.getCell('A1', { includeMergeInfo: true });
if (cell?.isMerged) {
console.log(`Spans ${cell.rowSpan} rows and ${cell.colSpan} columns`);
console.log(`Is top-left: ${cell.isTopLeft}`);
}Preserving Conditional Formatting
// Load file
await xlsx.loadXlsx('formatted.xlsx');
// Modify data
xlsx.getCell('A1')!.value = 'New Value';
// Save with formatting preserved
await xlsx.saveXlsx('output.xlsx');TypeScript Support
Full TypeScript support with comprehensive type definitions:
import type {
TableRange,
DetectTableOptions,
ColumnInfo,
HeaderStructure,
CellInfo,
MergeInfo
} from 'xlsx-manager';Development
bun install
bun run typecheck
bun test
bun run build
bun run test:packageTo test private Massar exports locally (PowerShell):
$env:XLSX_MASSAR_SAMPLES = 'C:/path/to/exports'
bun test tests/localThe runner writes saved workbooks to the ignored tests/local/out/ folder
and logs only filenames, cell counts, and timings. It snapshots a separate
copy, treats explicit default fonts as equivalent to implicit defaults, and
compares each conditional-formatting rule's style directly in the original
and saved XML. Keep real exports outside the repository, and delete the
generated copies after inspection. Excel and Massar import checks are
separate manual checks.
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
