UNPKG

@oniryk/xlsx

Version:

A lightweight, efficient TypeScript library for generating single-sheet Excel XLSX files with support for large datasets

85 lines (84 loc) 3.15 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const fs_1 = __importDefault(require("fs")); const os_1 = __importDefault(require("os")); const path_1 = __importDefault(require("path")); const utils_1 = require("./utils"); /** * Manages shared strings in an Excel workbook * Handles deduplication and XML generation for the shared strings table * Used to optimize file size by storing repeated strings only once */ class SharedStrings { /** * Creates a new SharedStrings instance * Initializes a temporary file for XML generation */ constructor() { /** Array of unique strings in the workbook */ this.strings = []; /** Map of strings to their indices for quick lookup */ this.stringIndexMap = new Map(); this.file = path_1.default.join(os_1.default.tmpdir(), `xlsx-strings-${(0, crypto_1.randomUUID)()}.xml`); } /** * Adds a string to the shared strings table * If the string already exists, returns its index * If the string is new, adds it and returns the new index * * @param str - String to add to the shared strings table * @returns Index of the string in the shared strings table */ add(str) { if (this.stringIndexMap.has(str)) { return this.stringIndexMap.get(str); } const index = this.strings.push(str) - 1; this.stringIndexMap.set(str, index); return index; } /** * Generates the shared strings XML file * Creates an XML file containing all unique strings in the workbook * Processes strings in chunks to manage memory usage * * @returns Promise that resolves to the path of the generated XML file */ async generateSharedStringsXML() { const ws = fs_1.default.createWriteStream(this.file); const write = (0, utils_1.promiseWrite)(ws); await write(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n`, `<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${this.strings.length}" uniqueCount="${this.strings.length}">`); const acc = []; for (const str of this.strings) { acc.push(`<si><t>${(0, utils_1.escapeXML)(str)}</t></si>`); if (acc.length % 5000 === 0) { await write(acc.join('')); acc.length = 0; } } await write(acc.join(''), '</sst>'); await (0, utils_1.finishStream)(ws); return this.file; } /** * Gets the total number of unique strings in the table * @returns Number of unique strings */ size() { return this.strings.length; } /** * Clears all strings and mappings from memory * Should be called when the shared strings table is no longer needed */ destroy() { this.strings.length = 0; this.stringIndexMap.clear(); } } exports.default = SharedStrings;