t-comm
Version:
专业、稳定、纯粹的工具库
119 lines (117 loc) • 3.28 kB
JavaScript
/* eslint-disable @typescript-eslint/no-require-imports */
function getJsonFromSheet(dataPath) {
var xlsx = require('xlsx');
var readFileSync = require('fs').readFileSync;
var excelBuffer = readFileSync(dataPath, {
encoding: 'utf-8'
});
// 解析数据
var result = xlsx.read(excelBuffer, {
type: 'binary',
cellHTML: false
});
return xlsx.utils.sheet_to_json(result.Sheets.Sheet1);
}
/**
* excel 转 json
* @param {object} params 参数
* @returns jsonData
* @example
*
* const options = {
* header: ['id', 'name', 'age'], // 可选:自定义表头
* range: 1, // 可选:跳过第一行(标题行)
* defval: null, // 可选:空单元格的默认值
* raw: false, // 可选:是否保留原始数据格式
* };
*
* excelToJson({
* filePath: CONFIG.xlsxPath,
* sheetIndex: 1,
* options,
* });
*
* // [
* // { id: 1, name: '2', age: '3' },
* // { id: 1, name: '2', age: '3' }
* // ];
*
*/
function excelToJson(_a) {
var filePath = _a.filePath,
_b = _a.sheetIndex,
sheetIndex = _b === void 0 ? 0 : _b,
_c = _a.options,
options = _c === void 0 ? {} : _c;
var xlsx = require('xlsx');
// 读取 Excel 文件
var workbook = xlsx.readFile(filePath);
// 获取第一个工作表名
var sheetName = workbook.SheetNames[sheetIndex];
// 获取工作表
var worksheet = workbook.Sheets[sheetName];
// 转换为 JSON
var jsonData = xlsx.utils.sheet_to_json(worksheet, options);
return jsonData;
}
/**
* json 转 excel
* @param {object} params 参数
* @example { workbook, worksheet }
*
* const jsonData = [
* { id: 1, name: '2', age: '3' },
* { id: 1, name: '2', age: '3' },
* ];
*
* jsonToExcel({
* jsonData,
* outputPath: CONFIG.outputFilePath,
* options: {
* header: ['id', 'name', 'age'], // 可选:自定义表头顺序
* skipHeader: false, // 可选:是否跳过表头行
* },
* sheetName: 'addedData',
* });
*/
function jsonToExcel(_a) {
var jsonData = _a.jsonData,
outputPath = _a.outputPath,
_b = _a.options,
options = _b === void 0 ? {} : _b,
_c = _a.sheetName,
sheetName = _c === void 0 ? 'Sheet1' : _c,
_d = _a.overwrite,
overwrite = _d === void 0 ? true : _d;
var xlsx = require('xlsx');
var fs = require('fs');
var workbook;
if (fs.existsSync(outputPath)) {
workbook = xlsx.readFile(outputPath);
} else {
workbook = xlsx.utils.book_new();
}
// 创建工作表
var worksheet = xlsx.utils.json_to_sheet(jsonData, options);
if (workbook.SheetNames.includes(sheetName)) {
if (overwrite) {
// 删除现有sheet
var sheetIndex = workbook.SheetNames.indexOf(sheetName);
workbook.SheetNames.splice(sheetIndex, 1);
delete workbook.Sheets[sheetName];
} else {
throw new Error("\u5DE5\u4F5C\u8868 \"".concat(sheetName, "\" \u5DF2\u5B58\u5728"));
}
}
xlsx.utils.book_append_sheet(workbook, worksheet, sheetName);
// 写入文件
xlsx.writeFile(workbook, outputPath, {
bookType: 'xlsx',
type: 'file' // 输出类型
});
return {
workbook: workbook,
worksheet: worksheet
};
}
export { excelToJson, getJsonFromSheet, jsonToExcel };