nodejs写excel

2019-07-20  本文已影响0人  胖子罗

背景介绍

近期工作中有需求去定制excel报表,比如插入图片、合并单元格、设置单元格样式;最开始用的node-xlsx库,但这个库只能读写普通的文本,无法满足需求,于是找到excel4node

安装

npm install excel4node --save-dev

引用

const xl = require('excel4node')

写入图片

const wb = new xl.Workbook()
const ws = wb.addWorksheet('test')
  ws.addImage({
    image: fs.readFileSync(path.resolve(__dirname, '../static/logo.png')),//可以支持本地路径、URL
    type: 'picture',
    position: {
      type: 'twoCellAnchor',
      from: {
        col: 1,
        colOff: 0,
        row: 1,
        rowOff: 0,
      },
      to: {
        col: 5,
        colOff: 0,
        row: 8,
        rowOff: 0,
      },
    },
  })

设置单元格格式

const styleData = wb.createStyle({
    alignment:{
      horizontal:'left',//设置单元格左对齐
      vertical:'center'//设置单元格上下居中
    },
    font:{
      bold:false,//设置字体加粗
      size:14//设置字体大小

    },//
    border:{//设置边框
      left: {
        style: 'thin',
        color: '#D3D3D3'
      },
      right: {
        style: 'thin',
        color: '#D3D3D3'
      },
      top: {
        style: 'thin',
        color: '#D3D3D3'
      },
      bottom: {
        style: 'thin',
        color: '#D3D3D3'
      }
    },
    fill:{//设置单元格背景色
      type:'pattern',
      patternType:'solid',
      bgColor:'#ffffff',
      fgColor:'#ffffff'
    }
  })
//使用指定格式写入单元格
ws.cell(13+i,j+1).string(''+values[j]).style(styleData)

合并单元格

//合并单元格
  ws.cell(1,1,9,14,true).string('').style(styleTitle)
  ws.cell(10,1,10,14,true).string('').style(styleTitle)
  ws.cell(11,1,11,14,true).string('').style(styleReportHeader)

设置行高、列宽

ws.row(10).setHeight(30) //设置行高
ws.column(1).setWidth(18)//设置列宽

详情见:https://github.com/natergj/excel4node

上一篇下一篇

猜你喜欢

热点阅读