import React, { Component } from "react"; import { Button } from 'antd'; const htmlPrefix = ` <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="https://www.w3.org/TR/REC-html40"> <head> <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> <meta charset="utf-8" /> <style type="text/css"> table th{ font-size: 14px; } table th,td{ text-align: center; } table td{ font-size: 12px; } .red{ color: red; } </style> </head> <body> ` const htmlSuffix = ` </body> </html> ` export default class ExcelButton extends Component { constructor(props, context) { super(props, context); this.state = { table: '' }; } componentDidMount() { } componentWillReceiveProps(props) { if(props.table) { const type = Object.prototype.toString.call(props.table).slice(8, -1); switch(type) { case 'HTMLTableElement': this.setState({ table: props.table.outerHTML }); break; case 'String': this.setState({ table: props.table }); break; } } } render() { return ( <Button {...this.props} type="primary" onClick={() => { const html = ` ${htmlPrefix} ${this.state.table} ${htmlSuffix} `; const blob = new Blob([html], { type: "application/vnd.ms-excel" }); let link = document.createElement('a'); link.style.display = 'none'; link.href = URL.createObjectURL(blob); link.setAttribute('download', `${this.props.fileName?this.props.fileName: '鐧惧疂鐩�'}.xls`); document.body.appendChild(link); link.click(); }}> {this.props.children} </Button> ); } }