// 小型纯文本 SpreadsheetML 导出;inlineStr 避免公式执行与号码精度变化。
const encoder = new TextEncoder();
const xml = (value: string) => value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
function crc32(bytes: Uint8Array) {
let crc = 0xffffffff;
for (const byte of bytes) { crc ^= byte; for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0); }
return (crc ^ 0xffffffff) >>> 0;
}
function zip(files: [string, string][]) {
const chunks: Uint8Array[] = [], central: Uint8Array[] = [];
let offset = 0;
for (const [path, content] of files) {
const name = encoder.encode(path), bytes = encoder.encode(content), crc = crc32(bytes);
const header = new Uint8Array(30 + name.length), h = new DataView(header.buffer);
h.setUint32(0, 0x04034b50, true); h.setUint16(4, 20, true); h.setUint16(6, 0x800, true); h.setUint32(14, crc, true); h.setUint32(18, bytes.length, true); h.setUint32(22, bytes.length, true); h.setUint16(26, name.length, true); header.set(name, 30);
const directory = new Uint8Array(46 + name.length), d = new DataView(directory.buffer);
d.setUint32(0, 0x02014b50, true); d.setUint16(4, 20, true); d.setUint16(6, 20, true); d.setUint16(8, 0x800, true); d.setUint32(16, crc, true); d.setUint32(20, bytes.length, true); d.setUint32(24, bytes.length, true); d.setUint16(28, name.length, true); d.setUint32(42, offset, true); directory.set(name, 46);
chunks.push(header, bytes); central.push(directory); offset += header.length + bytes.length;
}
const size = central.reduce((sum, bytes) => sum + bytes.length, 0), footer = new Uint8Array(22), f = new DataView(footer.buffer);
f.setUint32(0, 0x06054b50, true); f.setUint16(8, files.length, true); f.setUint16(10, files.length, true); f.setUint32(12, size, true); f.setUint32(16, offset, true);
const result = new Uint8Array(offset + size + footer.length); let cursor = 0;
for (const chunk of [...chunks, ...central, footer]) { result.set(chunk, cursor); cursor += chunk.length; }
return result;
}
function column(index: number): string { return index < 26 ? String.fromCharCode(65 + index) : column(Math.floor(index / 26) - 1) + column(index % 26); }
export function textWorkbook(rows: string[][], sheetName = "激活码清单") {
const width = Math.max(1, ...rows.map((row) => row.length));
const sheet = `${Array.from({ length: width }, (_, i) => ``).join("")}${rows.map((row, i) => `${row.map((cell, j) => `${xml(cell)}`).join("")}
`).join("")}`;
return zip([
["[Content_Types].xml", ''],
["_rels/.rels", ''],
["xl/workbook.xml", ``],
["xl/_rels/workbook.xml.rels", ''],
["xl/worksheets/sheet1.xml", sheet],
]);
}