Reads, builds, and styles spreadsheet workbooks in JavaScript.
Downloads / mo 105.0M
Stars 15.5K
Last release 4.4.0
License MIT Strengths Streams workbook rows . Write rows progressively and release committed row objects. Styles cells, rows, and columns . Apply number formats and visual styles at different worksheet levels. Limitations Formula results need external calculation . Supply calculated results when writing formula cells. Streaming mode excludes images . Use document workbooks when the exported spreadsheet needs images. $ npm install exceljs Copy
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
workbook.addWorksheet('Sheet1');
await workbook.xlsx.writeFile('output.xlsx');
exceljs examples From open-source projects on GitHub async editRange(path: string, range: string, content: any, options?: Record<string, any>): Promise<EditResult> {
// Verify file exists and check size
try {
await this.checkFileSize(path);
} catch (error) {
if ((error as any).code === 'ENOENT' ||
(error instanceof Error && error.message.includes('ENOENT'))) {
throw new Error(`File not found: ${path}`);
}
throw error;
}
// Validate content
if (!Array.isArray(content)) {
throw new Error('Content must be a 2D array for range editing');
}
// Parse range: "Sheet1!A1:C10" or "Sheet1"
const [sheetName, cellRange] = this.parseRange(range);
const workbook = await newWorkbook();
await workbook.xlsx.readFile(path);
// Get or create sheet
let worksheet = workbook.getWorksheet(sheetName);
if (!worksheet) {
worksheet = workbook.addWorksheet(sheetName);
}
if (cellRange) {
// Write to specific range
const { startRow, startCol, endRow, endCol } = this.parseCellRange(cellRange);
// A FROM:TO range bounds the write: content that doesn't fit is refused
// before any cell changes, so no cell outside the range is overwritten
if (endRow !== undefined && endCol !== undefined) {
const rows = content.length;
const columns = Math.max(0, ...content.map((row: unknown) => Array.isArray(row) ? row.length : 0));
const rangeRows = endRow - startRow + 1;
const rangeColumns = endCol - startCol + 1;
if (rows > rangeRows || columns > rangeColumns) {
throw new Error(
`Content has ${rows} row(s) and ${columns} column(s) but range ${cellRange} holds ` +
`${rangeRows} row(s) and ${rangeColumns} column(s); nothing was written`
);
}
}
for (let r = 0; r < content.length; r++) {
const rowData = content[r];
if (!Array.isArray(rowData)) continue;
for (let c = 0; c < rowData.length; c++) {
const cell = worksheet.getCell(startRow + r, startCol + c);
const value = rowData[c];
if (typeof value === 'string' && value.startsWith('=')) {
cell.value = { formula: value.substring(1) };
} else {
cell.value = value;
}
}
}
} else {
// Replace entire sheet content
// Clear existing data
worksheet.eachRow((row, rowNumber) => {
row.eachCell((cell) => {
cell.value = null;
});
});
// Write new data
for (let r = 0; r < content.length; r++) {
const rowData = content[r];
if (!Array.isArray(rowData)) continue;
const row = worksheet.getRow(r + 1);
for (let c = 0; c < rowData.length; c++) {
const value = rowData[c];
if (typeof value === 'string' && value.startsWith('=')) {
row.getCell(c + 1).value = { formula: value.substring(1) };
} else {
row.getCell(c + 1).value = value;
}
}
row.commit();
}
}
await workbook.xlsx.writeFile(path);
return { success: true, editsApplied: 1 };
}
Show full example Extracts spreadsheet data and generates new spreadsheet files.
Downloads / mo 60.5M
Stars 36.3K
Last release 0.20.3
License Apache-2.0 Strengths Reads varied spreadsheet formats . Extract data from older XLS files and current XLSX workbooks. Builds workbooks from row objects . Convert JavaScript records into worksheets and export an XLSX file. Limitations Npm releases trail official downloads . Install the current release from the official download URL. File decryption covers XOR only . Use another tool for AES-encrypted XLSX files. Formula results need external calculation . Writing formulas does not calculate their results in JavaScript. $ npm install https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz Copy
const XLSX = require('xlsx');
const workbook = XLSX.utils.book_new();
const sheet = XLSX.utils.aoa_to_sheet([['Name'], ['Ada']]);
XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');
XLSX.writeFile(workbook, 'output.xlsx');
xlsx examples From open-source projects on GitHub _final(callback) {
const workbook = createWorkbook(this.fileName);
const existingLower = new Set(workbook.SheetNames.map((n) => n.toLowerCase()));
const base = (this.sheetName || 'Sheet 1').substring(0, MAX_SHEET_NAME_LENGTH);
let sheetName = base;
if (existingLower.has(sheetName.toLowerCase())) {
let counter = 1;
do {
const suffix = `_${counter}`;
sheetName = base.substring(0, MAX_SHEET_NAME_LENGTH - suffix.length) + suffix;
counter++;
} while (existingLower.has(sheetName.toLowerCase()));
}
xlsx.utils.book_append_sheet(workbook, xlsx.utils.aoa_to_sheet(this.rows), sheetName);
callback();
}
Show full example Reads XLSX files as rows or schema-mapped records in browsers and Node.js.
Downloads / mo 19.6M
Stars 331
Last release 9.3.17
License MIT Strengths Maps rows through schemas . Map spreadsheet columns to named object properties and validate values. Runs in browsers and Node . Read uploaded spreadsheets or files from a Node.js application. Limitations Legacy XLS files are unsupported . Convert older workbooks to XLSX before reading them. Formula values must be cached . Formula cells without stored results are read as empty cells. $ npm install read-excel-file Copy
import { readSheet } from 'read-excel-file/node';
const rows = await readSheet('./input.xlsx');
read-excel-file examples From open-source projects on GitHub export async function readXlsxWorkbook(file: Blob | ArrayBuffer): Promise<XlsxSheet[]> {
// Loaded here, not at the top of the module: the dialog is on a route the
// SPA needs anyway, and this library is only needed once a workbook is
// chosen. Vite puts it in a chunk of its own.
const { default: readXlsxFile } = await import('read-excel-file/browser')
const sheets = await readXlsxFile<NumericText>(file, {
// The pass-through that keeps the cell's own text: the library would
// otherwise parse the value into a Number, and `Number` then decides how
// many digits a phone number has.
parseNumber: (text) => ({ numericText: text }),
})
// A workbook with no worksheet is not one to map columns against, and the
// caller has nothing to show for it — better refused than opened empty.
if (sheets.length === 0) throw new Error('the workbook has no sheets')
return sheets.map((sheet) => ({ name: sheet.sheet, table: tableOf(sheet.data as SheetRow[]) }))
}
Show full example Creates an XLSX file from rows of cell values in a browser or Node.js.
Downloads / mo 10.0M
Stars 36
Last release 4.1.1
License MIT Strengths Takes plain arrays of rows . Each cell holds a string, number, boolean, date, or null. Limitations Needs a recent Node.js . The current release drops support for older Node.js versions. $ npm install write-excel-file Copy
import writeExcelFile from 'write-excel-file/node';
const sheetData = [['Name'], ['Ada']];
await writeExcelFile(sheetData).toFile('./output.xlsx');
write-excel-file examples From open-source projects on GitHub const exportExcel = async<TRow extends Record<string, unknown>>({
header,
fields,
rows,
filename,
// Resolved per call, like the rest: this is a destructuring default, so it
// runs when exportExcel does rather than when the module loaded.
confirmText = i18n.global.t('composables.export.confirm')
}: ExportOptions<TRow>): Promise<boolean> => {
if (pending) return false
if (!rows.length) return false
pending = true
try {
if (confirmText !== null) {
try {
await ElMessageBox.confirm(confirmText, i18n.global.t('common.notice'), {
type: 'warning',
confirmButtonText: i18n.global.t('common.confirm'),
cancelButtonText: i18n.global.t('common.cancel')
})
} catch {
// Dismissing the confirm is a decision, not a failure
return false
}
}
exporting.value = true
const { data, columns } = buildSheet(header, rows.map(row => fields.map(field => row[field])))
// The browser entry, not the package root: the root offers none, and the
// node one reaches for fs.
const { default: writeXlsxFile } = await import('write-excel-file/browser')
await writeXlsxFile(data, {
sheet: 'Sheet1',
columns,
dateFormat: DATE_FORMAT
}).toFile(`${filename}.xlsx`)
return true
} finally {
pending = false
exporting.value = false
}
}
Show full example Adds basic cell styling to SheetJS for creating Excel spreadsheets.
Downloads / mo 4.6M
Stars 513
Last release 1.2.0
License Apache-2.0 Strengths Styles fonts, fills, and borders . A style object on each cell sets alignment, border, fill, font, and number format. Limitations Built on an older SheetJS . The bundled SheetJS core trails the current SheetJS release. $ npm install xlsx-js-style Copy
const XLSX = require('xlsx-js-style');
const workbook = XLSX.utils.book_new();
const sheet = XLSX.utils.aoa_to_sheet([[{ v: 'Name', t: 's', s: { font: { bold: true } } }]]);
XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');
XLSX.writeFile(workbook, 'output.xlsx');
xlsx-js-style examples From open-source projects on GitHub export const exportFile = async (tableData: TableData, type: 'csv' | 'xlsx') => {
if (!tableData?.rows || tableData.rows.length === 0) {
return;
}
const { saveAs } = await import('file-saver');
if (type === 'xlsx') {
const XLSX = await import('xlsx-js-style');
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet([tableData.columnNames, ...tableData.rows]);
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const excelBuffer = XLSX.write(wb, {
bookType: 'xlsx',
type: 'array'
});
const blob = new Blob([excelBuffer], { type: EXCEL_TYPE });
saveAs(blob, `export${EXCEL_EXTENSION}`);
} else {
const separator = ',';
const header = tableData.columnNames.join(separator);
const rows = tableData.rows.map(row => row.join(separator));
const content = [header, ...rows].join('\n');
// Excel reads a CSV without a BOM in the system code page, garbling non-ASCII data. The
// Angular and classic exports write one for the same reason (ZEPPELIN-672).
const BOM = '\uFEFF';
const blob = new Blob([BOM, content], { type: 'text/plain;charset=utf-8' });
saveAs(blob, `export.${type}`);
}
};
Show full example Parses and builds Excel files in Node.js on top of SheetJS.
Downloads / mo 2.0M
Stars 3.0K
Last release 0.25.0
License Apache-2.0 Strengths Typed API . The package ships TypeScript types for static type checking. $ npm install node-xlsx Copy
import xlsx from 'node-xlsx';
const sheets = xlsx.parse('./input.xlsx');
node-xlsx examples From open-source projects on GitHub /**
* 写入excel
* @param {Array} data
* @param {string} name
*/
function writeXML(data, name) {
let buffer = xlsx.build([
{
name: "抽奖结果",
data: data
}
]);
return new Promise((resolve, reject) => {
fs.writeFile(path.join(process.cwd(), name), buffer, err => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
Show full example Edits XLSX workbooks while preserving existing features and styles.
Downloads / mo 1.1M
Stars 1.0K
Last release 1.21.0
License MIT Strengths Preserves existing workbook styles . Edit a template while retaining its existing formatting. Opens compatible encrypted XLSX files . Supply a password for workbooks using XLSX Agile encryption. Limitations Renaming sheets leaves formula references . Formulas that point at a renamed sheet keep the old sheet name. Formula results need external calculation . Changed inputs do not recalculate formula values. $ npm install xlsx-populate Copy
const XlsxPopulate = require('xlsx-populate');
const workbook = await XlsxPopulate.fromBlankAsync();
workbook.sheet(0).cell('A1').value('Hello');
await workbook.toFileAsync('./output.xlsx');
xlsx-populate examples From open-source projects on GitHub async function parseXLSX(file: File): Promise<Result> {
const buffer = await readFile(file);
try {
const sheet = XLSX.read(buffer, { type: "binary" });
const json = XLSX.utils.sheet_to_json<string[]>(sheet.Sheets[sheet.SheetNames[0]], {
header: 1,
blankrows: false,
rawNumbers: false
});
return { data: json };
} catch (e) {
if (/password-protected/.test(e.message)) {
const password = prompt(
"Please enter the password to open this XLSX file. Press cancel to exit."
);
if (password === null) {
return { data: [], error: "Password required." };
}
try {
const workbook = await XlsxPopulate.fromDataAsync(buffer, { password });
const sheet = workbook.sheet(0);
if (sheet) {
let json = sheet.usedRange().value();
json = _.map(json, (row) => {
return _.map(row, (cell) => {
if (cell) {
return cell.toString();
}
return "";
});
});
return { data: json };
}
} catch (e) {
// follow through to the error below
}
return { data: [], error: "Unable to parse Password protected XLSX" };
}
throw e;
}
}
Show full example Generates XLSX files with styles, formulas, and multiple worksheets.
Downloads / mo 536.2K
Stars 135
Last release 1.8.2
License MIT Strengths Reusable cell styles . createStyle defines a style that many cells can share. $ npm install excel4node Copy
const xl = require('excel4node');
const workbook = new xl.Workbook();
const sheet = workbook.addWorksheet('Sheet1');
sheet.cell(1, 1).string('Hello');
workbook.write('output.xlsx');
excel4node examples From open-source projects on GitHub export default function generateBufferExcel(contacts: UserContact[]) {
const ws = wb.addWorksheet('Report', options);
const titles = Object.keys(contacts[0]);
titles.forEach((title, i) => {
const capitalized = title[0].toUpperCase() + title.slice(1);
ws.cell(1, i + 1)
.string(capitalized)
.style(style);
});
contacts.forEach((item, i) => {
const values = Object.values(item);
values.forEach((value, j) => {
ws.cell(i + 2, j + 1)
.string(String(value))
.style(style);
});
});
return wb.writeToBuffer();
}
Show full example