XLSX
Patching
Modify existing .xlsx files by replacing placeholders with new content
Patch an existing .xlsx template by replacing {{placeholder}} tokens with new cell values.
patchWorkbook
Replaces placeholders in an existing .xlsx file:
import { patchWorkbook } from "@office-open/xlsx";
import { readFileSync, writeFileSync } from "node:fs";
const result = await patchWorkbook({
outputType: "nodebuffer",
data: readFileSync("template.xlsx"),
patches: {
name: { value: "John Doe" },
amount: { value: 1500 },
date: { value: "2024-12-31" },
},
});
writeFileSync("output.xlsx", result);
How It Works
The patcher scans all cells in every worksheet for text matching the placeholder pattern (default {{key}}). When found, it replaces the cell value with the patch content.
Placeholders that span multiple runs (split by formatting) are handled automatically.
Patch Values
Each patch replaces the cell value with a new value:
patches: {
name: { value: "Alice" }, // String
quantity: { value: 42 }, // Number
active: { value: true }, // Boolean
deadline: { value: new Date("2024-12-31") }, // Date
}
The patch value type determines the cell type in the output.
Custom Delimiters
Default delimiters are {{ and }}. Change them with placeholderDelimiters:
await patchWorkbook({
outputType: "nodebuffer",
data: templateBuffer,
patches: { name: { value: "John" } },
placeholderDelimiters: { start: "<<", end: ">>" },
});
Output Types
The outputType parameter controls the return type:
outputType | Returns |
|---|---|
"nodebuffer" | Buffer |
"uint8array" | Uint8Array |
"arraybuffer" | ArrayBuffer |
"base64" | string |
"blob" | Blob |
"string" | string |
Options
| Option | Type | Default | Description |
|---|---|---|---|
outputType | string | — | Output format (see table above) |
data | Buffer | Uint8Array | ... | — | Input .xlsx file data |
patches | Record<string, IPatch> | — | Map of placeholder name to new value |
placeholderDelimiters | { start: string, end: string} | { {{, }} } | Custom placeholder delimiters |
Tips
- Placeholders are replaced in all worksheets across the workbook.
- The original cell's style is preserved when replacing the value.
- Use
nodebufferfor Node.js file I/O andblobfor browser downloads. - Patch values are plain values (no need for class instances).