首页 前端知识 echarts导出功能

echarts导出功能

2024-02-02 09:02:08 前端知识 前端哥 693 100 我要收藏

在这里插入图片描述
导出功能模块前端代码:

<a-menu-item>
     <a @click="ecartsToexcel(leftParam.Header, leftParam.Name, leftParam.Data, leftParam.Title)"
                        >导出excel</a
                      >
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="ExportPng('centerLeftcharts', leftParam.Title)">导出图片</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="exportChartToPDF('centerLeftcharts', leftParam.Title)">导出pdf</a>
                    </a-menu-item>
                  </a-menu>

data中的数据

 leftParam: {
        Header: [{ value1: '包间' }, { value2: '消费余额' }, { value3: '百分比' }],
        Name: ['第一包间', '第二包间', '第三包间', '第四包间', '第五包间'],
        Data: [10, 52, 200, 334, 390],
        Title: '余额消费包间占比',
      },

1、导出excle功能
安装插件

npm install xlsx

引入插件

const XLSX = require('xlsx');

需要两个方法,第一个是核心,第二个封装一下方便使用
第一个:

function ExportsEXCL(name) {
    this.downLoad = ({
        header = [],
        body = [],
        excelName = name,
        hasTitle = true,
    }) => {
        const styleCell = this.setBorderStyle();
        const _headers = header.map((v, i) => {
            let key = Object.keys(v);
            return Object.assign({}, {
                v: `${v[key[0]]}<key>${key[0]}`,
                position: String.fromCharCode(65 + i) + (hasTitle ? 1 : 0)
            });
        })
            .reduce(
                (prev, next) =>
                    Object.assign({}, prev, {
                        [next.position]: {
                            v: next.v,
                            s: styleCell
                        }
                    }), {}
            );
        const _body = body
            .map((v, i) =>
                header.map((k, j) => {
                    let key = Object.keys(k);
                    return Object.assign({}, {
                        v: v[key[0]],
                        position: String.fromCharCode(65 + j) + (i + (hasTitle ? 2 : 1))
                    });
                })
            )
            .reduce((prev, next) => prev.concat(next))
            .reduce(
                (prev, next) =>
                    Object.assign({}, prev, {
                        [next.position]: {
                            v: next.v,
                            s: styleCell
                        }
                    }), {}
            );
        const mergeThead = this.setMergeThead(_headers, hasTitle);
        const _thead = this.setTableThead(mergeThead);
        const output = Object.assign({}, _thead, _body);
        const outputPos = Object.keys(output);
        const ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];
        const wb = {
            SheetNames: ['mySheet'],
            Sheets: {
                mySheet: Object.assign({}, output, {
                    '!ref': ref,

                })
            }
        };
        this.save(wb, `${excelName}.xlsx`);
    };
    this.setTableThead = wb => {
        for (let key in wb) {
            let i = wb[key].v.indexOf('<key>');
            if (wb[key].v.includes('<key>')) {
                wb[key].v = wb[key].v.substr(0, i);
            }
        }
        return wb;
    };
    this.setMergeThead = (wb, hasTitle) => {
        const borderAll = {
            top: {
                style: 'thin'
            },
            bottom: {
                style: 'thin'
            },
            left: {
                style: 'thin'
            },
            right: {
                style: 'thin'
            }
        };
        return wb;
    };

    this.setBorderStyle = () => {
        const borderAll = {
            top: {
                style: 'thin'
            },
            bottom: {
                style: 'thin'
            },
            left: {
                style: 'thin'
            },
            right: {
                style: 'thin'
            }
        };
        return {
            border: borderAll
        };
    };
    this.save = (wb, fileName) => {
        let wopts = {
            bookType: 'xlsx',
            bookSST: false,
            type: 'binary'
        };
        let xw = XLSX.write(wb, wopts);

        let obj = new Blob([this.s2ab(xw)], {
            type: ''
        });
        let elem = document.createElement('a');
        elem.download = fileName || '下载';
        elem.href = URL.createObjectURL(obj);
        elem.click();
        setTimeout(function () {
            URL.revokeObjectURL(obj);
        }, 100);
    };

    this.s2ab = s => {
        if (typeof ArrayBuffer !== 'undefined') {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
            return buf;
        } else {
            var buf = new Array(s.length);
            for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
            return buf;
        }
    };

    // 根据val查询Object key
    this.findKey = (val, obj) => {
        return Object.keys(obj).find(v => obj[v] === val);
    };
}

第二个方法:

function ecartsToexcel(header, nameArr, dataArr, title) {
    var percentages = calculatePercentage(nameArr, dataArr)
    let arrData = []
    let obj1 = {}
    for (var i = 0; i < nameArr.length; i++) {
        obj1 = {
            value1: nameArr[i],
            value2: dataArr[i],
            value3: percentages[i],
        }
        arrData.push(obj1)
    }
    const doit = new ExportsEXCL(title)
    doit.downLoad({
        header: header,
        body: arrData,
        hasTitle: true,
    })
}

2、导出图片
使用echarts自带的功能即可

function ExportPng(chart, title) {
    let myChart = echarts.init(document.getElementById(chart))
    let picInfo = myChart.getDataURL({
        type: 'png',
        pixelRatio: 1.5, //放大两倍下载,之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: '#fff',
    }) //获取到的是一串base64信息

    const elink = document.createElement('a')
    elink.download = title
    elink.style.display = 'none'
    elink.href = picInfo
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
}

3 、导出PDF
下载

npm install jsPDF

引入

import jsPDF from 'jspdf';

方法

function exportChartToPDF(chartId, filename) {
    //下载为pdf
    var myChart = echarts.getInstanceByDom(
        document.getElementById(chartId)
    )
    var url = myChart.getConnectedDataURL({
        pixelRatio: 1, //导出的图片分辨率比率,默认是1
        backgroundColor: '#fff', //图表背景色
        excludeComponents: [
            //保存图表时忽略的工具组件,默认忽略工具栏
            'toolbox',
        ],
        type: 'png', //图片类型支持png和jpeg
    })
    createPDFObject(url, filename)
}
function createPDFObject(imgData, filename) {
    var doc = new jsPDF('p', 'pt')
    doc.addImage(imgData, 5, 5, 600, 250, 'img')
    doc.save(filename + '.pdf')//名字

}
转载请注明出处或者链接地址:https://www.qianduange.cn//article/1130.html
标签
评论
发布的文章

jQuery ---- 插件

2024-02-15 14:02:06

CSS-JavaScript-Jquery-Servlet

2024-02-15 14:02:00

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!