### Install and Run Development Commands Source: https://github.com/productdevbook/hucre/blob/main/README.md Use these pnpm commands for installing dependencies, running the development server, testing, building, and linting. ```sh pnpm install ``` ```sh pnpm dev # vitest watch ``` ```sh pnpm test # lint + typecheck + test ``` ```sh pnpm build # obuild (minified, tree-shaken) ``` ```sh pnpm lint:fix # oxlint + oxfmt ``` ```sh pnpm typecheck # tsgo ``` -------------------------------- ### Install Hucre Spreadsheet Engine Source: https://github.com/productdevbook/hucre/blob/main/README.md Install the Hucre package using npm. This is the first step before using any of its functionalities. ```sh npm install hucre ``` -------------------------------- ### Read and Write XLSX Files with Hucre Source: https://github.com/productdevbook/hucre/blob/main/README.md Demonstrates how to import and use Hucre's `readXlsx` and `writeXlsx` functions. The read example shows accessing rows from the first sheet, while the write example details creating a new XLSX file with specified columns and data. ```ts import { readXlsx, writeXlsx } from "hucre" // Read an XLSX file const workbook = await readXlsx(buffer) console.log(workbook.sheets[0].rows) // Write an XLSX file const xlsx = await writeXlsx({ sheets: [ { name: "Products", columns: [ { header: "Name", key: "name", width: 25 }, { header: "Price", key: "price", width: 12, numFmt: "$#,##0.00" }, { header: "Stock", key: "stock", width: 10 }, ], data: [ { name: "Widget", price: 9.99, stock: 142 }, { name: "Gadget", price: 24.5, stock: 87 }, ], }, ], }) ``` -------------------------------- ### XLSX Round-Trip Example Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Demonstrates opening an XLSX file, modifying a cell, and saving it while preserving charts, macros, and themes. ```typescript import { openXlsx, saveXlsx } from "hucre/xlsx" const workbook = await openXlsx(buffer) workbook.sheets[0].rows[0][0] = "Updated!" const output = await saveXlsx(workbook) // Charts, macros, themes, and other features preserved ``` -------------------------------- ### Apply Gradient Fill Style Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Example of applying a gradient fill with a 90-degree angle, transitioning from red to blue. ```typescript // Gradient const gradientStyle: CellStyle = { fill: { type: "gradient", degree: 90, stops: [ { position: 0, color: { rgb: "FF0000" } }, { position: 100, color: { rgb: "0000FF" } } ] } } ``` -------------------------------- ### Apply Pattern Fill Style Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Example of applying a solid pattern fill with a yellow foreground color to a cell. ```typescript const style: CellStyle = { fill: { type: "pattern", pattern: "solid", fgColor: { rgb: "FFFF00" } // Yellow } } ``` -------------------------------- ### Apply Border Style to Cell Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Example of applying different border styles and colors to the top, left, and bottom sides of a cell. ```typescript const style: CellStyle = { border: { top: { style: "medium", color: { rgb: "0000FF" } }, left: { style: "thin", color: { rgb: "000000" } }, bottom: { style: "double", color: { rgb: "0000FF" } }, } } ``` -------------------------------- ### Example: Writing Objects to an XLSX File with Table Options Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Demonstrates how to use the writeObjects function to create an inventory spreadsheet with a named table, total row, and sum for the stock column. ```typescript import { writeObjects } from "hucre" const products = [ { name: "Widget", price: 9.99, stock: 142 }, { name: "Gadget", price: 24.5, stock: 87 }, ] const xlsx = await writeObjects(products, { sheetName: "Inventory", table: { name: "Products", showTotalRow: true, totals: { stock: "sum" } } }) ``` -------------------------------- ### Handle ParseError in TypeScript Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Example of catching a ParseError and logging specific details about the parsing failure. ```typescript import { readXlsx, ParseError } from "hucre" try { const wb = await readXlsx(badBuffer) } catch (e) { if (e instanceof ParseError) { console.error( `Parse failed at ${e.details?.file}:${e.details?.line}:${e.details?.column}`, e.message ) } } ``` -------------------------------- ### Handle EncryptedFileError and DecryptionError in TypeScript Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Example demonstrating how to differentiate between a file being encrypted (EncryptedFileError) and a failed decryption attempt (DecryptionError). ```typescript import { read, EncryptedFileError, DecryptionError } from "hucre" try { const wb = await read(encryptedBuffer) } catch (e) { if (e instanceof EncryptedFileError) { console.error(`File is encrypted (${e.format}). Provide a password.`) } else if (e instanceof DecryptionError) { console.error("Password was wrong.") } } ``` -------------------------------- ### Handle UnsupportedFormatError in TypeScript Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Example of catching an UnsupportedFormatError when trying to read an unsupported file type. ```typescript import { read, UnsupportedFormatError } from "hucre" try { const wb = await read(buffer) } catch (e) { if (e instanceof UnsupportedFormatError) { console.error("Cannot read this file format:", e.message) } } ``` -------------------------------- ### Generate Spreadsheet with Hyperlinks Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Write an XLSX file containing hyperlinks using the writeXlsx function and the link() helper. This example shows how to create both external web links and internal sheet navigation links. ```typescript import { writeXlsx, link } from "hucre/xlsx" const xlsx = await writeXlsx({ sheets: [ { name: "Links", columns: [ { header: "Item", key: "item" }, { header: "Link", key: "url" } ], data: [ { item: "Product 1", url: link("View", "https://example.com/products/1") }, { item: "Sheet2", url: link("Go", "#Sheet2!A1", "Jump to Sheet 2") } ] } ] }) ``` -------------------------------- ### Hucre CLI for File Conversion and Inspection Source: https://github.com/productdevbook/hucre/blob/main/README.md Examples of using the Hucre command-line interface for converting between XLSX and CSV formats, inspecting file contents, and validating data against a schema. ```bash npx hucre convert input.xlsx output.csv npx hucre convert input.csv output.xlsx npx hucre inspect file.xlsx npx hucre inspect file.xlsx --sheet 0 npx hucre validate data.xlsx --schema schema.json ``` -------------------------------- ### Apply Font Style to Cell Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Example of applying font styles, including name, size, boldness, and color, to a cell object. ```typescript const cell: Cell = { value: "Important", type: "string", style: { font: { name: "Calibri", size: 14, bold: true, color: { rgb: "FF0000" } } } } ``` -------------------------------- ### Handle DefterError in TypeScript Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Example of how to catch and handle a DefterError in a try-catch block. ```typescript import { DefterError } from "hucre" try { // hucre operation } catch (e) { if (e instanceof DefterError) { console.error("Hucre error:", e.message) } } ``` -------------------------------- ### Add and Write Charts to XLSX Source: https://github.com/productdevbook/hucre/blob/main/README.md Create a new chart and add it to a sheet within an XLSX workbook. This example configures chart type, titles, series data, axes, legend, and data labels, then writes the workbook. ```typescript import { addChart, writeXlsx } from "hucre" const dashboard = { name: "Dashboard", rows: [ ["Quarter", "Revenue", "Forecast"], ["Q1", 12000, 11500], ["Q2", 15500, 15000], ["Q3", 14000, 14500], ["Q4", 17800, 17200], ], } addChart(dashboard, { type: "column", title: "Quarterly Revenue", titleFontSize: 14, titleBold: true, titleColor: "1F77B4", titleBorderColor: "1F77B4", titleBorderWidth: 1.5, titleBorderDash: "dash", series: [ { name: "Revenue", values: "B2:B5", categories: "A2:A5", color: "1F77B4" }, { name: "Forecast", values: "C2:C5", categories: "A2:A5", color: "FF7F0E" }, ], axes: { x: { title: "Quarter" }, y: { title: "Revenue (USD)", numberFormat: { formatCode: "$#,##0" } }, }, legend: "bottom", legendFillColor: "F2F2F2", legendBorderDash: "dot", plotAreaBorderColor: "DDDDDD", plotAreaBorderWidth: 0.75, dataLabels: { showValue: true, position: "outEnd", fontSize: 9 }, anchor: { from: { row: 6, col: 0 }, to: { row: 22, col: 7 } }, }) const xlsx = await writeXlsx({ sheets: [dashboard] }) ``` -------------------------------- ### parseRange() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Parses an A1-style range reference into its corresponding 0-based start and end row/column indices. ```APIDOC ## parseRange() ### Description Parse an A1-style range reference into 0-based indices. ### Method `export function parseRange(range: string): { startRow: number; startCol: number; endRow: number; endCol: number } | null` ### Parameters #### Path Parameters - **range** (string) - Required - The A1-style range reference (e.g., "A1:D10"). ### Response #### Success Response - **startRow** (number) - The starting row index (0-based). - **startCol** (number) - The starting column index (0-based). - **endRow** (number) - The ending row index (0-based). - **endCol** (number) - The ending column index (0-based). - Returns `null` if the range is invalid. ### Request Example ```typescript import { parseRange } from "hucre" parseRange("A1:D10") // { startRow: 0, startCol: 0, endRow: 9, endCol: 3 } ``` ``` -------------------------------- ### Selective Imports for Tree Shaking Source: https://github.com/productdevbook/hucre/blob/main/README.md Import only the specific modules you need from Hucre to enable tree shaking and reduce bundle size. This example shows imports for XLSX, CSV, ODS, JSON/NDJSON, and XML modules. ```typescript import { readXlsx, writeXlsx } from "hucre/xlsx" // XLSX only import { parseCsv, writeCsv } from "hucre/csv" // CSV only (~2 KB gzipped) import { readOds, writeOds } from "hucre/ods" // ODS only import { parseJson, writeNdjson } from "hucre/json" // JSON / NDJSON import { readXml, writeXml } from "hucre/xml" // Tabular XML ``` -------------------------------- ### Import Main Entry Point (Auto-detect) Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/README.md Import the main read and write functions for auto-detecting file formats. This is the primary way to use Hucre for general file operations. ```typescript import { read, write, readObjects, writeObjects } from "hucre" ``` -------------------------------- ### Handle ValidationError in TypeScript Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Example of catching a ValidationError and iterating through the collected errors to log details. ```typescript import { validateWithSchema, ValidationError } from "hucre" try { const result = validateWithSchema(rows, schema, { collectAllErrors: false }) } catch (e) { if (e instanceof ValidationError) { for (const err of e.errors) { console.error( `Row ${err.row}, field "${err.field}": ${err.message}`, `(got "${err.value}")` ) } } } ``` -------------------------------- ### a11y.applyA11ySummary() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-advanced-features.md Promotes the first sheet's accessibility summary to the workbook's core properties description. ```APIDOC ## a11y.applyA11ySummary() ### Description Promote the first sheet's `a11y.summary` to the workbook's description (in core properties). ### Method Signature ```typescript a11y.applyA11ySummary(workbook: Workbook): void ``` ### Parameters * `workbook` (Workbook) - The workbook to modify. ``` -------------------------------- ### deleteRows() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Deletes a specified number of rows from a sheet starting at a given index, shifting remaining rows up. ```APIDOC ## deleteRows() ### Description Deletes rows from a sheet, shifting remaining rows up. ### Method ```typescript deleteRows(sheet: Sheet, index: number, count?: number): void ``` ### Parameters #### Path Parameters - **sheet** (Sheet) - Required - Sheet to modify - **index** (number) - Required - 0-based start position - **count** (number) - Optional - Number of rows to delete (default: 1) ``` -------------------------------- ### Build XLSX Files with Fluent API Source: https://github.com/productdevbook/hucre/blob/main/README.md Demonstrates the `WorkbookBuilder` for creating XLSX files using a fluent, method-chaining interface to define sheets, columns, rows, and freeze panes. ```typescript import { WorkbookBuilder } from "hucre" const xlsx = await WorkbookBuilder.create() .addSheet("Products") .columns([ { header: "Name", key: "name", autoWidth: true }, { header: "Price", key: "price", numFmt: "$"#,##0.00"" }, ]) .row(["Widget", 9.99]) .row(["Gadget", 24.5]) .freeze(1) .done() .build() ``` -------------------------------- ### MergeRange Interface Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Defines a rectangular range of cells using 0-based start and end row/column indices. ```typescript interface MergeRange { startRow: number // 0-based startCol: number // 0-based endRow: number // 0-based, inclusive endCol: number // 0-based, inclusive } ``` -------------------------------- ### Add and Read Charts in XLSX Source: https://github.com/productdevbook/hucre/blob/main/README.md Demonstrates how to read existing charts from a workbook and how to declaratively add new charts when writing an XLSX file. ```typescript import { addChart, getCharts, openXlsx, writeXlsx } from "hucre" const wb = await openXlsx(templateBytes) // Read side — find every chart in a template workbook. for (const { sheetName, chart } of getCharts(wb)) { console.log(sheetName, chart.kinds, chart.title) } // Write side — declarative chart attachment. const dashboard = { name: "Dashboard", rows: dashboardRows } addChart(dashboard, { type: "column", title: "Q1 Revenue", series: [{ name: "Revenue", values: "B2:B13", categories: "A2:A13" }], anchor: { from: { row: 14, col: 0 } }, }) await writeXlsx({ sheets: [dashboard] }) ``` -------------------------------- ### Builder Class Source: https://github.com/productdevbook/hucre/blob/main/README.md Provides a fluent API for constructing workbooks and filling templates with data. ```APIDOC ## Builder Class ### Description Provides a fluent API for constructing workbooks and filling templates with data. ### Classes and Functions - `WorkbookBuilder.create()`: Initializes a fluent API for building workbooks. - `fillTemplate(workbook, data)`: Replaces `{{placeholders}}` within workbook templates using provided data. ``` -------------------------------- ### deleteColumns() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Deletes a specified number of columns from a sheet starting at a given index, shifting remaining columns to the left. ```APIDOC ## deleteColumns() ### Description Deletes columns, shifting remaining columns left. ### Method ```typescript deleteColumns(sheet: Sheet, index: number, count?: number): void ``` ### Parameters #### Path Parameters - **sheet** (Sheet) - Required - Sheet to modify - **index** (number) - Required - 0-based start position - **count** (number) - Optional - Number of columns to delete (default: 1) ``` -------------------------------- ### Apply Accessibility Summary to Workbook Description Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-advanced-features.md Use `a11y.applyA11ySummary()` to promote the accessibility summary from the first sheet to the workbook's core properties description. ```typescript export const a11y = { applyA11ySummary(workbook: Workbook): void } ``` -------------------------------- ### Convert Between File Formats Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/quick-reference.md Read data from a buffer (auto-detecting format) and then write it out to different formats like XLSX or CSV. ```typescript import { read, writeXlsx, writeCsv } from "hucre" const wb = await read(buffer) // Auto-detect const xlsx = await writeXlsx({ sheets: wb.sheets }) const csv = writeCsv(wb.sheets[0].rows) ``` -------------------------------- ### Handle DecryptionError in TypeScript Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Example of how to catch and handle a DecryptionError when reading an encrypted file. This pattern is useful for providing user-friendly feedback on decryption failures. ```typescript import { read, DecryptionError } from "hucre" try { const wb = await read(encryptedBuffer, { password: "guess" }) } catch (e) { if (e instanceof DecryptionError) { console.error("Decryption failed: wrong password or corrupt file.") } } ``` -------------------------------- ### Get All Charts from Workbook Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Retrieves all charts from a workbook and flattens them into a single array, providing sheet context for each chart. Useful for iterating over all charts in a document. ```typescript export function getCharts( workbook: Workbook ): Array<{ sheetName: string; chart: Chart }> ``` ```typescript import { readXlsx, getCharts } from "hucre" const wb = await readXlsx(buffer) for (const { sheetName, chart } of getCharts(wb)) { console.log(sheetName, chart.title, chart.kinds) } ``` -------------------------------- ### Fill Placeholders in XLSX Templates Source: https://github.com/productdevbook/hucre/blob/main/README.md Shows how to use `fillTemplate` to populate `{{placeholders}}` within an existing XLSX file with provided data, then save the modified workbook. ```typescript import { openXlsx, saveXlsx, fillTemplate } from "hucre" const workbook = await openXlsx(templateBuffer) fillTemplate(workbook, { company: "Acme Inc", date: new Date(), total: 12500, }) const output = await saveXlsx(workbook) ``` -------------------------------- ### Add Sparklines to a Sheet Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Integrate sparklines into your spreadsheet by adding a 'sparklines' array to the sheet object. This example demonstrates a line sparkline with custom color and markers. ```typescript const sheet: WriteSheet = { name: "Report", rows: [ ["Month", "Jan", "Feb", "Mar", "Trend"], ["Sales", 100, 120, 110, null] ], sparklines: [ { location: "D2", dataRange: "B2:D2", type: "line", color: "1F77B4", markers: true } ] } ``` -------------------------------- ### Generate and Audit Accessible Spreadsheets Source: https://github.com/productdevbook/hucre/blob/main/README.md Create screen-reader-friendly spreadsheets with alt text for images and per-sheet summaries. Audit workbooks for common WCAG 2.1 AA issues like missing alt text, header rows, and low contrast. ```typescript import { writeXlsx, a11y, readXlsx } from "hucre" const xlsx = await writeXlsx({ sheets: [ { name: "Q1 Sales", rows: [ ["Region", "Revenue"], ["EU", 12_400], ], a11y: { summary: "Quarterly sales by region", headerRow: 0 }, images: [ { data: pngBytes, type: "png", anchor: { from: { row: 0, col: 3 } }, altText: "Bar chart showing 47% YoY growth", }, ], }, ], }) // Audit a workbook for missing alt text, missing header rows, // merged headers, low contrast, and more. const wb = await readXlsx(xlsx) for (const issue of a11y.audit(wb)) { console.log(issue.type, issue.code, issue.message, issue.location) } // Color contrast helpers (WCAG 2.1 sRGB) a11y.contrastRatio("0969DA", "FFFFFF") // ≈ 4.93 (passes AA) a11y.relativeLuminance("808080") ``` -------------------------------- ### Delete Rows from Sheet Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Deletes a specified number of rows starting from a given index. Rows below the deleted section are shifted upwards. Use with caution as data will be lost. ```typescript export function deleteRows( sheet: Sheet, index: number, count: number = 1 ): void ``` -------------------------------- ### fromHtml() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-export-xml.md Parse an HTML into a sheet. ```APIDOC ## fromHtml() ### Description Parse an HTML `
` into a sheet. ### Method ```typescript export function fromHtml( html: string, options?: { headerRow?: boolean } ): Sheet ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **html** (`string`) - Required - HTML containing one or more `
` elements - **options.headerRow** (`boolean`) - Optional - Treat first row as headers (default: false) ### Request Example ```typescript import { fromHtml, writeXlsx } from "hucre" const html = `
NamePrice
Widget9.99
` const sheet = fromHtml(html, { headerRow: true }) const xlsx = await writeXlsx({ sheets: [sheet] }) ``` ### Response #### Success Response (200) `Sheet` with parsed data #### Response Example (No specific example provided in source, but implies a Sheet object structure) ``` -------------------------------- ### Parse A1 Range Reference Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Parses an A1-style range reference (e.g., 'A1:D10') into its 0-based start and end row/column indices. Returns null if the format is invalid. ```typescript import { parseRange } from "hucre" parseRange("A1:D10") // { startRow: 0, startCol: 0, endRow: 9, endCol: 3 } ``` -------------------------------- ### Calculate Color Contrast Ratio Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-advanced-features.md Calculate the sRGB contrast ratio between foreground and background hex colors using `a11y.contrastRatio()`. The ratio ranges from 1 to 21, indicating the level of readability. ```typescript export const a11y = { contrastRatio(foreground: string, background: string): number } ``` ```typescript import { a11y } from "hucre" a11y.contrastRatio("FFFFFF", "000000") // 21 (max) a11y.contrastRatio("0969DA", "FFFFFF") // ~4.93 (passes AA) ``` -------------------------------- ### Create A1 Range Reference Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Creates an A1-style range reference (e.g., 'A1:D10') from 0-based start and end row/column indices. Useful for defining data areas. ```typescript import { rangeRef } from "hucre" rangeRef(0, 0, 9, 3) // "A1:D10" ``` -------------------------------- ### writeXlsx() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Writes a workbook to XLSX format, supporting comprehensive styling, charts, pivot tables, data validations, conditional formatting, and more. ```APIDOC ## writeXlsx() ### Description Writes a workbook to XLSX format with comprehensive styling, charts, and advanced features. ### Method `writeXlsx` ### Parameters #### Options - **options** (WriteOptions) - Required - Workbook configuration - **options.sheets** (WriteSheet[]) - Required - Array of sheets to write - **sheets[].name** (string) - Optional - Sheet name - **sheets[].data** (Record[]) - Optional - Object-based rows - **sheets[].rows** (CellValue[][]) - Optional - Raw cell data - **sheets[].columns** (ColumnDef[]) - Optional - Column definitions - **sheets[].cells** (Map<"row,col", Cell>) - Optional - Cell-level overrides - **sheets[].images** (SheetImage[]) - Optional - Embedded images - **sheets[].charts** (SheetChart[]) - Optional - Chart definitions - **sheets[].pivotTables** (WritePivotTable[]) - Optional - Pivot table definitions - **sheets[].dataValidations** (DataValidation[]) - Optional - Data validation rules - **sheets[].conditionalRules** (ConditionalRule[]) - Optional - Conditional formatting - **sheets[].autoFilter** (AutoFilter) - Optional - Auto-filter range and criteria - **sheets[].freezePane** (FreezePane) - Optional - Frozen panes - **sheets[].merges** (MergeRange[]) - Optional - Merged cells - **sheets[].tables** (TableDefinition[]) - Optional - Excel tables - **sheets[].sparklines** (Sparkline[]) - Optional - Sparkline charts - **sheets[].textBoxes** (SheetTextBox[]) - Optional - Text boxes and shapes - **sheets[].namedRanges** (NamedRange[]) - Optional - Workbook-scoped named ranges - **sheets[].protection** (SheetProtection) - Optional - Sheet-level protection - **options.properties** (WorkbookProperties) - Optional - Workbook properties (title, creator, etc.) - **options.encryption** (EncryptionOptions) - Optional - Workbook encryption settings ### Return `Promise` — XLSX file data ### Example ```typescript import { writeXlsx } from "hucre/xlsx" const xlsx = await writeXlsx({ sheets: [ { name: "Sales", columns: [ { header: "Date", key: "date", numFmt: "yyyy-mm-dd", autoWidth: true }, { header: "Amount", key: "amount", numFmt: "$#,##0.00", width: 12 }, ], data: [ { date: new Date("2026-01-15"), amount: 1250 }, { date: new Date("2026-01-16"), amount: 890 }, ], freezePane: { rows: 1 }, autoFilter: { range: "A1:B3" }, }, ], properties: { title: "Monthly Report", creator: "Sales Team", }, encryption: { password: "secret", }, }) ``` ``` -------------------------------- ### Delete Columns from Sheet Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Deletes a specified number of columns starting from a given index. Columns to the right of the deleted section are shifted left. Data in deleted columns will be lost. ```typescript export function deleteColumns( sheet: Sheet, index: number, count: number = 1 ): void ``` -------------------------------- ### openXlsx() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Opens an XLSX file for modification while preserving unknown parts like charts, macros, and VBA. Returns a RoundtripWorkbook. ```APIDOC ## openXlsx() ### Description Opens an XLSX file for modification and round-trip preservation. Preserves unknown parts (charts, macros, VBA, themes, etc.) that hucre doesn't natively handle. ### Parameters - **input** (Uint8Array | ArrayBuffer | ReadableStream) - Required - The XLSX file content. - **options** (ReadOptions) - Optional - Options for reading the XLSX file. ### Return `Promise` - Workbook with all content preserved for re-serialization. ### Example ```typescript import { openXlsx, saveXlsx } from "hucre/xlsx" const workbook = await openXlsx(buffer) workbook.sheets[0].rows[0][0] = "Updated!" const output = await saveXlsx(workbook) // Charts, macros, themes, and other features preserved ``` ``` -------------------------------- ### Parse XML with SAX-style Events using parseSax Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-export-xml.md Utilize parseSax for SAX-style (streaming) XML parsing with event handlers for element start, text content, and element end. ```typescript import { parseSax } from "hucre/xml" parseSax(xmlString, { startElement: (name, attrs) => console.log("START", name, attrs), text: (data) => console.log("TEXT", data), endElement: (name) => console.log("END", name) }) ``` -------------------------------- ### Export Workbook Sheet to HTML and Markdown Source: https://github.com/productdevbook/hucre/blob/main/README.md Demonstrates converting a workbook sheet into HTML and Markdown formats, with options for including headers, styles, and classes in the HTML output. ```typescript import { toHtml, toMarkdown } from "hucre" const html = toHtml(workbook.sheets[0], { headerRow: true, styles: true, classes: true, }) const md = toMarkdown(workbook.sheets[0]) // | Name | Price | Stock | // |--------|-------:|------:| // | Widget | 9.99 | 142 | ``` -------------------------------- ### Read, Modify, and Write Workbook Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/quick-reference.md A common pattern to read a workbook, modify its content in memory, and then write it back out. ```typescript import { read, write } from "hucre" const wb = await read(buffer) wb.sheets[0].rows[0][0] = "Updated" const xlsx = await write({ sheets: wb.sheets }) ``` -------------------------------- ### Add Image to Spreadsheet with Hucre Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-styling-charts.md Demonstrates how to use the `writeXlsx` function from the hucre library to add a PNG image to a spreadsheet. Ensure image data is correctly formatted as a Uint8Array. ```typescript import { writeXlsx, imageFromBase64 } from "hucre" const pngBytes = new Uint8Array([...]) // PNG data const xlsx = await writeXlsx({ sheets: [ { name: "Dashboard", rows: [["Chart"]], images: [ { data: pngBytes, type: "png", anchor: { from: { row: 0, col: 1 } }, altText: "Revenue chart" } ] } ] }) ``` -------------------------------- ### Group Rows in Sheet Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-sheet-operations.md Creates an outline group for a contiguous range of rows. This feature is collapsible in spreadsheet applications like Excel. Specify the start and end row indices and an optional initial collapsed state. ```typescript export function groupRows( sheet: Sheet, startIndex: number, endIndex: number, collapsed?: boolean ): void ``` -------------------------------- ### write() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Writes a workbook to the specified format (XLSX or ODS). It allows configuration of sheets, properties, default font, date system, and encryption. ```APIDOC ## write() ### Description Writes a workbook to the specified format (XLSX or ODS). It allows configuration of sheets, properties, default font, date system, and encryption. ### Method `async write(options: WriteOptions & { format?: "xlsx" | "ods" }): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options.format** (`"xlsx" | "ods"`) - Optional - Default: `"xlsx"` - Output format - **options.sheets** (`WriteSheet[]`) - Required - Array of sheets to write - **options.properties** (`WorkbookProperties`) - Optional - Workbook metadata (title, author, etc.) - **options.defaultFont** (`FontStyle`) - Optional - Default font for the workbook - **options.dateSystem** (`"1900" | "1904"`) - Optional - Default: `"1900"` - Excel date serial system - **options.encryption** (`{ password: string; spinCount?: number }`) - Optional - Password protection (XLSX only) - **options.activeSheet** (`number`) - Optional - Default: `0` - 0-based index of active sheet on open ### Request Example ```typescript import { write } from "hucre" const xlsx = await write({ sheets: [ { name: "Products", columns: [ { header: "Name", key: "name", width: 20 }, { header: "Price", key: "price", width: 12 }, ], data: [ { name: "Widget", price: 9.99 }, { name: "Gadget", price: 24.5 }, ], }, ], }) // With encryption const encrypted = await write({ sheets: [{ name: "Secret", rows: [["data"]] }], encryption: { password: "hunter2" }, }) ``` ### Response #### Success Response (200) `Promise` — Binary file data (XLSX or ODS) #### Response Example None explicitly provided, but returns `Uint8Array` data. ### Throws None explicitly documented for `write`. ``` -------------------------------- ### Assemble Cell Images Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-advanced-features.md Combines parsed cell image references with resolved media bytes to create `CellImage[]`. This is used to prepare cell images for reading. ```typescript export function assembleCellImages( refs: ParsedCellImageRef[], mediaMap: Map ): CellImage[] ``` -------------------------------- ### Validate Tabular Data with Schema Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-advanced-features.md Use `validateWithSchema` to validate and coerce tabular data against a defined schema. It supports type inference, custom validation rules, and error collection. Specify header rows, starting rows, and maximum rows for processing. ```typescript export function validateWithSchema( rows: CellValue[][], schema: SchemaDefinition, options?: { headerRow?: number | string[] // 0-based row index or explicit headers startRow?: number // Skip rows before this (0-based) maxRows?: number // Process only this many rows collectAllErrors?: boolean // Default: true (collect all, don't stop on first) } ): { data: Record[] // Validated & coerced errors: Array<{ row: number column: string | number field: string message: string value: unknown }> } ``` ```typescript interface SchemaField { type?: "string" | "number" | "integer" | "boolean" | "date" required?: boolean pattern?: RegExp // Regex validation (strings) min?: number // Min value (numbers) or length (strings) max?: number // Max value (numbers) or length (strings) enum?: unknown[] // Allowed values default?: unknown // Default for null/empty validate?: (v: unknown) => boolean | string // Custom validator transform?: (v: unknown) => unknown // Post-validation transform column?: string // Column header name columnIndex?: number // Column index (0-based) } ``` ```typescript import { validateWithSchema, parseCsv } from "hucre" const csv = `Product,Price,SKU,Stock Widget,9.99,WID-0001,142 Gadget,24.5,GAD-0002,87` const rows = parseCsv(csv) const result = validateWithSchema(rows, { "Product": { type: "string", required: true }, "Price": { type: "number", required: true, min: 0 }, "SKU": { type: "string", pattern: /^[A-Z]{3}-\d{4}$/ }, "Stock": { type: "integer", min: 0, default: 0 } }, { headerRow: 0 }) console.log(result.data) // Validated objects console.log(result.errors) // [{ row: 2, field: "Stock", message: "...", value: "abc" }] ``` -------------------------------- ### Write Objects to Tabular XML Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-export-xml.md Use `writeXml` to convert an array of objects into a tabular XML string. Keys starting with `@` become attributes, and dot-paths in keys create nested elements. Options control the root tag, row tag, output indentation, and XML declaration. ```typescript import { writeXml } from "hucre/xml" const xml = writeXml( [ { "@code": "P1", Name: "Oak", "Pricing.Cost": 100, "Pricing.Retail": 180 }, { "@code": "P2", Name: "Pine", "Pricing.Cost": 90, "Pricing.Retail": 160 } ], { rootTag: "Catalog", rowTag: "Product", pretty: true } ) // Output: // // // // Oak // // 100 // 180 // // // ... // ``` -------------------------------- ### writeOds() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Writes a workbook object to ODS format. Requires write options. ```APIDOC ## writeOds() ### Description Writes a workbook to ODS format. ### Parameters - **options** (WriteOptions) - Required - Options for writing the ODS file. ### Return `Promise` - The ODS file content as a Uint8Array. ``` -------------------------------- ### Open XLSX for Round-Trip Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Opens an XLSX file for modification while preserving unknown parts like charts, macros, and themes. Returns a RoundtripWorkbook. ```typescript export async function openXlsx( input: Uint8Array | ArrayBuffer | ReadableStream, options?: ReadOptions ): Promise ``` -------------------------------- ### CSV Write Options Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Configuration options for writing CSV files. Customize delimiters, BOM, quoting, escaping, and line terminators. ```typescript interface CsvWriteOptions { delimiter?: string // Default: "," bom?: boolean // Add UTF-8 BOM quote?: string // Default: '"' escape?: string // Default: '"' (doubled) lineTerminator?: string // Default: "\r\n" } ``` -------------------------------- ### fillTemplate() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-advanced-features.md Replaces `{{placeholder}}` patterns in a workbook with provided data. Supports nested objects with dot-notation. ```APIDOC ## fillTemplate() ### Description Replace `{{placeholder}}` patterns in a workbook with values. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method ```typescript export function fillTemplate( workbook: RoundtripWorkbook, data: Record ): void ``` ### Parameters - **workbook** (`RoundtripWorkbook`) - Required - Workbook opened with `openXlsx()` - **data** (`Record`) - Required - Key-value pairs to substitute ### Request Example ```typescript import { openXlsx, fillTemplate, saveXlsx } from "hucre" const templateBuffer = await fetch("template.xlsx").then(r => r.arrayBuffer()) const wb = await openXlsx(templateBuffer) fillTemplate(wb, { company: "Acme Inc", date: new Date("2026-01-15"), total: 12500 }) const output = await saveXlsx(wb) ``` ### Response #### Success Response (void) This function does not return a value. #### Response Example N/A ``` -------------------------------- ### CSV Read Options Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Configuration options for reading CSV files. Allows customization of delimiters, headers, type inference, and value transformations. ```typescript interface CsvReadOptions { delimiter?: string // Auto-detect by default hasHeaders?: boolean // Default: false typeInference?: boolean // Default: false (keep all as strings) transformHeader?: (h: string) => string transformValue?: (v: CellValue, header: string) => CellValue onError?: (line: number, error: Error) => void } ``` -------------------------------- ### Fill Templates in Spreadsheets Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/quick-reference.md Load an XLSX template using `openXlsx`, fill in placeholders with dynamic data using `fillTemplate`, and save the modified workbook with `saveXlsx`. ```typescript import { openXlsx, fillTemplate, saveXlsx } from "hucre" const wb = await openXlsx(templateBuffer) fillTemplate(wb, { company: "Acme Inc", date: new Date(), total: 12500 }) const output = await saveXlsx(wb) ``` -------------------------------- ### Parse and Generate Cell References Source: https://github.com/productdevbook/hucre/blob/main/README.md Illustrates utilities for parsing cell references (e.g., 'AA15') into row/column objects and generating cell references and ranges from row/column indices. ```typescript import { parseCellRef, cellRef, colToLetter, rangeRef } from "hucre" parseCellRef("AA15") // { row: 14, col: 26 } cellRef(14, 26) // "AA15" colToLetter(26) // "AA" rangeRef(0, 0, 9, 3) // "A1:D10" ``` -------------------------------- ### fetchCsv() Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-export-xml.md Fetches a CSV file from a given URL and parses its content. It allows for custom CSV reading options and fetch request options. ```APIDOC ## fetchCsv() ### Description Fetch a CSV file from a URL and parse it. ### Parameters #### Path Parameters - **url** (string) - Required - URL to CSV file - **options** (CsvReadOptions & { responseOptions?: RequestInit }) - Optional - CSV parsing options (delimiter, headers, etc.) and fetch options (headers, auth, etc.) ### Return Parsed data and headers ### Example ```typescript import { fetchCsv } from "hucre" const { data, headers } = await fetchCsv("https://example.com/data.csv", { delimiter: ",", header: true, responseOptions: { headers: { "Authorization": "Bearer token" } } }) ``` ``` -------------------------------- ### JSON Read Options Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Configuration options for reading JSON data. Specify the path to rows, flattening behavior, header/value transformations, and maximum rows. ```typescript interface JsonReadOptions { rowsAt?: string // Dot-path to rows array flatten?: boolean // Default: true transformHeader?: (h: string, idx: number) => string transformValue?: (v: CellValue, header: string, rowIdx: number) => CellValue maxRows?: number } ``` -------------------------------- ### Read and Write ODS Files Source: https://github.com/productdevbook/hucre/blob/main/README.md Use `readOds` to load an ODS file from a buffer and `writeOds` to create an ODS file with specified sheet data. ```typescript import { readOds, writeOds } from "hucre/ods" const wb = await readOds(buffer) const ods = await writeOds({ sheets: [{ name: "Sheet1", rows: [["Hello", 42]] }] }) ``` -------------------------------- ### Roundtrip Charts with Sheet Copying Source: https://github.com/productdevbook/hucre/blob/main/README.md Shows how charts are preserved when a sheet is copied between workbooks using `copySheetToWorkbook` and then saved. ```typescript import { copySheetToWorkbook, getCharts, openXlsx, saveXlsx } from "hucre" const template = await openXlsx(templateBytes) const report = await openXlsx(reportBytes) // Copy a chart-bearing sheet from the template into the report workbook… copySheetToWorkbook(template.sheets[0], report, "Dashboard") // …and saveXlsx re-emits the chart parts (not just the cell data). const out = await saveXlsx(report) console.log(getCharts(await openXlsx(out)).length) // includes the copied chart ``` -------------------------------- ### Define Custom UnsupportedFormatError Class Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/types-and-errors.md Thrown when an unknown or unsupported file format is encountered. Includes the format that was not supported. ```typescript export class UnsupportedFormatError extends DefterError { name = "UnsupportedFormatError" constructor(format: string) } ``` -------------------------------- ### Write XLSX File with Comprehensive Options Source: https://github.com/productdevbook/hucre/blob/main/_autodocs/api-read-write.md Use `writeXlsx` to generate XLSX files. Supports detailed sheet configurations including columns, data, styling, charts, and protection. Requires a `WriteOptions` object. ```typescript export async function writeXlsx( options: WriteOptions ): Promise ``` ```typescript import { writeXlsx } from "hucre/xlsx" const xlsx = await writeXlsx({ sheets: [ { name: "Sales", columns: [ { header: "Date", key: "date", numFmt: "yyyy-mm-dd", autoWidth: true }, { header: "Amount", key: "amount", numFmt: "$#,##0.00", width: 12 }, ], data: [ { date: new Date("2026-01-15"), amount: 1250 }, { date: new Date("2026-01-16"), amount: 890 }, ], freezePane: { rows: 1 }, autoFilter: { range: "A1:B3" }, }, ], properties: { title: "Monthly Report", creator: "Sales Team", }, encryption: { password: "secret", }, }) ```