通过文本标识转成json格式
1.文本内容
以下是生成的“员工工资表”:
员工编号| 姓名| 职位| 部门| 基本工资| 奖金| 总工资
—|—|—|—|—|—|—
001| 张三| 销售经理| 销售部| 8000| 2000| 10000
002| 李四| 技术主管| 技术部| 9000| 1500| 10500
003| 王五| 财务专员| 财务部| 7000| 1000| 8000
004| 赵六| 人事助理| 人事部| 6000| 800| 6800
请注意,以上数据仅为示例,实际使用时请替换为真实数据。
2. 转换成表格形式
以下是生成的“员工工资表”:
员工编号 | 姓名 | 职位 | 部门 | 基本工资 | 奖金 | 总工资 |
---|---|---|---|---|---|---|
001 | 张三 | 销售经理 | 销售部 | 8000 | 2000 | 10000 |
002 | 李四 | 技术主管 | 技术部 | 9000 | 1500 | 10500 |
003 | 王五 | 财务专员 | 财务部 | 7000 | 1000 | 8000 |
004 | 赵六 | 人事助理 | 人事部 | 6000 | 800 | 6800 |
请注意,以上数据仅为示例,实际使用时请替换为真实数据。
3. 代码实现
// 表格转换
function handleTableData(txt) {
let arr = [], curr_arr = txt.split('\n').filter(el => el != ''), headerIndex = 0, dataIndex = 0;
while (curr_arr.findIndex(el => el.indexOf('---') != -1) > 0) {
headerIndex = curr_arr.findIndex(el => el.indexOf('---') != -1); // 表头
let nextIndex = curr_arr.slice(headerIndex+1, curr_arr.length).findIndex(el => el.indexOf('---') != -1);
if ( nextIndex > 0) { // 多表格
dataIndex = headerIndex + nextIndex - 1;
} else {
dataIndex = curr_arr.findLastIndex(el => el.indexOf('|') != -1);
}
const headers = curr_arr[headerIndex-1].split('|').filter(el => el != '').map((header, index) => {
return {
'title': header.trim(),
'dataIndex': 'columns-' + index
};
});
const rows = curr_arr.slice(headerIndex+1, dataIndex), jsonData = [];
for (let i = 1; i < rows.length; i++) {
const values = rows[i].split('|').filter(el => el != '').map(value => value.trim());
const obj = {};
for (let j = 0; j < headers.length; j++) {
obj[headers[j].dataIndex] = values[j];
}
jsonData.push(obj);
}
if (nextIndex > 0) {
arr.push({
preTxt: curr_arr.slice(0, headerIndex-1).join('\n'),
columns: headers,
data: jsonData,
lastTxt: ''
});
} else {
arr.push({
preTxt: curr_arr.slice(0, headerIndex-1).join('\n'),
columns: headers,
data: jsonData,
lastTxt: curr_arr.slice(dataIndex+1, curr_arr.length).join('')
});
}
curr_arr = curr_arr.slice(dataIndex, curr_arr.length);
}
return arr;
}
4.生成的数据格式
通过标识符 | 判断表格开始,前后生成表格数组,也适用于多表格
多表格文本
** 表格一:周工作安排表**
| 日期 | 任务 | 负责人 | 开始时间 | 结束时间 | 完成状态 |
| — | — | — | — | — | — |
| 2023-05-22 | 编写报告 | 张三 | 9:00 | 17:00 | 未完成 |
| 2023-05-23 | 会议准备 | 李四 | 10:00 | 12:00 | 已完成 |
| 2023-05-24 | 项目讨论 | 王五 | 14:00 | 16:00 | 进行中 |
| 2023-05-25 | 客户拜访 | 赵六 | 13:00 | 18:00 | 未完成 |
| 2023-05-26 | 数据分析 | 钱七 | 9:00 | 18:00 | 进行中 |
** 表格二:月度工作计划表**
| 日期 | 主要任务 | 负责人 | 预计开始时间 | 预计结束时间 | 备注 |
| — | — | — | — | — | — |
| 2023-05-01 | 市场调研 | 孙八 | - | - | - |
| 2023-05-15 | 产品发布 | 周九 | - | - | - |
| 2023-05-31 | 月度总结 | 吴十 | - | - | - |
这两个表格分别展示了周工作安排和月度工作计划。您可以根据实际情况调整列名和内容。