'use strict' /** * xlsx 读取器(零依赖,只用 node 自带的 zlib) * -------------------------------------------- * 为什么不用现成的读表工具:平台的导出表里有大量**多行单元格** * (选择题的标准答案+学生作答就是一大段带换行的文本)。 * cocorobo_office 的 read 会把这种单元格读成空字符串,数据直接没了。 * 所以教学数据这类文件必须走这里,读原始 XML。 * * 支持:workbook 多 sheet、内联字符串(t="str" / t="inlineStr")、 * sharedStrings、数字、布尔、日期序列号(按给定格式转字符串)。 * 不支持:公式求值(取缓存值)、图表、宏。 */ const fs = require('node:fs') const zlib = require('node:zlib') const SIG_CENTRAL = Buffer.from([0x50, 0x4b, 0x01, 0x02]) const SIG_LOCAL = Buffer.from([0x50, 0x4b, 0x03, 0x04]) /** 读 zip 里的所有文件(只处理 stored / deflate,xlsx 只会用这两种) */ function unzip (buf) { const files = new Map() let pos = 0 while ((pos = buf.indexOf(SIG_LOCAL, pos)) !== -1) { 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.slice(pos + 30, pos + 30 + nameLen).toString('utf8') const dataStart = pos + 30 + nameLen + extraLen // 有的工具写 size=0 但在流里带数据标记,用 central directory 兜底 let size = compSize if (size === 0) { const cd = buf.indexOf(SIG_CENTRAL) if (cd !== -1) size = buf.readUInt32LE(cd + 20) } const raw = buf.slice(dataStart, dataStart + size) let data if (method === 0) data = raw else if (method === 8) data = zlib.inflateRawSync(raw) else { pos = dataStart + size; continue } files.set(name, data) pos = dataStart + size } return files } function decodeXmlText (s) { return s .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))) .replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16))) .replace(/&/g, '&') } /** 把一行 XML 里的 cell 解析成 列号→值 */ function parseRow (rowXml, shared, inlineStr) { const cells = {} const cellRe = /]*?)(?:\/>|>([\s\S]*?)<\/c>)/g let m while ((m = cellRe.exec(rowXml))) { const attrs = m[1] || '' const inner = m[2] || '' const ref = (attrs.match(/\br="([A-Z]+)\d+"/) || [])[1] if (!ref) continue const col = colIndex(ref) const type = (attrs.match(/\bt="([^"]+)"/) || [])[1] || '' let value = '' if (type === 'inlineStr') { value = [...inner.matchAll(/]*>([\s\S]*?)<\/t>/g)].map((x) => decodeXmlText(x[1])).join('') } else { const v = (inner.match(/]*>([\s\S]*?)<\/v>/) || [])[1] if (v === undefined) continue if (type === 's') value = shared[Number(v)] ?? '' else if (type === 'str') value = decodeXmlText(v) else if (type === 'b') value = v === '1' else value = decodeXmlText(v) } // 富文本:.... if (typeof value === 'string' && value.includes(']*>([\s\S]*?)<\/t>/g)].map((x) => x[1]).join('') } cells[col] = value } return cells } function colIndex (letters) { let n = 0 for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64) return n - 1 } /** * @param {string} file 绝对路径 * @returns {{sheets: Array<{name: string, rows: string[][]}>}} */ function readXlsx (file) { const buf = fs.readFileSync(file) const files = unzip(buf) const get = (name) => { const d = files.get(name) return d ? d.toString('utf8') : '' } // sharedStrings const shared = [] const ss = get('xl/sharedStrings.xml') if (ss) { for (const m of ss.matchAll(/]*>([\s\S]*?)<\/si>/g)) { const parts = [...m[1].matchAll(/]*>([\s\S]*?)<\/t>/g)].map((x) => decodeXmlText(x[1])) shared.push(parts.join('')) } } // workbook.xml 的 sheet 顺序 + rId const wb = get('xl/workbook.xml') const rels = get('xl/_rels/workbook.xml.rels') const relMap = new Map() for (const m of rels.matchAll(/]*>/g)) { const id = (m[0].match(/Id="([^"]+)"/) || [])[1] const target = (m[0].match(/Target="([^"]+)"/) || [])[1] if (id && target) relMap.set(id, target.replace(/^\/?xl\//, '')) } const sheets = [] for (const m of wb.matchAll(/]*>/g)) { const name = decodeXmlText((m[0].match(/name="([^"]*)"/) || [])[1] || '') const rid = (m[0].match(/r:id="([^"]+)"/) || [])[1] const target = relMap.get(rid) || '' const xml = get('xl/' + target) if (!xml) continue const rows = [] for (const rm of xml.matchAll(/]*)>([\s\S]*?)<\/row>/g)) { const cells = parseRow(rm[2], shared) const width = Math.max(0, ...Object.keys(cells).map(Number).map((n) => n + 1)) const arr = [] for (let i = 0; i < width; i++) { const v = cells[i] arr.push(v === undefined ? '' : (typeof v === 'boolean' ? String(v) : String(v))) } rows.push(arr) } sheets.push({ name, rows }) } return { sheets } } module.exports = { readXlsx } if (require.main === module) { const target = process.argv[2] if (!target) { console.error('用法:node scripts/xlsx-read.js <文件.xlsx>') process.exit(2) } const { sheets } = readXlsx(target) for (const s of sheets) { console.log(`# sheet: ${s.name}(${s.rows.length} 行)`) for (const row of s.rows.slice(0, 5)) { console.log(' ' + row.map((c) => (c.length > 40 ? c.slice(0, 40) + '…' : c)).join(' | ')) } if (s.rows.length > 5) console.log(` ……还有 ${s.rows.length - 5} 行`) } }