Files
khb_microservices/packages/accounting_automation/scripts/xlsx-read.mjs

53 lines
2.6 KiB
JavaScript

import fs from "fs";
import zlib from "zlib";
export function unzip(buf) {
let e = buf.length - 22;
while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--;
const n = buf.readUInt16LE(e + 10), cdOff = buf.readUInt32LE(e + 16);
const files = {};
let p = cdOff;
for (let i = 0; i < n; i++) {
const method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), nlen = buf.readUInt16LE(p + 28), xlen = buf.readUInt16LE(p + 30), clen = buf.readUInt16LE(p + 32), lh = buf.readUInt32LE(p + 42);
const name = buf.toString("utf8", p + 46, p + 46 + nlen);
const ln = buf.readUInt16LE(lh + 26), lx = buf.readUInt16LE(lh + 28);
const data = buf.subarray(lh + 30 + ln + lx, lh + 30 + ln + lx + csize);
files[name] = method === 0 ? data : zlib.inflateRawSync(data);
p += 46 + nlen + xlen + clen;
}
return files;
}
const dec = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, c) => String.fromCharCode(+c)).replace(/&amp;/g, "&");
export function readXlsx(path) {
const f = unzip(fs.readFileSync(path));
const wb = f["xl/workbook.xml"].toString("utf8");
const rels = f["xl/_rels/workbook.xml.rels"].toString("utf8");
const ss = [];
if (f["xl/sharedStrings.xml"]) {
for (const m of f["xl/sharedStrings.xml"].toString("utf8").matchAll(/<si>([\s\S]*?)<\/si>/g)) {
ss.push(dec([...m[1].matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map((x) => x[1]).join("")));
}
}
const sheets = [];
for (const m of wb.matchAll(/<sheet [^>]*name="([^"]*)"[^>]*r:id="([^"]*)"/g)) {
const rid = m[2];
const rel = new RegExp(`<Relationship [^>]*Id="${rid}"[^>]*>`).exec(rels)[0];
const target = /Target="([^"]*)"/.exec(rel)[1].replace(/^\/?(xl\/)?/, "xl/");
const xml = f[target].toString("utf8");
const rows = [];
for (const r of xml.matchAll(/<row [^>]*?r="(\d+)"[^>]*?(?:\/>|>([\s\S]*?)<\/row>)/g)) {
const cells = {};
for (const c of (r[2] ?? "").matchAll(/<c ([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
const ref = /r="([A-Z]+)\d+"/.exec(c[1])[1];
const t = /t="(\w+)"/.exec(c[1])?.[1];
const v = /<v>([\s\S]*?)<\/v>/.exec(c[2] ?? "")?.[1];
const is = /<is>[\s\S]*?<t[^>]*>([\s\S]*?)<\/t>/.exec(c[2] ?? "")?.[1];
let val = v === undefined ? (is === undefined ? null : dec(is)) : t === "s" ? ss[+v] : t === "str" || t === "inlineStr" ? dec(v) : t === "b" ? v === "1" : +v;
if (val !== null) cells[ref] = val;
}
rows.push({ n: +r[1], cells });
}
sheets.push({ name: dec(m[1]), rows });
}
return sheets;
}