使用nodejs處理Excel文件

目前支持寫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文件的項(xiàng)目來說明

首先新建文件夾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文件夾下查詢修改后文件

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容