| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- const fs = require('fs');
- const zlib = require('zlib');
- const buf = fs.readFileSync('docs/工作考核对象.docx');
- let pos = 0; const sig = 0x04034b50; let xml = null;
- while (pos < buf.length - 4) {
- if (buf.readUInt32LE(pos) !== sig) { pos++; continue; }
- const method = buf.readUInt16LE(pos + 8);
- const compSize = buf.readUInt32LE(pos + 18);
- const nameLen = buf.readUInt16LE(pos + 26);
- const extraLen = buf.readUInt16LE(pos + 28);
- const name = buf.toString('utf8', pos + 30, pos + 30 + nameLen);
- const dataStart = pos + 30 + nameLen + extraLen;
- const dataEnd = dataStart + compSize;
- if (name === 'word/document.xml') { let d = buf.slice(dataStart, dataEnd); if (method===8) d=zlib.inflateRawSync(d); xml = d.toString('utf8'); }
- pos = dataEnd;
- }
- function txt(s){let r='';const re=/<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g;let m;while((m=re.exec(s))!==null)r+=m[1];return r;}
- function findPara(s, from){let idx=s.indexOf('<w:p',from);while(idx!==-1){const c=s[idx+4];if(c===' '||c==='>'||c==='\t'||c==='\n')return idx;idx=s.indexOf('<w:p',idx+5);}return -1;}
- const blocks=[]; let i=0; const body=xml;
- while(i<body.length){
- const tIdx=body.indexOf('<w:tbl>',i);
- const pIdx=findPara(body,i);
- if(tIdx===-1&&pIdx===-1)break;
- if(pIdx!==-1&&(tIdx===-1||pIdx<tIdx)){const end=body.indexOf('</w:p>',pIdx);blocks.push({type:'p',text:txt(body.substring(pIdx,end+6))});i=end+6;}
- else {const end=body.indexOf('</w:tbl>',tIdx);blocks.push({type:'tbl',raw:body.substring(tIdx,end+8)});i=end+8;}
- }
- const out=[];let ti=0;
- for(let b=0;b<blocks.length;b++){
- if(blocks[b].type!=='tbl')continue;ti++;
- const pre=[];for(let k=b-1;k>=0;k--){if(blocks[k].type==='tbl')break;if(blocks[k].text.trim())pre.unshift(blocks[k].text);}
- out.push('\n=== TABLE '+ti+' ===');
- out.push('PRE: '+JSON.stringify(pre));
- const rowRe=/<w:tr[ >]([\s\S]*?)<\/w:tr>/g;let rm;
- while((rm=rowRe.exec(blocks[b].raw))!==null){
- const cellRe=/<w:tc[ >]([\s\S]*?)<\/w:tc>/g;let cm;const cells=[];
- while((cm=cellRe.exec(rm[1]))!==null)cells.push(txt(cm[1]).trim());
- out.push(cells.join(' | '));
- }
- }
- fs.writeFileSync('docs/_parsed.txt', out.join('\n'), 'utf8');
- console.log('tables:',ti);
|