详解使用Node.js 将txt文件转为Excel文件

2020-06-17 05:48:11易采站长站整理

var policyLists = data.split(config.splitRules.policyName);
if (policyLists[0] === 'rn') {
policyLists.shift();
};

然后针对数组中每一个元素(一个段落)根据之前文件中所需要项目,使用正则表达式切提取出所需要的内容,然后将提取出的内容组成所需要的数据结构,具体代码如下。其中schedule项目中内容也并非在一行中,所以也同样使用上面的方法进行切割。而对于其他的项目,则通过正则表达式来进行内容的获取。


policyLists.forEach(function (policy) {
var policyData = policyFormatter(config.splitRules.policyName + policy);
excelData.push(policyData);
});

/**
* 对每一个policy进行整理 使其符合表格插入的形式
* @param {*} policy
* {
* policyName: String
* client: []] * policyType: String
* include: [] * schedule[] * scheduleResidence: String
* }
*
*/
function policyFormatter(policy) {

var policyNameMatcher = new RegExp(config.splitRules.policyName + "([swd-]*)rn"),
clientMatcher = new RegExp(config.splitRules.client + "([swd?-.]*)rn", "g"),
policyTypeMatcher = new RegExp(config.splitRules.policyType + "([swd()-]*)rn"),
includeMatcher = new RegExp(config.splitRules.include + "([s/w.:_?="*]*)rn", "g");

var scheduleLists = policy.split(config.splitRules.schedule).slice(1),
scheduleFormatLists = [],
scheduleResidenceMatcher = new RegExp(config.splitRules.scheduleResidence + "([swd-()]*)rn");

scheduleLists.forEach(function (schedule) {
var scheduleFormat = config.splitRules.schedule + schedule;
scheduleFormatLists.push(scheduleFormat);
});

// console.log(scheduleFormatLists);

var results = {
policyName: policy.match(policyNameMatcher)[1].trim(),
client: policy.match(clientMatcher) ? policy.match(clientMatcher).join('').trim() : '',
policyType: policy.match(policyTypeMatcher)[1].trim(),
include: policy.match(includeMatcher).join('').trim(),
schedule: scheduleFormatLists.join('').trim(),
scheduleResidence: scheduleLists[0].match(scheduleResidenceMatcher)[1].trim()
};

// console.dir(results);
return results;
}

主要逻辑处理完以后,把收集到的内容传给excel处理模块,导出成文件就能解决问题了。

不过似乎最终如果能导出为Word,似乎更好。看来还有新的改进空间还留着呢。