node根據excel批量改名

程序預覽

index.js

var xlsx = require('node-xlsx');
var fs = require('fs');
process.stdin.setEncoding('utf8');

// This function reads only one line on console synchronously. After pressing `enter` key the console will stop listening for data.
function readlineSync() {
    return new Promise((resolve, reject) => {
        process.stdin.resume();
        process.stdin.on('data', function (data) {
            process.stdin.pause(); // stops after one line reads
            resolve(data);
        });
    });
}

// entry point
async function main() {
    console.log('請輸入或拖入表格路徑,輸入後按回車鍵');
    let sheetsInput = await readlineSync();
    console.log('請輸入或拖入待改名文件的文件夾路徑,輸入後按回車鍵');
    let zipDirPathInput = await readlineSync();
    console.log("輸入的信息是:",sheetsInput,zipDirPathInput);







    var sheets = xlsx.parse(sheetsInput.trim());//xlsx.parse("C:\\Users\\Administrator\\Desktop\\1.xlsx");//獲取到全部sheets
    var zipDirPath=zipDirPathInput.trim();//"C:\\Users\\Administrator\\Desktop\\zipdir";
    let totalNum=0;
    sheets.forEach(function(sheet,index){
        //console.log(sheet['name']);

        if(index==0){
            for(var rowId in sheet['data']){
                var row=sheet['data'][rowId];
                //console.log(rowId);
                //console.log(row);
                let thisName=row[0];
                let thisCode=row[1];
                //console.log(thisCode);

                let needChangeFliePath=zipDirPath + '/' + thisCode+".zip";
                let newPathName=zipDirPath + '/' + thisName+"_"+thisCode+"_原"+thisCode+".zip";
                fs.stat(needChangeFliePath, function(err, stat){
                    if(stat&&stat.isFile()) {
                        //console.log('文件存在');
                        //console.log(needChangeFliePath);
                        fs.rename(needChangeFliePath, newPathName, function(err) {
                            if (err) {
                                throw err;
                            }else {
                                totalNum++;
                                //let info=zipDirPath + '/' + thisName+thisCode+"_原"+thisCode+".zip";
                                console.log("已處理"+totalNum+" "+newPathName);
                            }
                        });
                    } else {
                        console.log(needChangeFliePath+',文件未匹配到或已處理,不須要處理');
                    }
                });

            }
        }

    });



}

main();

package.json

{
  "name": "1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "node-xlsx": "^0.15.0"
  }
}
相關文章
相關標籤/搜索