excel2json
Version:
excel2json
108 lines (107 loc) • 3.55 kB
JavaScript
;
/**
* @fileOverview cell converter
* @name cell
* @author Yuhei Aihara
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const zlib_1 = __importDefault(require("zlib"));
const lodash_1 = __importDefault(require("lodash"));
const libxmljs_1 = __importDefault(require("libxmljs"));
const logger_1 = __importDefault(require("../logger"));
const getCellCoord = (cell) => {
const cells = cell.match(/^(\D+)(\d+)$/) || [];
return {
cell,
column: cells[1],
row: parseInt(cells[2], 10),
};
};
exports.default = (cellNodes, strings, ns) => {
const result = [];
lodash_1.default.forEach(cellNodes, (cellNode) => {
const attr = cellNode.attr('r');
const coord = getCellCoord(attr ? attr.value() : '');
const type = cellNode.attr('t');
const id = cellNode.get('a:v', ns);
let value;
if (!id) {
// empty cell
return;
}
if (type && type.value() === 's') {
value = '';
lodash_1.default.forEach(strings.find(`//a:si[${parseInt(id.text(), 10) + 1}]//a:t`, ns), (t) => {
const elm = t.get('..');
if (elm && elm.name() !== 'rPh') {
value += t.text();
}
});
}
else {
value = id.text();
}
if (value === '') {
// empty cell
return;
}
result.push({
cell: coord.cell,
column: coord.column,
row: coord.row,
value,
});
});
return result;
};
if (require.main === module) {
process.on('message', async (data) => {
if (data.exit) {
process.exit();
}
const { ns, start, end } = data;
const unzip = {
strings: await new Promise((resolve) => {
zlib_1.default.unzip(Buffer.from(data.strings || '', 'base64'), (err, buf) => {
if (err) {
logger_1.default.error(err.stack);
if (process.send) {
process.send({ err });
}
return;
}
resolve(buf.toString());
});
}),
sheets: await new Promise((resolve) => {
zlib_1.default.unzip(Buffer.from(data.sheets || '', 'base64'), (err, buf) => {
if (err) {
logger_1.default.error(err.stack);
if (process.send) {
process.send({ err });
}
return;
}
resolve(buf.toString());
});
}),
};
const strings = libxmljs_1.default.parseXml(unzip.strings);
const sheets = libxmljs_1.default.parseXml(unzip.sheets);
const cellNodes = sheets.find('/a:worksheet/a:sheetData/a:row/a:c', ns);
const result = module.exports(cellNodes.slice(start, end), strings, ns);
if (process.send) {
process.send({ result });
}
});
process.on('uncaughtException', (err) => {
logger_1.default.error(err.stack);
if (process.send) {
process.send({ err });
}
process.exit(1);
});
}