build-xlsx-from-rows.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. 'use strict'
  2. /**
  3. * 把页面导出的行数据写成 xlsx
  4. * ---------------------------
  5. * 为什么需要这一步:客户端的下载通道会把 >10 字节的文件卡在临时态
  6. * (.cn.cocorobo.teacher.XXXX),正式文件不落盘。所以不能依赖 handleExportData()
  7. * 写盘,改为把它本该写进去的行数据拿回来,由脚本自己生成 xlsx。
  8. *
  9. * 用法:node build-xlsx-from-rows.js <rows.json> <输出路径.xlsx>
  10. *
  11. * rows.json 结构(由 pblPanelRows 产出):
  12. * { className, courseTitle, rows: [[姓名,班级,课程,页码,题型,内容,时间], ...],
  13. * pageOutline: {"1": "第1页内容", ...} }
  14. */
  15. const fs = require('node:fs')
  16. const path = require('node:path')
  17. const HEADER = ['学生姓名', '学生班级', '所属课程', '提交对应页码', '题型', '作业内容', '提交时间']
  18. function esc (s) {
  19. return String(s == null ? '' : s)
  20. .replace(/&/g, '&amp;')
  21. .replace(/</g, '&lt;')
  22. .replace(/>/g, '&gt;')
  23. .replace(/"/g, '&quot;')
  24. // XML 1.0 不允许的控制字符
  25. .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
  26. }
  27. function colName (i) {
  28. let s = ''
  29. let n = i + 1
  30. while (n > 0) {
  31. const r = (n - 1) % 26
  32. s = String.fromCharCode(65 + r) + s
  33. n = Math.floor((n - 1) / 26)
  34. }
  35. return s
  36. }
  37. function sheetXml (rows, widths) {
  38. const cols = widths
  39. ? `<cols>${widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join('')}</cols>`
  40. : ''
  41. const body = rows.map((row, r) => {
  42. const cells = row.map((v, c) => {
  43. const ref = colName(c) + (r + 1)
  44. const val = esc(v)
  45. // 数字列保持数值,其余一律内联字符串(保留换行)
  46. if (typeof v === 'number' && Number.isFinite(v)) {
  47. return `<c r="${ref}"><v>${v}</v></c>`
  48. }
  49. return `<c r="${ref}" t="str"><v xml:space="preserve">${val}</v></c>`
  50. }).join('')
  51. return `<row r="${r + 1}" xml:space="preserve">${cells}</row>`
  52. }).join('')
  53. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  54. <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData>${cols}</worksheet>`
  55. }
  56. /** 极简 zip 写入(只写 stored,不压缩;xlsx 不要求压缩) */
  57. function crc32 (buf) {
  58. let c = ~0
  59. for (let i = 0; i < buf.length; i++) {
  60. c ^= buf[i]
  61. for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1))
  62. }
  63. return ~c >>> 0
  64. }
  65. function zip (files) {
  66. const local = []
  67. const central = []
  68. let offset = 0
  69. for (const [name, content] of files) {
  70. const nameBuf = Buffer.from(name, 'utf8')
  71. const data = Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8')
  72. const crc = crc32(data)
  73. const lh = Buffer.alloc(30)
  74. lh.writeUInt32LE(0x04034b50, 0)
  75. lh.writeUInt16LE(20, 4)
  76. lh.writeUInt16LE(0x0800, 6)
  77. lh.writeUInt16LE(0, 8)
  78. lh.writeUInt16LE(0, 10)
  79. lh.writeUInt16LE(0, 12)
  80. lh.writeUInt32LE(crc, 14)
  81. lh.writeUInt32LE(data.length, 18)
  82. lh.writeUInt32LE(data.length, 22)
  83. lh.writeUInt16LE(nameBuf.length, 26)
  84. lh.writeUInt16LE(0, 28)
  85. local.push(lh, nameBuf, data)
  86. const ch = Buffer.alloc(46)
  87. ch.writeUInt32LE(0x02014b50, 0)
  88. ch.writeUInt16LE(20, 4)
  89. ch.writeUInt16LE(20, 6)
  90. ch.writeUInt16LE(0x0800, 8)
  91. ch.writeUInt16LE(0, 10)
  92. ch.writeUInt16LE(0, 12)
  93. ch.writeUInt16LE(0, 14)
  94. ch.writeUInt32LE(crc, 16)
  95. ch.writeUInt32LE(data.length, 20)
  96. ch.writeUInt32LE(data.length, 24)
  97. ch.writeUInt16LE(nameBuf.length, 28)
  98. ch.writeUInt16LE(0, 30)
  99. ch.writeUInt16LE(0, 32)
  100. ch.writeUInt16LE(0, 34)
  101. ch.writeUInt16LE(0, 36)
  102. ch.writeUInt32LE(0, 38)
  103. ch.writeUInt32LE(offset, 42)
  104. central.push(ch, nameBuf)
  105. offset += 30 + nameBuf.length + data.length
  106. }
  107. const centralBuf = Buffer.concat(central)
  108. const end = Buffer.alloc(22)
  109. end.writeUInt32LE(0x06054b50, 0)
  110. end.writeUInt16LE(files.length, 8)
  111. end.writeUInt16LE(files.length, 10)
  112. end.writeUInt32LE(centralBuf.length, 12)
  113. end.writeUInt32LE(offset, 16)
  114. return Buffer.concat([...local, centralBuf, end])
  115. }
  116. function buildXlsx (payload, outPath) {
  117. const rows = payload.rows || []
  118. const worksRows = [HEADER, ...rows.map((r) => r.map((v) => (v == null ? '' : String(v))))]
  119. const outline = payload.pageOutline || {}
  120. const pageText = Object.keys(outline)
  121. .sort((a, b) => Number(a) - Number(b))
  122. .map((k) => `第${k}页的内容:${outline[k]}`)
  123. .join('\n')
  124. const infoRows = [
  125. ['课程标题', payload.courseTitle || ''],
  126. ['课程内容', pageText]
  127. ]
  128. const files = [
  129. ['[Content_Types].xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  130. <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/worksheets/sheet2.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`],
  131. ['_rels/.rels', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  132. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`],
  133. ['xl/workbook.xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  134. <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="作业数据" sheetId="1" r:id="rId1"/><sheet name="课程信息" sheetId="2" r:id="rId2"/></sheets></workbook>`],
  135. ['xl/_rels/workbook.xml.rels', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  136. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet2.xml"/></Relationships>`],
  137. ['xl/worksheets/sheet1.xml', sheetXml(worksRows, [14, 14, 30, 12, 14, 60, 22])],
  138. ['xl/worksheets/sheet2.xml', sheetXml(infoRows, [14, 100])]
  139. ]
  140. fs.mkdirSync(path.dirname(outPath), { recursive: true })
  141. fs.writeFileSync(outPath, zip(files))
  142. return outPath
  143. }
  144. module.exports = { buildXlsx }
  145. if (require.main === module) {
  146. const [, , rowsFile, outPath] = process.argv
  147. if (!rowsFile || !outPath) {
  148. console.error('用法:node build-xlsx-from-rows.js <rows.json> <输出.xlsx>')
  149. process.exit(2)
  150. }
  151. const payload = JSON.parse(fs.readFileSync(rowsFile, 'utf8'))
  152. if (!Array.isArray(payload.rows) || !payload.rows.length) {
  153. console.error('rows.json 里没有 rows')
  154. process.exit(1)
  155. }
  156. const p = buildXlsx(payload, outPath)
  157. console.log(JSON.stringify({ ok: true, file: p, rows: payload.rows.length }))
  158. }