xlsx-extractor
Version:
Extract the colums/rows from XLSX file.
92 lines (91 loc) • 3.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const xlsx_util_1 = require("./xlsx-util");
/**
* Get a sheet.
* @param zip Extract data of XLSX (Zip) file.
* @param index Index of sheet. Range of from 1 to XlsxExtractor.count.
* @returns Sheet.
*/
const getSheet = async (zip, index) => {
const data = await xlsx_util_1.getSheetData(zip, index);
const cells = xlsx_util_1.getCells(data.sheet.worksheet.sheetData[0].row);
const size = xlsx_util_1.getSheetSize(data.sheet, cells);
const rows = size.row.max - size.row.min + 1;
const cols = size.col.max - size.col.min + 1;
const sheet = xlsx_util_1.createEmptyCells(rows, cols);
const strings = !data.strings ? {} : data.strings.sst.si;
cells.forEach((cell) => {
let value = cell.value;
if (cell.type === 's') {
const index = parseInt(value, 10);
value = xlsx_util_1.valueFromStrings(strings[index]);
}
let row = cell.row - size.row.min;
row = row >= 0 ? row : size.row.min;
let col = cell.col - size.col.min;
col = col >= 0 ? col : size.col.min;
sheet[row][col] = value;
});
return {
id: index,
name: data.name,
cells: sheet
};
};
/**
* Extract a specified range of sheets.
* Using `ZipObject` efficiently handles counting and getting multiple sheets without opening the file every time.
* @param filePath Path of XMLS file.
* @param range Range of sheets. The default is all.
* @returns Sheets.
*/
const extractRangeInner = async (zip, begin, end) => {
const sheets = [];
const count = xlsx_util_1.getSheetInnerCount(zip);
if (begin < 1 || count < end) {
throw new Error(`Index out of range. begin = ${begin} (min = 1), end = ${end} (max = ${count})`);
}
for (let i = begin; i <= end; ++i) {
sheets.push(await getSheet(zip, i));
}
return sheets;
};
/**
* Extract and get an index of sheets.
* @param filePath Path of XMLS file.
* @returns Index of sheets (1 - Sheet count).
* @throws Failed to expand the XLSX file.
*/
exports.getSheetCount = (filePath) => {
// Hide structure in ZIP file to "Inner" side
return xlsx_util_1.getSheetInnerCount(xlsx_util_1.unzip(filePath));
};
/**
* Extract a sheet.
* @param filePath Path of XMLS file.
* @param index Index of sheet. Range of from 1 to XlsxExtractor.count.
* @return Sheet.
*/
exports.extract = (filePath, index) => {
return getSheet(xlsx_util_1.unzip(filePath), index);
};
/**
* Extract and get a specified range of sheets.
* @param filePath Path of XMLS file.
* @param begin Begin index (1 - Sheet count).
* @param end End index (1 - Sheet count).
* @returns Sheets.
*/
exports.extractRange = async (filePath, begin, end) => {
return extractRangeInner(xlsx_util_1.unzip(filePath), begin, end);
};
/**
* Extract and get specified all of sheets.
* @param filePath Path of XMLS file.
* @returns Sheets.
*/
exports.extractAll = (filePath) => {
const zip = xlsx_util_1.unzip(filePath);
return extractRangeInner(zip, 1, xlsx_util_1.getSheetInnerCount(zip));
};