eljson
Version:
## 介绍
65 lines (64 loc) • 2.4 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.excelToObj = void 0;
const consola_1 = __importDefault(require("consola"));
const utils_1 = require("./utils");
const xlsx_1 = require("xlsx");
const excelToObj = (path, sheetName) => {
const xlsxData = (0, xlsx_1.readFile)(path);
const sheet_name_list = xlsxData.SheetNames;
// 检查工作表名称是否存在
const hasValue = sheet_name_list.find((name) => name == sheetName);
if (!hasValue) {
let csheetName = sheetName == '' ? '空' : sheetName;
consola_1.default.fatal(`工作表名称(${csheetName})不存在🥺😫`);
return {};
}
else {
// 转化 sheet 数据为行、列、当前值的数组
let sheetArray = [];
for (let i = 0; i < sheet_name_list.length; i++) {
const y = sheet_name_list[i];
if (y == sheetName) {
const worksheet = xlsxData.Sheets[y];
for (const z in worksheet) {
if (z[0] == '!') {
continue;
}
let tt = 0;
for (let i = 0; i < z.length; i++) {
if (!isNaN(z[i])) {
tt = i;
break;
}
}
const col = z.substring(0, tt);
const row = parseInt(z.substring(tt), 10);
const value = worksheet[z].v;
sheetArray.push({
col,
row,
value: (0, utils_1.trimStr)(value)
});
}
break;
}
}
// 再次转化为每一行数据
let sheetObj = {};
for (let i = 0; i < sheetArray.length; i++) {
const curSheet = sheetArray[i];
const curRow = curSheet.row;
const curCol = curSheet.col;
const curVal = curSheet.value;
if (!sheetObj[curRow])
sheetObj[curRow] = {};
sheetObj[curRow][curCol] = curVal;
}
return sheetObj;
}
};
exports.excelToObj = excelToObj;