最近同事在用java讀取xlsx文件遇到困難榴徐,說是什么表格他復雜之類的,java呢匀归,我不懂坑资,那么就想用我偉大的nodejs
,結(jié)果還真有那么厲害的穆端。好了袱贮,我就不嫌棄java了,這里當做小筆記体啰,絕非復制粘貼攒巍。
npm i xlsx -S
讀取數(shù)據(jù)
let xlsx = require('xlsx');
let workbook = xlsx.readFile('susu.xlsx'); //workbook就是xls文檔對象
let sheetNames = workbook.SheetNames; //獲取表明
let sheet = workbook.Sheets[sheetNames[0]]; //通過表明得到表對象
var data =xlsx.utils.sheet_to_json(sheet); //通過工具將表對象的數(shù)據(jù)讀出來并轉(zhuǎn)成json
寫數(shù)據(jù)
let xlsx = require('xlsx');
let json = [
{"大標題":null},
{null:"大標題"},
{null:"大標題"},
{null:"大標題"},
{ Name: 'name_01', Age: 21, Address: 'address_01' },
{ Name: 'name_02', Age: 22, Address: 'address_02' },
{ Name: 'name_03', Age: 23, Address: 'address_03' },
{ Name: 'name_04', Age: 24, Address: 'address_04' },
{ Name: 'name_05', Age: 25, Address: 'address_05' }, ];
let ss = xlsx.utils.json_to_sheet(json); //通過工具將json轉(zhuǎn)表對象
let keys = Object.keys(ss).sort(); //排序 [需要注意,必須從A1開始]
let ref = keys[1]+':'+keys[keys.length - 1]; //這個是定義一個字符串 也就是表的范圍[A1:C5]
let workbook = { //定義操作文檔
SheetNames:['nodejs-sheetname'], //定義表明
Sheets:{
'nodejs-sheetname':Object.assign({},ss,{'!ref':ref}) //表對象[注意表明]
},
}
xlsx.writeFile(workbook,"./suzhenwei.xls"); //將數(shù)據(jù)寫入文件