这里演示的demo是基于react的
yarn add exceljs file-saver echarts
首先安装以上三个包。
直接使用下列代码即可。
import React, { Component } from 'react'
import './App.css'
import * as echarts from 'echarts/lib/echarts'
import {
LegendComponent,
TitleComponent,
GridComponent,
TooltipComponent,
MarkPointComponent,
} from 'echarts/components'
echarts.use([
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
MarkPointComponent,
])
import 'echarts/lib/chart/bar'
import * as Excel from "exceljs";
import * as FileSaver from "file-saver";//用于客户端读写数据
class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// 基于准备好的dom,初始化echarts实例
this.myChart = echarts.init(document.getElementById('Line'))
// 绘制图表
this.myChart.setOption({
title: { text: 'ECharts 入门示例' },
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20],
},
],
})
}
handleExport() {
this.imagesBase64 = this.myChart.getDataURL('png')
this.handleExcel(this.imagesBase64);
}
handleExcel(base64Img) {
const EXCEL_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
let workbook = new Excel.Workbook();
workbook.creator = "Me";
workbook.lastModifiedBy = "Her";
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date();
workbook.views = [
{
x: 0,
y: 0,
width: 1000,
height: 2000,
firstSheet: 0,
activeTab: 1,
visibility: "visible",
},
];
let worksheet = workbook.addWorksheet("sheet1");
const imgArr = [base64Img] // 可以多张图片
imgArr.forEach((item, index) => {
const imageId1 = workbook.addImage({
base64: item,
extension: "png",// 图片扩展名,支持“jpeg”,“png”,“gif”
});
worksheet.addImage(
imageId1,
`${String.fromCharCode(65 + index * 6)}1:${String.fromCharCode(
70 + index * 6
)}16`
);
});
workbook.xlsx.writeBuffer().then((data) => {
const blob = new Blob([data], { type: EXCEL_TYPE });
console.log(blob.stream(), 6664744)
FileSaver.saveAs(blob, "download.xlsx");
});
}
render() {
return (
<div>
<div id="Line" style={{ width: 400, height: 400 }}></div>
<button onClick={this.handleExport.bind(this)}>下载</button>
</div>
)
}
}
export default App