| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- 'use strict'
- /**
- * 把页面导出的行数据写成 xlsx
- * ---------------------------
- * 为什么需要这一步:客户端的下载通道会把 >10 字节的文件卡在临时态
- * (.cn.cocorobo.teacher.XXXX),正式文件不落盘。所以不能依赖 handleExportData()
- * 写盘,改为把它本该写进去的行数据拿回来,由脚本自己生成 xlsx。
- *
- * 用法:node build-xlsx-from-rows.js <rows.json> <输出路径.xlsx>
- *
- * rows.json 结构(由 pblPanelRows 产出):
- * { className, courseTitle, rows: [[姓名,班级,课程,页码,题型,内容,时间], ...],
- * pageOutline: {"1": "第1页内容", ...} }
- */
- const fs = require('node:fs')
- const path = require('node:path')
- const HEADER = ['学生姓名', '学生班级', '所属课程', '提交对应页码', '题型', '作业内容', '提交时间']
- function esc (s) {
- return String(s == null ? '' : s)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- // XML 1.0 不允许的控制字符
- .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
- }
- function colName (i) {
- let s = ''
- let n = i + 1
- while (n > 0) {
- const r = (n - 1) % 26
- s = String.fromCharCode(65 + r) + s
- n = Math.floor((n - 1) / 26)
- }
- return s
- }
- function sheetXml (rows, widths) {
- const cols = widths
- ? `<cols>${widths.map((w, i) => `<col min="${i + 1}" max="${i + 1}" width="${w}" customWidth="1"/>`).join('')}</cols>`
- : ''
- const body = rows.map((row, r) => {
- const cells = row.map((v, c) => {
- const ref = colName(c) + (r + 1)
- const val = esc(v)
- // 数字列保持数值,其余一律内联字符串(保留换行)
- if (typeof v === 'number' && Number.isFinite(v)) {
- return `<c r="${ref}"><v>${v}</v></c>`
- }
- return `<c r="${ref}" t="str"><v xml:space="preserve">${val}</v></c>`
- }).join('')
- return `<row r="${r + 1}" xml:space="preserve">${cells}</row>`
- }).join('')
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData>${cols}</worksheet>`
- }
- /** 极简 zip 写入(只写 stored,不压缩;xlsx 不要求压缩) */
- function crc32 (buf) {
- let c = ~0
- for (let i = 0; i < buf.length; i++) {
- c ^= buf[i]
- for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1))
- }
- return ~c >>> 0
- }
- function zip (files) {
- const local = []
- const central = []
- let offset = 0
- for (const [name, content] of files) {
- const nameBuf = Buffer.from(name, 'utf8')
- const data = Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8')
- const crc = crc32(data)
- const lh = Buffer.alloc(30)
- lh.writeUInt32LE(0x04034b50, 0)
- lh.writeUInt16LE(20, 4)
- lh.writeUInt16LE(0x0800, 6)
- lh.writeUInt16LE(0, 8)
- lh.writeUInt16LE(0, 10)
- lh.writeUInt16LE(0, 12)
- lh.writeUInt32LE(crc, 14)
- lh.writeUInt32LE(data.length, 18)
- lh.writeUInt32LE(data.length, 22)
- lh.writeUInt16LE(nameBuf.length, 26)
- lh.writeUInt16LE(0, 28)
- local.push(lh, nameBuf, data)
- const ch = Buffer.alloc(46)
- ch.writeUInt32LE(0x02014b50, 0)
- ch.writeUInt16LE(20, 4)
- ch.writeUInt16LE(20, 6)
- ch.writeUInt16LE(0x0800, 8)
- ch.writeUInt16LE(0, 10)
- ch.writeUInt16LE(0, 12)
- ch.writeUInt16LE(0, 14)
- ch.writeUInt32LE(crc, 16)
- ch.writeUInt32LE(data.length, 20)
- ch.writeUInt32LE(data.length, 24)
- ch.writeUInt16LE(nameBuf.length, 28)
- ch.writeUInt16LE(0, 30)
- ch.writeUInt16LE(0, 32)
- ch.writeUInt16LE(0, 34)
- ch.writeUInt16LE(0, 36)
- ch.writeUInt32LE(0, 38)
- ch.writeUInt32LE(offset, 42)
- central.push(ch, nameBuf)
- offset += 30 + nameBuf.length + data.length
- }
- const centralBuf = Buffer.concat(central)
- const end = Buffer.alloc(22)
- end.writeUInt32LE(0x06054b50, 0)
- end.writeUInt16LE(files.length, 8)
- end.writeUInt16LE(files.length, 10)
- end.writeUInt32LE(centralBuf.length, 12)
- end.writeUInt32LE(offset, 16)
- return Buffer.concat([...local, centralBuf, end])
- }
- function buildXlsx (payload, outPath) {
- const rows = payload.rows || []
- const worksRows = [HEADER, ...rows.map((r) => r.map((v) => (v == null ? '' : String(v))))]
- const outline = payload.pageOutline || {}
- const pageText = Object.keys(outline)
- .sort((a, b) => Number(a) - Number(b))
- .map((k) => `第${k}页的内容:${outline[k]}`)
- .join('\n')
- const infoRows = [
- ['课程标题', payload.courseTitle || ''],
- ['课程内容', pageText]
- ]
- const files = [
- ['[Content_Types].xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`],
- ['_rels/.rels', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`],
- ['xl/workbook.xml', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`],
- ['xl/_rels/workbook.xml.rels', `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <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>`],
- ['xl/worksheets/sheet1.xml', sheetXml(worksRows, [14, 14, 30, 12, 14, 60, 22])],
- ['xl/worksheets/sheet2.xml', sheetXml(infoRows, [14, 100])]
- ]
- fs.mkdirSync(path.dirname(outPath), { recursive: true })
- fs.writeFileSync(outPath, zip(files))
- return outPath
- }
- module.exports = { buildXlsx }
- if (require.main === module) {
- const [, , rowsFile, outPath] = process.argv
- if (!rowsFile || !outPath) {
- console.error('用法:node build-xlsx-from-rows.js <rows.json> <输出.xlsx>')
- process.exit(2)
- }
- const payload = JSON.parse(fs.readFileSync(rowsFile, 'utf8'))
- if (!Array.isArray(payload.rows) || !payload.rows.length) {
- console.error('rows.json 里没有 rows')
- process.exit(1)
- }
- const p = buildXlsx(payload, outPath)
- console.log(JSON.stringify({ ok: true, file: p, rows: payload.rows.length }))
- }
|