使用nodejs實現(xiàn)JSON文件自動轉(zhuǎn)Excel的工具(推薦)
這段時間做項目,需要把json格式的文檔給到業(yè)務人員去翻譯,每次手動翻譯,很麻煩,于是就想著寫一個高逼格的自動化工具來完成這件事情。
說實現(xiàn),初步思路就是使用類似"json2excel start"這樣的命令,然后它就自己跑。像vue,react運行命令一樣。
首先,我們 npm init 新建一個項目工程,新建我們項目的核心文件json2excel.js ,并運行node json2exce.js,然后控制臺就可以打印東西了。
把一個文件轉(zhuǎn)化成另一個文件,我們要知道這個文件的路徑,以及保存到的位置,所以命令設計為:
json2excel start inpath outpath
我們使用一個非常好用的命令行輔助包"commander",提示命令輸入,json2excel.js如下,
const program = require('commander') // 定義當前的版本 program .version(require('../package').version) // 定義命令方法 program .usage('<command> [inPath] [toPath]') program .command('start [paths...]') .description('Conversion from JSON to csv') .alias('-s') .action(paths => require('./command/j2c')(paths)) program.parse(process.argv) if (!program.args.length) { program.help() }
然后運行node json2excel.js會看到(現(xiàn)在還沒安裝bin命令,所以用node json2excel代替json2excel),
非常哇瑟的一個操作,就可以看到命令引導提示了。
.command() 是定義命令及其后面的參數(shù),我們定義了paths
.description() 是描述
.alias() 是命令的別名
.action() 是運行命令時要執(zhí)行的操作,paths是command里面?zhèn)鬟^來的參數(shù)
我們新建../command/j2c.js,.action()的時候我們有接受命令參數(shù)
module.exports = (paths) => { // 這樣就得到了輸入、輸出的路徑了 let [inPath, outPath] = paths }
如果命令參數(shù)沒有附帶怎么辦?
如: node json2excel start
不帶路徑然后就回車
那我們就引導用戶再次輸入,使用"co","co-prompt"這兩個工具
上代碼:../command/j2c.js
const co = require('co') const prompt = require('co-prompt') module.exports = (paths) => { co(function* () { let [inPath, outPath] = paths // 處理用戶輸入 inPath = inPath ? inPath : yield prompt('Input file directory: ') outPath = outPath ? outPath : (yield prompt('Output file directory: ')) || inPath }) }
co里面接受generator函數(shù),主要是異步操作作同步處理的寫法。
運行 node json2excel start
這樣就可以保證拿到輸入輸出的路徑了,用戶體驗滿分,棒棒的。
下一步, 通過拿到的輸入路徑,獲取json文件 ,使用"glob"這個工具,通過正則匹配拿到inpath路徑下所有的json文件
站在巨人的肩膀上做事,事半功倍,代碼如下:
拿到json文件,我們就開始向Excel轉(zhuǎn)換,csv是一種和json一樣簡單數(shù)據(jù)結(jié)構,我們把json轉(zhuǎn)成csv的格式。
以下是json格式和csv格式的對比,這樣去看,轉(zhuǎn)換也不難。左邊是json數(shù)據(jù)格式,右邊是字符串,可以這么理解。
我們使用"json2csv"這個包,有時間的也可以自己轉(zhuǎn)換拼接。
讀取json文件并轉(zhuǎn)換成scv:
const Json2csvParser = require('json2csv').Parser for(let filename in files) { // 同步讀取文件 let jsonData = fs.readFileSync(files[filename]) jsonData = JSON.parse(jsonData) // json2csv轉(zhuǎn)換 const fields = Object.keys(jsonData[0]) const json2csvParser = new Json2csvParser({fields}) const csvData = json2csvParser.parse(jsonData) // 寫入的文件名 const outputFileName = `${outPath}/${filename}.csv` // 寫入文件 const err = fs.writeFileSync(outputFileName, csvData) if(err) { return console.log(err) } else { console.log(`- ${filename}.json Conversion successful!`) } }
運行后可以得到一個.csv的文件,一個簡單的實現(xiàn)完成。
細節(jié)優(yōu)化,并實現(xiàn):
在office下會顯示亂碼,所以要定義為UTF-8的格式存儲。
// office Excel需要 BOM 頭來定義 UTF-8編碼格式 const BOM = Buffer.from('\uFEFF') const csvData = Buffer.concat([BOM, Buffer.from(csvData)])
如果輸出路徑不存在,存儲也不會成功
// 不存在文件夾就創(chuàng)建 if(!fs.existsSync(outPath)) { fs.mkdirSync(outPath) }
json格式數(shù)據(jù),有對象形式的,也有數(shù)組形式的,如果是對象就轉(zhuǎn)化成數(shù)組
// 如果是對象,把對象的每一個鍵值對,轉(zhuǎn)化成'key', 'value'的數(shù)組項 let jsonData, fields if(Object.prototype.toString.call(jsonData) === '[object Object]') { jsonData = Object.keys(jsonData).map(key => ({ key: key, value: jsonData[key] })) fields = ['key', 'value'] } if(Object.prototype.toString.call(jsonData) === '[object Array]') { jsonData = jsonData fields = Object.keys(jsonData[0]) }
存儲成功顯示文件存儲的路徑,并退出進程
// 提示輸出的文件目錄,并退出 console.log(chalk.blue(`- Please go to check the file: ${chalk.underline(path.join(process.cwd(), outPath))}`)) process.exit()
操作加提示,并且輸出的文字加顏色
// 使用一個非常方便的工具chalk const chalk = require('chalk') console.log(chalk.green('Start Conversion: '))
完整代碼如下:
'use strict' const fs = require('fs') const path = require('path') const chalk = require('chalk') const glob = require('glob') const co = require('co') const prompt = require('co-prompt') const Json2csvParser = require('json2csv').Parser // 獲取多文件的方法 const getMultiEntry = function (globPath) { let entries = {} glob.sync(globPath).forEach(function (entry) { const basename = path.basename(entry, path.extname(entry)) entries[basename] = entry }) return entries } module.exports = (paths) => { co(function* () { let [inPath, outPath] = paths // 處理用戶輸入 inPath = inPath ? inPath : yield prompt('Input file directory: ') outPath = outPath ? outPath : (yield prompt('Output file directory: ')) || inPath // 遍歷獲取json文件 const files = getMultiEntry(`${inPath}/*.json`) // 如果指定目錄下沒有json文件輸出提示信息并退出進程 if (!Object.keys(files).length) { console.log(chalk.red('\n x There is no JSON file in the specified folder')) process.exit() } // 開始轉(zhuǎn)換文件 console.log('\n ') console.log(chalk.green('Start Conversion: ')) for(let filename in files) { // 同步讀取文件 let jsonData = fs.readFileSync(files[filename]) jsonData = JSON.parse(jsonData) /* * 判斷csv能接受的數(shù)據(jù)結(jié)構 * 如果是json對象,則取key, value作為列 * 如果是json數(shù)組,則讀取第一行的所有key * */ let jData, fields if(Object.prototype.toString.call(jsonData) === '[object Object]') { jData = Object.keys(jsonData).map(key => ({ key: key, value: jsonData[key] })) fields = ['key', 'value'] } if(Object.prototype.toString.call(jsonData) === '[object Array]') { jData = jsonData fields = Object.keys(jsonData[0]) } // json格式 => csv格式 const json2csvParser = new Json2csvParser({fields}) const csvData = json2csvParser.parse(jData) // office Excel需要 BOM 頭來定義 UTF-8編碼格式 const BOM = Buffer.from('\uFEFF') const bomCsv = Buffer.concat([BOM, Buffer.from(csvData)]) // 寫入的文件名 const outputFileName = `${outPath}/${filename}.csv` // 不存在文件夾就創(chuàng)建 if(!fs.existsSync(outPath)) { fs.mkdirSync(outPath) } // 寫入文件 const err = fs.writeFileSync(outputFileName, bomCsv) if(err) { return console.log(err) } else { console.log(chalk.green(`- ${filename}.json Conversion successful!`)) } } // 提示輸出的文件目錄 console.log('\n ') console.log(chalk.blue(`- Please go to check the file: ${chalk.underline(path.join(process.cwd(), outPath))}`)) process.exit() }) }
之后就是使用命令了,如何安裝使用命令?
package.json bin命令
實現(xiàn),在項目根目錄建一個bin目錄,package.json定義個bin命令
在bin/json2excel.js 文件的開頭寫上 #!/usr/bin/env node
項目包安裝的時候,npm就會在 /node_modules/.bin
里面安裝一個bin命令,這樣可以使用json2excel命令了,執(zhí)行json2excel start *
如果是全局安裝就可以在任何地方使用。
至此,一個json轉(zhuǎn)csv的實現(xiàn)完美的完成。
從json轉(zhuǎn)換csv,如果拿到csv如何還原成csv呢?
增加命令:
把json轉(zhuǎn)csv更名為 json2excel j2c [paths]
csv轉(zhuǎn)json取名為 json2excel c2j [paths]
csv轉(zhuǎn)成json和前面的實現(xiàn)差不多,這里不再寫了。
完整代碼請看 https://github.com/zwzou/json2excel#readme
至此一個完整的json - excel格式轉(zhuǎn)換完成。 期待以后擴展其它的格式
總結(jié)
到此這篇關于使用nodejs實現(xiàn)JSON文件自動轉(zhuǎn)Excel的工具的文章就介紹到這了,更多相關nodejs實現(xiàn)JSON文件轉(zhuǎn)Excel的工具內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解使用Nodejs內(nèi)置加密模塊實現(xiàn)對等加密與解密
這篇文章主要介紹了使用Nodejs內(nèi)置加密模塊實現(xiàn)對等加密與解密,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05