最近想爬取一些excel和word文件中的數(shù)據(jù),于是記錄下來,方便自己后面復(fù)雜粘貼,xls、xlsx、docx文件還是能處理的,但是doc文件處理不了
-
使用cmd文章來源:http://www.zghlxwxcb.cn/news/detail-554837.html
#創(chuàng)建npm項(xiàng)目 npm init #安裝所需包 npm install request --save npm install node-xlsx --save npm install adm-zip --save
-
在入口文件文章來源地址http://www.zghlxwxcb.cn/news/detail-554837.html
const xlsx = require('node-xlsx'); const fs = require('fs'); const path = require('path'); const AdmZip = require('adm-zip'); var request = require("request"); let url = "https://xxxx.cn/442054773520384.xls"; //創(chuàng)建跟該文件同級的data目路 const dataPath = path.resolve("./data"); getFlag(url).then(res => { console.log("res==" + res); }); function getFlag(url) { return new Promise(resolve => { //下載文件 getFileByUrl(url).then(filename => { //處理文件 handleDocxFile(filename); handleExcelFile(filename); resolve(1); }, () => { resolve(2); }).catch((err) => { console.error(err); resolve(3); }); }) } /** * 下載文件 * @param {*} url 網(wǎng)絡(luò)文件url地址 */ function getFileByUrl(url) { return new Promise((resolve, reject) => { //添加文件名和后綴--start let fileName = "file" + new Date().getTime(); if (url.indexOf(".docx") > -1) fileName += ".docx"; else if (url.indexOf(".xls") > -1) fileName += ".xls"; else if (url.indexOf(".xlsx") > -1) fileName += ".xlsx"; else reject(); console.log(fileName); //添加文件名和后綴--end //保存文件--start let stream = fs.createWriteStream(path.join(dataPath, fileName)); request(url).pipe(stream).on("close", function (err) { if (err) { reject(); } console.log("文件" + fileName + "下載完畢"); resolve(fileName); }); //保存文件--end }) } /** * 處理word文件 * @param {文件名} filename */ function handleDocxFile(filename) { if (filename.indexOf(".docx") != -1) { const filePath = path.join(dataPath, filename); const zip = new AdmZip(filePath); //filePath為文件路徑 const str = zip.readAsText("word/document.xml");//將document.xml讀取為text內(nèi)容; //處理該內(nèi)容 console.log(str); //刪除文件 fs.unlink(filePath, err => { if (err) console.log("刪除失敗"); else console.log("刪除成功"); }); } } /** * 處理Excel文件 * @param {文件名} filename */ function handleExcelFile(filename) { if (filename.indexOf(".xls") != -1 || filename.indexOf(".xlsx") != -1) { const filePath = path.join(dataPath, filename); const sheets = xlsx.parse(filePath); //循環(huán)工作表 for (let i = 0; i < sheets.length; i++) { let len = sheets[i].data.length; //循環(huán)獲取每一行 for (let j = 0; j < len; j++) { let row = sheets[i].data[j]; //循環(huán)獲取每個單元格 for (let k = 0; k < row.length; k++) { let cell = row[k]; //處理 console.log(cell); } } } //刪除該文件 fs.unlink(filePath, err => { if (err) console.log("刪除失敗"); else console.log("刪除成功"); }); } }
到了這里,關(guān)于node簡單處理xls、xlsx、docx文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!