目前支持寫Excel的node.js模塊:
node-xlsx: 基于Node.js解析excel文件數(shù)據(jù)及生成excel文件;
excel-parser: 基于Node.js解析excel文件數(shù)據(jù),支持xls及xlsx格式文件;
excel-export : 基于Node.js將數(shù)據(jù)生成導(dǎo)出excel文件,生成文件格式為xlsx;
node-xlrd: 基于node.js從excel文件中提取數(shù)據(jù),僅支持xls格式文件。
使用node-xlsx操作Excel文件
用一個處理Excel文件的項目來說明
首先新建文件夾xlsx,在此文件夾下安裝依賴
$ npm init
$ npm install --save node-xlsx
新建input文件夾,并將需要修改的文件拷貝到此文件夾下
新建index.js文件
const xlsx = require('node-xlsx')
const fs=require('fs');
//readdir為讀取該文件夾下的文件
fs.readdir('./input', function(err,files){
? ? files.forEach((file) => {
? ? ? ? let path = `${__dirname}/input/${file}`;
? ? ? ? console.log(path);
? ? ? ? //表格解析
? ? ? ? let sheetList = xlsx.parse(path);
? ? ? ? //對數(shù)據(jù)進(jìn)行處理
? ? ? ? sheetList.forEach((sheet) => {
? ? ? ? ? ? sheet.data.forEach((row, index) => {
? ? ? ? ? ? ? ? let rowIndex = index;
? ? ? ? ? ? ? ? row.forEach((cell, index) => {
? ? ? ? ? ? ? ? ? ? let colIndex = index;
? ? ? ? ? ? ? ? ? ? if(cell !== undefined){
? ? ? ? ? ? ? ? ? ? ? ? sheet.data[rowIndex][colIndex] = cell.replace(/replaced text1/g, '')
? ? ? ? ? ? ? ? ? ? ? ? ? ? .replace(/replaced text2/g, '');
? ? ? ? ? ? ? ? ? ? ? ? let reg = /\{([\u4e00-\u9fa5\.\w\:\、\/\d\s《》-]*)\|[\u4e00-\u9fa5\.\w\:\、\/\d\s《》-]*\}/;
? ? ? ? ? ? ? ? ? ? ? ? let tempStr = sheet.data[rowIndex][colIndex];
? ? ? ? ? ? ? ? ? ? ? ? while(reg.test(tempStr)){
? ? ? ? ? ? ? ? ? ? ? ? ? ? tempStr = tempStr.replace(reg, RegExp.$1);
? ? ? ? ? ? ? ? ? ? ? ? ? ? // console.log(tempStr);
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? sheet.data[rowIndex][colIndex] = tempStr;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? })
? ? ? ? ? ? })
? ? ? ? ? ? console.log(sheet);
? ? ? ? })
? ? ? ? //數(shù)據(jù)進(jìn)行緩存
? ? ? ? let buffer = xlsx.build(sheetList);
? ? ? ? //將緩存的數(shù)據(jù)寫入到相應(yīng)的Excel文件下
? ? ? ? fs.writeFile(path.replace(/input/, 'output').replace(/\./, '修改版.'), buffer, function(err){?
? ? ? ? ? ? if (err) {
? ? ? ? ? ? ? ? console.log(err);
? ? ? ? ? ? ? ? return ;
? ? ? ? ? ? }
? ? ? ? });
? ? })
})
執(zhí)行js腳本:
node index.js
在output文件夾下查詢修改后文件