excel-zod
v0.1.1
Published
Connect Zod schemas with Excel - read, write, and validate spreadsheets with type safety
Maintainers
Readme
excel-zod
Type-safe Excel reading and writing with Zod schemas.
Define your spreadsheet structure with Zod, then read, write, and validate Excel files with full TypeScript type safety. No more manual column mapping, no more runtime surprises.
Why excel-zod?
- Schema-first - Define your Excel structure once, get types and validation for free
- Full type inference - Parsed data is fully typed based on your Zod schema
- Detailed errors - Row number, column name, expected vs actual values
- Template generation - Create blank Excel files with headers, validation, and formatting
- Zero config - Headers auto-match to schema keys (case-insensitive)
- Battle-tested foundation - Built on ExcelJS and Zod
Installation
npm install excel-zod zodZod is a peer dependency. You need to install it separately.
Quick Start
import { z } from 'zod';
import { createExcelSchema } from 'excel-zod';
// 1. Define your schema
const UserSchema = createExcelSchema(z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int().positive(),
joinDate: z.date(),
active: z.boolean(),
}));
// 2. Read Excel into typed, validated objects
const { data, errors } = await UserSchema.parse('users.xlsx');
// data: { name: string, email: string, age: number, joinDate: Date, active: boolean }[]
if (errors.length > 0) {
console.error('Validation errors:');
for (const err of errors) {
console.error(` Row ${err.row}, Column "${err.column}": ${err.message}`);
}
}
// 3. Write typed data back to Excel
await UserSchema.write(data, 'output.xlsx');
// 4. Generate a blank template
await UserSchema.generateTemplate('template.xlsx');API Reference
createExcelSchema(zodSchema)
Creates an ExcelSchema instance from a Zod object schema.
const schema = createExcelSchema(z.object({ ... }));schema.parse(filePath, options?)
Read and validate an Excel file. Returns { data, errors, totalRows }.
Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| sheet | string \| number | 1 | Sheet name or 1-based index |
| headerRow | number | 1 | Row containing headers |
| startRow | number | headerRow + 1 | First data row |
| columns | ColumnMapping[] | auto-detect | Custom column mappings |
| stopOnEmpty | boolean | true | Stop on first empty row |
schema.parseStrict(filePath, options?)
Same as parse, but throws ExcelValidationError if any rows fail validation.
schema.write(data, filePath, options?)
Write typed data to an Excel file with headers, formatting, and proper column widths.
Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| sheetName | string | "Sheet1" | Worksheet name |
| columns | ColumnMapping[] | auto | Custom header names |
schema.generateTemplate(filePath, options?)
Generate a blank Excel template with headers, type hints, data validation, and frozen header row.
Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| sheetName | string | "Sheet1" | Worksheet name |
| addValidation | boolean | true | Add Excel data validation |
| freezeHeader | boolean | true | Freeze the header row |
Column Mapping
By default, excel-zod matches Excel headers to schema keys (case-insensitive). You can customize this:
// Match by custom header names
const { data } = await schema.parse('file.xlsx', {
columns: [
{ key: 'name', header: 'Full Name' },
{ key: 'email', header: 'Email Address' },
],
});
// Match by column index (1-based)
const { data } = await schema.parse('file.xlsx', {
columns: [
{ key: 'name', index: 1 },
{ key: 'email', index: 3 },
],
});Error Handling
import { ExcelValidationError } from 'excel-zod';
try {
const data = await schema.parseStrict('users.xlsx');
} catch (err) {
if (err instanceof ExcelValidationError) {
console.error(err.format());
// Row 3, Column "email": Invalid email (got: "not-an-email")
// Row 5, Column "age": Number must be greater than 0 (got: -1)
}
}Supported Types
| Zod Type | Excel Handling |
|----------|---------------|
| z.string() | Text cells, auto-coerced |
| z.number() | Numeric cells, string-to-number coercion |
| z.boolean() | Yes/No, true/false, 1/0 |
| z.date() | Excel dates, serial numbers, ISO strings |
| z.optional() | Allows empty cells |
| z.default() | Uses default for empty cells |
Comparison with Alternatives
| Feature | excel-zod | Manual ExcelJS | csv-parse + zod | |---------|-----------|---------------|-----------------| | Type-safe reading | Yes | No | Partial | | Schema validation | Built-in | Manual | Separate step | | Excel write | Yes | Manual setup | No (CSV only) | | Template generation | Yes | Manual | No | | Error messages | Row + column | Manual | Row only | | Date handling | Automatic | Manual | Manual |
Pro Version
Looking for advanced features like multi-sheet schemas, streaming for large files, custom formatters, and pivot table generation? Check out excel-zod Pro (coming soon).
License
MIT
