安装
npm install exceljs
解析excel
通过 Workbook 的 readFile 方法可以拿到workbook对象, workbook对象包含的概念有 worksheet(工作表) --> row(行) --> cell(单元格).于是可以通过依次遍历 worksheet, row, cell来拿到单元格的数据 直接通过 worksheet.getSheetValues() 拿到数据(包含了列号,还有行号那些数据的位置,以empty代替)
const { Workbook } = require ( "exceljs" ) ;
const workbook = new Workbook ( ) ;
( async function ( ) {
const res = await workbook. xlsx. readFile ( "./test.xlsx" ) ;
res. eachSheet ( item => {
const res = item. getSheetValues ( ) ;
console . log ( res) ;
} ) ;
} ) ( ) ;
生成excel
创建 workbook, 添加worksheet, 设置columns列,然后添加行数据rowData
const { Workbook } = require ( "exceljs" ) ;
const workbook = new Workbook ( ) ;
( async function ( ) {
const sheet = workbook. addWorksheet ( "test-sheet" ) ;
sheet. columns = [
{ header: "id" , key: "id" , width: 20 } ,
{ header: "姓名" , key: "nickname" , width: 30 } ,
{ header: "年龄" , key: "age" , width: 30 } ,
{ header: "手机号" , key: "phone" , width: 50 }
] ;
const rowData = [
{ id: 1 , nickname: "小明1" , age: 20 , phone: "123456789" } ,
{ id: 2 , nickname: "小明2" , age: 20 , phone: "123456789" } ,
{ id: 3 , nickname: "小明3" , age: 20 , phone: "123456789" } ,
{ id: 4 , nickname: "小明4" , age: 20 , phone: "123456789" }
] ;
sheet. addRows ( rowData) ;
workbook. xlsx. writeFile ( "./test1.xlsx" ) ;
} ) ( ) ;