export type XlsxCellValue = string | number | boolean | null | undefined;
export interface XlsxWorksheetData {
sheetName?: string;
columns: readonly string[];
columnTypes?: readonly string[];
rows: readonly (readonly XlsxCellValue[])[];
}
type ZipEntry = {
path: string;
data: Uint8Array;
crc: number;
localHeaderOffset: number;
};
const encoder = new TextEncoder();
const CRC_TABLE = buildCrcTable();
function buildCrcTable(): number[] {
const table: number[] = [];
for (let i = 0; i < 256; i++) {
let c = i;
for (let j = 0; j < 8; j++) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
table.push(c >>> 0);
}
return table;
}
function crc32(data: Uint8Array): number {
let crc = 0xffffffff;
for (const byte of data) {
crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
}
return (crc ^ 0xffffffff) >>> 0;
}
function escapeXml(value: string): string {
return [...value]
.filter((char) => {
const code = char.charCodeAt(0);
return code === 9 || code === 10 || code === 13 || code >= 32;
})
.join("")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """);
}
function columnName(index: number): string {
let value = "";
let n = index + 1;
while (n > 0) {
const rem = (n - 1) % 26;
value = String.fromCharCode(65 + rem) + value;
n = Math.floor((n - 1) / 26);
}
return value;
}
function cellRef(rowIndex: number, colIndex: number): string {
return `${columnName(colIndex)}${rowIndex + 1}`;
}
function sheetRange(columnCount: number, rowCount: number): string {
if (columnCount === 0 || rowCount === 0) return "A1";
return `A1:${columnName(columnCount - 1)}${rowCount}`;
}
function normalizeSheetName(value?: string): string {
const invalidChars = new Set(["[", "]", ":", "*", "?", "/", "\\"]);
const name =
[...(value || "Sheet1")]
.map((char) => (invalidChars.has(char) ? " " : char))
.join("")
.trim() || "Sheet1";
return name.slice(0, 31);
}
function normalizeUniqueSheetNames(sheets: readonly XlsxWorksheetData[]): string[] {
const names: string[] = [];
sheets.forEach((sheet, index) => {
const base = normalizeSheetName(sheet.sheetName || `Sheet${index + 1}`);
let candidate = base;
let suffix = 2;
while (names.includes(candidate)) {
const suffixText = ` (${suffix})`;
candidate = `${base.slice(0, 31 - suffixText.length)}${suffixText}`;
suffix += 1;
}
names.push(candidate);
});
return names;
}
function estimateColumnWidths(columns: readonly string[], rows: readonly (readonly XlsxCellValue[])[]): number[] {
return columns.map((column, colIndex) => {
const values = rows.slice(0, 100).map((row) => row[colIndex]);
const maxLen = [column, ...values.map((value) => (value == null ? "" : String(value)))].map((value) => Math.min(value.length, 60)).reduce((max, length) => Math.max(max, length), 8);
return Math.max(10, Math.min(60, maxLen + 2));
});
}
function isNumericColumnType(columnType?: string): boolean {
const base = (columnType || "")
.trim()
.toLowerCase()
.split(/[\s([]/, 1)[0];
return new Set([
"bit",
"tinyint",
"smallint",
"mediumint",
"int",
"integer",
"bigint",
"int2",
"int4",
"int8",
"uint8",
"uint16",
"uint32",
"uint64",
"uint128",
"uint256",
"float",
"float4",
"float8",
"float32",
"float64",
"real",
"double",
"decimal",
"numeric",
"number",
"money",
"smallmoney",
]).has(base);
}
function safeExcelNumber(value: string): string | undefined {
const trimmed = value.trim();
if (!trimmed || !Number.isFinite(Number(trimmed))) return undefined;
const significantDigits = (trimmed.split(/[eE]/, 1)[0].match(/\d/g) || []).join("").replace(/^0+/, "").length;
return significantDigits <= 15 ? trimmed : undefined;
}
function cellXml(value: XlsxCellValue, rowIndex: number, colIndex: number, style?: number, columnType?: string): string {
const ref = cellRef(rowIndex, colIndex);
const styleAttr = style == null ? "" : ` s="${style}"`;
if (value == null) return `