美文网首页
react项目中导出Excel

react项目中导出Excel

作者: Issho | 来源:发表于2020-04-08 14:22 被阅读0次

☼ 注:笔者的文章是根据自己当前项目做的笔记,具体应用请参照自己实际项目情况

1、纯前端导出

① 安装react-export-excel插件

npm install react-export-excel --save

② 封装组件

/**
 * 本地表格导出Excel按钮,仅限于当前前端页面所展示的表格
 * @param {Element} tableRef 表格元素
 * @param {Function} onClickExport 按钮点击事件
 */
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import ReactHTMLTableToExcel from 'react-html-table-to-excel'
import { Button } from 'antd'
import styles from './index.scss'

class ExportExcel extends Component {
    UNSAFE_componentWillReceiveProps = nextProps => {
        if (nextProps.tableRef) {
            // 获取到table设置id,这里项目中用的是antd的Table组件
            const tableCon = ReactDOM.findDOMNode(nextProps.tableRef)
            const table = tableCon.querySelector('table')
            table.setAttribute('id', 'table-to-xls')
        }
    }

    render() {
        const icon = <span><i className='iconfont iconexport'></i>导出</span>
        // 普通按钮
        if (!this.props.tableRef) return <Button type="primary" onClick={this.props.onClickExport}>{ icon }</Button>
        return (
            <ReactHTMLTableToExcel
                id={styles['test-table-xls-button']}
                className="ant-btn ant-btn-primary"
                table="table-to-xls"
                filename="tablexls"
                sheet="tablexls"
                buttonText={icon} />
        )
    }
}

export default ExportExcel
2、后台返回Blob对象(数据处理参考上一篇axios拦截器的配置)

① 封装工具函数

/**
 * 导出Excel,暂时只适用普通url和bloburl,兼容IE10+
 * @param {a} ele a标签
 * @param {blob/url} data blob对象或普通url
 * @param {string} file 导出的文件名,针对blob有效,普通url无效,需要后台来更改文件名
 */
export const insertComponent = (ele, data, file = '默认文件名') => {

    if (!data) {
        return
    }

    // 针对IE
    if (window.navigator.msSaveBlob && typeof data === 'object') {
        return window.navigator.msSaveBlob(data, `${file}.xls`)
    }

    const el = document.createElement(ele)

    if (typeof el.href !== 'undefined') {
        // 针对普通url
        el.href = typeof data === 'string' ? data : window.URL.createObjectURL(data)
        // 针对blob,edge必须有download属性,且普通url只有edge可以修改文件名
        el.download = `${file}.xls`
        // 兼容fireFox的事件触发
        const evt = document.createEvent('MouseEvents')
        evt.initEvent('click', true, true)
        el.dispatchEvent(evt)
        // 或:
        // document.body.appendChild(el)
        // el.click()
        // document.body.removeChild(el)
    }
}

② 调用工具函数生成Excel并下载

/**
 * 导出Excel
 * @param {Object} params 参数对象
 */
exportExcel = params=> {
   // 接口请求方法
   exportTransactionFlow(params).then(data => {
        insertComponent('a', data, '文件名')
    })
}

相关文章

网友评论

      本文标题:react项目中导出Excel

      本文链接:https://www.haomeiwen.com/subject/daweyctx.html