react xlsx
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react xlsx相关的知识,希望对你有一定的参考价值。
npm install --save better-xlsx
用了better-xlsx 继续封装了导出方法
/** * Created by zhanglei on 2017/11/18. */ import Xlsx from ‘better-xlsx‘; export default class Excel { constructor(headData,data){ this.file = new Xlsx.File(); this.sheet = this.file.addSheet(‘Sheet1‘); this.border = (cell, top, left, bottom, right) =>{ const light = ‘ffded9d4‘; const dark = ‘ff7e6a54‘; cell.style.border.top = ‘thin‘; cell.style.border.topColor = top ? dark : light; cell.style.border.left = ‘thin‘; cell.style.border.leftColor = left ? dark : light; cell.style.border.bottom = ‘thin‘; cell.style.border.bottomColor = bottom ? dark : light; cell.style.border.right = ‘thin‘; cell.style.border.rightColor = right ? dark : light; }; this.fill = (cell, type) => { type = type || 0; const colors = [‘ffeeeeee‘, ‘ff46b0c3‘, ‘ffe4e2de‘, ‘fffff8df‘, ‘fff1eeec‘]; cell.style.fill.patternType = ‘solid‘; cell.style.fill.fgColor = colors[type]; cell.style.fill.bgColor = ‘eee‘; }; this.init = () =>{ const header = this.sheet.addRow(); header.setHeightCM(1); const myHeader = headData.map((item,index) =>{ const head = header.addCell(); head.value = item; head.style.align.v = ‘center‘; head.style.font.color = ‘ffeeeeee‘; this.border(head, 0, 0, 1, 0); this.fill(head, 1); // this.sheet.col(index).width = 20; }); const myData = data.map(item =>{ const row = this.sheet.addRow(); row.setHeightCM(0.8); item.map((d,i) =>{ const cell1 = row.addCell(); cell1.value = d; cell1.style.align.v = ‘center‘; this.border(cell1, 1, 1, 1, 1); this.fill(cell1,2)//颜色 }); }); this.file .saveAs(‘blob‘) .then(function(content) { const link = document.createElement(‘a‘); link.href = URL.createObjectURL(content); link.download = new Date().getTime()+‘.xlsx‘; link.click(); setTimeout(function() { URL.revokeObjectURL(content); }, 100); }); } } } //用法 // const data = [ // [‘2012-12-1‘,‘222‘,‘333‘,‘2222‘], // [‘2012-12-1‘,‘3333‘,‘2222‘,‘3333‘], // ]; // const headData = [null,‘涨三‘,‘李四‘,‘王五‘]; // const excel = new Excel(headData,data); // excel.init();
以上是关于react xlsx的主要内容,如果未能解决你的问题,请参考以下文章
javascript 用于在节点#nodejs #javascript内设置react app的代码片段
如何在前端(TS、React)上将 CSV 转换并下载到 XLSX
[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段