xlsx-read.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. 'use strict'
  2. /**
  3. * xlsx 读取器(零依赖,只用 node 自带的 zlib)
  4. * --------------------------------------------
  5. * 为什么不用现成的读表工具:平台的导出表里有大量**多行单元格**
  6. * (选择题的标准答案+学生作答就是一大段带换行的文本)。
  7. * cocorobo_office 的 read 会把这种单元格读成空字符串,数据直接没了。
  8. * 所以教学数据这类文件必须走这里,读原始 XML。
  9. *
  10. * 支持:workbook 多 sheet、内联字符串(t="str" / t="inlineStr")、
  11. * sharedStrings、数字、布尔、日期序列号(按给定格式转字符串)。
  12. * 不支持:公式求值(取缓存值)、图表、宏。
  13. */
  14. const fs = require('node:fs')
  15. const zlib = require('node:zlib')
  16. const SIG_CENTRAL = Buffer.from([0x50, 0x4b, 0x01, 0x02])
  17. const SIG_LOCAL = Buffer.from([0x50, 0x4b, 0x03, 0x04])
  18. /** 读 zip 里的所有文件(只处理 stored / deflate,xlsx 只会用这两种) */
  19. function unzip (buf) {
  20. const files = new Map()
  21. let pos = 0
  22. while ((pos = buf.indexOf(SIG_LOCAL, pos)) !== -1) {
  23. const method = buf.readUInt16LE(pos + 8)
  24. const compSize = buf.readUInt32LE(pos + 18)
  25. const nameLen = buf.readUInt16LE(pos + 26)
  26. const extraLen = buf.readUInt16LE(pos + 28)
  27. const name = buf.slice(pos + 30, pos + 30 + nameLen).toString('utf8')
  28. const dataStart = pos + 30 + nameLen + extraLen
  29. // 有的工具写 size=0 但在流里带数据标记,用 central directory 兜底
  30. let size = compSize
  31. if (size === 0) {
  32. const cd = buf.indexOf(SIG_CENTRAL)
  33. if (cd !== -1) size = buf.readUInt32LE(cd + 20)
  34. }
  35. const raw = buf.slice(dataStart, dataStart + size)
  36. let data
  37. if (method === 0) data = raw
  38. else if (method === 8) data = zlib.inflateRawSync(raw)
  39. else { pos = dataStart + size; continue }
  40. files.set(name, data)
  41. pos = dataStart + size
  42. }
  43. return files
  44. }
  45. function decodeXmlText (s) {
  46. return s
  47. .replace(/&lt;/g, '<')
  48. .replace(/&gt;/g, '>')
  49. .replace(/&quot;/g, '"')
  50. .replace(/&apos;/g, "'")
  51. .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
  52. .replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
  53. .replace(/&amp;/g, '&')
  54. }
  55. /** 把一行 XML 里的 cell 解析成 列号→值 */
  56. function parseRow (rowXml, shared, inlineStr) {
  57. const cells = {}
  58. const cellRe = /<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g
  59. let m
  60. while ((m = cellRe.exec(rowXml))) {
  61. const attrs = m[1] || ''
  62. const inner = m[2] || ''
  63. const ref = (attrs.match(/\br="([A-Z]+)\d+"/) || [])[1]
  64. if (!ref) continue
  65. const col = colIndex(ref)
  66. const type = (attrs.match(/\bt="([^"]+)"/) || [])[1] || ''
  67. let value = ''
  68. if (type === 'inlineStr') {
  69. value = [...inner.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)].map((x) => decodeXmlText(x[1])).join('')
  70. } else {
  71. const v = (inner.match(/<v\b[^>]*>([\s\S]*?)<\/v>/) || [])[1]
  72. if (v === undefined) continue
  73. if (type === 's') value = shared[Number(v)] ?? ''
  74. else if (type === 'str') value = decodeXmlText(v)
  75. else if (type === 'b') value = v === '1'
  76. else value = decodeXmlText(v)
  77. }
  78. // 富文本:<is><r><t>..</t></r><r><t>..</t></r></is>
  79. if (typeof value === 'string' && value.includes('<t')) {
  80. value = [...value.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)].map((x) => x[1]).join('')
  81. }
  82. cells[col] = value
  83. }
  84. return cells
  85. }
  86. function colIndex (letters) {
  87. let n = 0
  88. for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64)
  89. return n - 1
  90. }
  91. /**
  92. * @param {string} file 绝对路径
  93. * @returns {{sheets: Array<{name: string, rows: string[][]}>}}
  94. */
  95. function readXlsx (file) {
  96. const buf = fs.readFileSync(file)
  97. const files = unzip(buf)
  98. const get = (name) => {
  99. const d = files.get(name)
  100. return d ? d.toString('utf8') : ''
  101. }
  102. // sharedStrings
  103. const shared = []
  104. const ss = get('xl/sharedStrings.xml')
  105. if (ss) {
  106. for (const m of ss.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>/g)) {
  107. const parts = [...m[1].matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)].map((x) => decodeXmlText(x[1]))
  108. shared.push(parts.join(''))
  109. }
  110. }
  111. // workbook.xml 的 sheet 顺序 + rId
  112. const wb = get('xl/workbook.xml')
  113. const rels = get('xl/_rels/workbook.xml.rels')
  114. const relMap = new Map()
  115. for (const m of rels.matchAll(/<Relationship\b[^>]*>/g)) {
  116. const id = (m[0].match(/Id="([^"]+)"/) || [])[1]
  117. const target = (m[0].match(/Target="([^"]+)"/) || [])[1]
  118. if (id && target) relMap.set(id, target.replace(/^\/?xl\//, ''))
  119. }
  120. const sheets = []
  121. for (const m of wb.matchAll(/<sheet\b[^>]*>/g)) {
  122. const name = decodeXmlText((m[0].match(/name="([^"]*)"/) || [])[1] || '')
  123. const rid = (m[0].match(/r:id="([^"]+)"/) || [])[1]
  124. const target = relMap.get(rid) || ''
  125. const xml = get('xl/' + target)
  126. if (!xml) continue
  127. const rows = []
  128. for (const rm of xml.matchAll(/<row\b([^>]*)>([\s\S]*?)<\/row>/g)) {
  129. const cells = parseRow(rm[2], shared)
  130. const width = Math.max(0, ...Object.keys(cells).map(Number).map((n) => n + 1))
  131. const arr = []
  132. for (let i = 0; i < width; i++) {
  133. const v = cells[i]
  134. arr.push(v === undefined ? '' : (typeof v === 'boolean' ? String(v) : String(v)))
  135. }
  136. rows.push(arr)
  137. }
  138. sheets.push({ name, rows })
  139. }
  140. return { sheets }
  141. }
  142. module.exports = { readXlsx }
  143. if (require.main === module) {
  144. const target = process.argv[2]
  145. if (!target) {
  146. console.error('用法:node scripts/xlsx-read.js <文件.xlsx>')
  147. process.exit(2)
  148. }
  149. const { sheets } = readXlsx(target)
  150. for (const s of sheets) {
  151. console.log(`# sheet: ${s.name}(${s.rows.length} 行)`)
  152. for (const row of s.rows.slice(0, 5)) {
  153. console.log(' ' + row.map((c) => (c.length > 40 ? c.slice(0, 40) + '…' : c)).join(' | '))
  154. }
  155. if (s.rows.length > 5) console.log(` ……还有 ${s.rows.length - 5} 行`)
  156. }
  157. }