excel-json-cli1
Version:
用于把表格数据导成json数据,可支持json、ts和js,或者,用于把json数据导成表格数据,可支持json、ts和js。
180 lines (179 loc) • 9.31 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.excel2json = void 0;
const node_xlsx_1 = __importDefault(require("node-xlsx"));
const fs = __importStar(require("fs-extra"));
const chalk_1 = __importDefault(require("chalk"));
const constants_1 = require("../constants");
const prettier_1 = require("prettier");
const prettierrc_1 = require("../constants/prettierrc");
const stringToObject = (jsonData, str, value) => {
const keys = str.split('.');
keys === null || keys === void 0 ? void 0 : keys.reduce((accumulator, currentValue, currentIndex) => {
var _a;
const val = keys.length - 1 === currentIndex ? value : (_a = jsonData[currentValue]) !== null && _a !== void 0 ? _a : {};
return accumulator ? accumulator[currentValue] = val : jsonData[currentValue] = val;
}, null);
};
const dataToJson = (data, { rule, key: isKey, notMatchFilename, isSoToMo }) => {
/**
* excel读取规制解析,文件名为第一行(小写字母-大写字母 或 整个单元格内容)
* rule 0:[4,15]表示第一列为语言key,第五列到第十九列为语言包数据,默认为0:[1,整行数据长度]
*/
const [key, interval] = rule.split(':');
const intervals = interval ? JSON.parse(interval) : [1];
// 记录文件导成json的数据
let jsonData = {};
data.forEach(sheet => {
// 记录每个标签页的语言key
let fileKeys = [];
sheet.data.forEach((row, rowi) => {
var _a, _b, _c;
if (rowi === 0) {
// 按第一行生成语言对象key
row.splice(intervals[0], (_a = intervals[1]) !== null && _a !== void 0 ? _a : row.length).forEach((col, coli) => {
if (notMatchFilename) { // 记录语言key
fileKeys.push(col);
}
else {
fileKeys.push(String(col).match(/[a-z]+-[A-Z]+/g) ? col.match(/[a-z]+-[A-Z]+/g)[0] : col);
}
jsonData[fileKeys[coli]] = {}; // 设置语言对象key
});
}
else {
// 将第一行以下的数据生成语言json对象
if (isKey) {
const data = row.splice(intervals[0], (_b = intervals[1]) !== null && _b !== void 0 ? _b : row.length);
fileKeys.forEach((filekey, i) => {
if (!(data[i] === '' || data[i] === null || data[i] === undefined)) {
console.log(chalk_1.default.green(`${sheet.name} | ${filekey} | ${row[key]} | ${data[i]}`)); // 打印数据日志
if (isSoToMo && (key === null || key === void 0 ? void 0 : key.includes('.'))) {
stringToObject(jsonData[filekey], key, data[i]);
}
else {
jsonData[filekey][row[key]] = data[i];
}
}
});
}
else {
row.splice(intervals[0], (_c = intervals[1]) !== null && _c !== void 0 ? _c : row.length).forEach((col, coli) => {
var _a;
if (!fileKeys[coli] || !row[key])
return; // 没有文件key 或 数据key,跳过该列
if (!(col === '' || col === null || col === undefined)) {
console.log(chalk_1.default.green(`${sheet.name} | ${fileKeys[coli]} | ${row[key]} | ${col}`)); // 打印数据日志
if (isSoToMo && ((_a = row[key]) === null || _a === void 0 ? void 0 : _a.includes('.'))) {
stringToObject(jsonData[fileKeys[coli]], row[key], col);
}
else {
jsonData[fileKeys[coli]][row[key]] = col; // 设置每行数据到对应语言对象
}
}
});
}
}
});
});
return jsonData;
};
const writeFile = (jsonData, output, add) => {
// 获取输出路径及文件类型,默认为单前文件夹ts文件
const [path, fileOrSuffix] = output.split('**');
const [filename, suffix] = fileOrSuffix.split('.');
Object.keys(jsonData).forEach(key => {
console.log('正在写入文件:', path + key + fileOrSuffix);
let old = {};
// 增量获取源文件数据
if (add) {
try {
const fileData = fs.readFileSync(path + key + fileOrSuffix, { flag: 'r', encoding: 'utf-8' }).replace(/\;/g, '');
old = constants_1.isExportType.includes(suffix) ? eval('(' + fileData.split('export default ')[1] + ')') : JSON.parse(fileData);
}
catch (error) {
console.error(chalk_1.default.red('不存在源文件:', path + key + fileOrSuffix, ',改文件只有单前文档数据'));
}
}
// 格式化json数据
const data = (constants_1.isExportType.includes(suffix) ? 'export default ' : '') + JSON.stringify(Object.assign(Object.assign({}, old), jsonData[key]), undefined, ' ');
// 查看文件夹是否存在
fs.stat(path + key, (_, stats) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
if (!stats && filename) {
// 不存在创建文件夹
fs.mkdir(path + key, { recursive: true }, err => {
var _a;
if (err) {
console.error(chalk_1.default.red(err));
}
else {
// 文件写入
fs.writeFile(path + key + fileOrSuffix, (0, prettier_1.format)(data, Object.assign({ parser: (_a = constants_1.typeToName[suffix]) !== null && _a !== void 0 ? _a : 'typescript' }, prettierrc_1.prettierConfig)), (err) => {
if (err) {
console.error(chalk_1.default.red(err));
}
});
}
});
}
else {
// 文件写入
fs.writeFile(path + key + fileOrSuffix, (0, prettier_1.format)(data, Object.assign({ parser: (_a = constants_1.typeToName[suffix]) !== null && _a !== void 0 ? _a : 'typescript' }, prettierrc_1.prettierConfig)), (err) => {
if (err) {
console.error(chalk_1.default.red(err));
}
});
}
}));
});
};
function excel2json(options) {
// 读取文件
const workSheetsFromFile = node_xlsx_1.default.parse(options.input);
// 将数组转成json对象
const jsonData = dataToJson(workSheetsFromFile, {
rule: options.rule,
key: options.key,
notMatchFilename: options.notMatchFilename,
isSoToMo: options.multilevelObjectDeconstruct
});
// 将对象写入文件
writeFile(jsonData, options.output, options.add);
}
exports.excel2json = excel2json;