'use strict'; // 仅生成一个文本/数值工作表;用Node内置ZIP压缩,不执行公式或嵌入外部链接。 const {deflateRawSync}=require('node:zlib'); const crcTable=Uint32Array.from({length:256},(_,value)=>{for(let bit=0;bit<8;bit++)value=value&1?0xedb88320^(value>>>1):value>>>1;return value>>>0;}); function crc32(buffer){let crc=0xffffffff;for(const byte of buffer)crc=crcTable[(crc^byte)&255]^(crc>>>8);return (crc^0xffffffff)>>>0;} function xml(value){return [...String(value??'')].filter(char=>{const n=char.codePointAt(0);return n===9||n===10||n===13||n>=32&&n<=0xd7ff||n>=0xe000&&n<=0xfffd||n>=0x10000&&n<=0x10ffff;}).join('').slice(0,32767).replace(/[&<>"']/g,char=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[char]));} function zip(files){ const locals=[],directory=[];let offset=0; for(const [filename,value] of Object.entries(files)){ const name=Buffer.from(filename),data=Buffer.from(value),compressed=deflateRawSync(data),crc=crc32(data),local=Buffer.alloc(30),central=Buffer.alloc(46); local.writeUInt32LE(0x04034b50,0);local.writeUInt16LE(20,4);local.writeUInt16LE(0x800,6);local.writeUInt16LE(8,8);local.writeUInt16LE(33,12);local.writeUInt32LE(crc,14);local.writeUInt32LE(compressed.length,18);local.writeUInt32LE(data.length,22);local.writeUInt16LE(name.length,26); central.writeUInt32LE(0x02014b50,0);central.writeUInt16LE(20,4);central.writeUInt16LE(20,6);central.writeUInt16LE(0x800,8);central.writeUInt16LE(8,10);central.writeUInt16LE(33,14);central.writeUInt32LE(crc,16);central.writeUInt32LE(compressed.length,20);central.writeUInt32LE(data.length,24);central.writeUInt16LE(name.length,28);central.writeUInt32LE(offset,42); locals.push(local,name,compressed);directory.push(central,name);offset+=local.length+name.length+compressed.length; } const index=Buffer.concat(directory),end=Buffer.alloc(22),count=Object.keys(files).length;end.writeUInt32LE(0x06054b50,0);end.writeUInt16LE(count,8);end.writeUInt16LE(count,10);end.writeUInt32LE(index.length,12);end.writeUInt32LE(offset,16);return Buffer.concat([...locals,index,end]); } function workbook(rows,{sheetName='库存流水',widths=[8,14,16,18,20,48,18,24,30],numericColumns=[0,3]}={}){ if(rows.length>1048576)throw new Error('超过Excel单表行数上限,请缩小筛选范围'); const column=index=>{let name='';for(index++;index;index=Math.floor((index-1)/26))name=String.fromCharCode(65+(index-1)%26)+name;return name;}; const cells=rows.map((row,index)=>`${row.map((value,col)=>{const ref=column(col)+(index+1);if(index&&numericColumns.includes(col)){if(typeof value!=='number'||!Number.isFinite(value))throw new Error('导出数值无效');return `${value}`;}return `${xml(value)}`;}).join('')}`).join(''); const sheet=`${widths.map((width,index)=>``).join('')}${cells}`; return zip({ '[Content_Types].xml':'', '_rels/.rels':'', 'xl/workbook.xml':``, 'xl/_rels/workbook.xml.rels':'', 'xl/styles.xml':'', 'xl/worksheets/sheet1.xml':sheet }); } module.exports={workbook};