作者:亚艾元技术部
客户提供了很多的数据,word格式的,里面数据格式都是表格,wojiang 数据拷贝到excel表里面以后,有的数据占3行,有的占据1行。实际占据3行的数据,应该占据1行才对。
我以前是用手工给客户处理的,当时有几万条数据,手工给他们合并了,花了1星期多的时间,很是费力,中间还不休息。
这次客户又把数据给了我word的格式,数据量也有几千条需要我手工的合并整理。手工整理合并了1000条以后,我决定写个程序,都说python处理excel表很方便。可惜我不会啊。
我选择了熟悉的nodejs, 还有xlsx库。来完成我要做的操作。这是关键的代码:
let filePath = `D:\\nodejs\\opexcel\\public\\excel\\bcsb.xlsx`; let workbook = xlsx.readFile(filePath); //workbook就是xls文档对象 let sheetNames = workbook.SheetNames; //获取表明 let sheet = workbook.Sheets[sheetNames[0]]; //通过表明得到表对象 var data =xlsx.utils.sheet_to_json(sheet); let last_item = null; let newdata = []; let i = 0; for(let j = 0,len=data.length; j < len; j++) { let item = data[j]; // 清除空格。 let xuhao = item["序号"] || ""; xuhao = xuhao.toString().trim(); if(xuhao != ""){ item["序号"] = xuhao; if(last_item){ newdata.push(last_item); } last_item = item; }else{ let mincheng = item["名称"] || ""; let fangfa = item["方法"] || ""; let shuoming = item["说明"] || ""; if(mincheng != ""){ last_item["名称"] = last_item["名称"] + " " + mincheng; } if(fangfa != ""){ last_item["方法"] = last_item["方法"] + ";\n " + fangfa; } if(shuoming != ""){ last_item["说明"] = last_item["说明"] + " " + shuoming; } } //console.log(typeof index) } if(last_item){ newdata.push(last_item); } const ws = xlsx.utils.json_to_sheet(newdata); const wb = xlsx.utils.book_new(); xlsx.utils.book_append_sheet(wb, ws, "Sheet1"); xlsx.writeFile(wb, `D:\\nodejs\\opexcel\\public\\excel\\new_bcsb.xlsx`)
我先用xlsx库读取我给定的excel文件,将其转为json格式,使用js的数组循环操作。当序号一列跨行的时候,后续几行数据,追加过来,这样就合并了单元格。
重新合并好的数据,再以excel的格式输出。保存到一个新的文件上面来。
当然,我这里使用了koa,在浏览器上面,每次访问这个页面,这个操作就会执行一次。几十个这样的文件,一个一个的放过来,执行,生成新的文件,虽然有点笨,但是与原来的方式相比,节省了大量的手工整理的时间。