import React, { Component } from 'react';
import { Button, WhiteSpace } from 'antd';
import './index.less';
import xlsx from 'xlsx';
class index extends Component {
constructor(props) {
super(props);
this.state = {};
}
print = (id) => {
const el = document.getElementById(id);
const iframe = document.createElement('IFRAME');
let doc = null;
iframe.setAttribute(
'style',
'position:absolute;width:0px;height:0px;left:500px;top:500px;'
);
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write(el.innerHTML);
//打印表格的样式
var ys="html,body{height:100%}table{word-break:break-all;width:100%;height:auto; border: 1px solid #000;border-collapse:collapse}th,td{border: 1px solid #000}";
var style=document.createElement("style");
style.innerText=ys;
doc.getElementsByTagName("head")[0].appendChild(style)
doc.close();
// 获取iframe的焦点,从iframe开始打印
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf('MSIE') > 0) {
document.body.removeChild(iframe);
}
};
printTable = () => {
this.print('table1');
};
tbToExcel = () => {
// var fileName = 'file.xlsx';
// var data = [[1, 2, 3], [1, 2, 3]];
// var ws_name = 'sheet1';
// var wb = xlsx.utils.book_new();
// var ws = xlsx.utils.aoa_to_sheet(data);
// xlsx.utils.book_append_sheet(wb, ws, ws_name);
// xlsx.writeFile(wb, fileName);
var fileName = 'excel.xlsx';
var data = document.getElementById('table');
var wb = xlsx.utils.table_to_book(data, { sheet: 'SheetJS' });
xlsx.write(wb, { bookSST: true, type: 'base64' });
xlsx.writeFile(wb, fileName);
};
render() {
return (
<div>
<WhiteSpace style={{ height: 15 }} />
<div>表格打印和导出EXCEL测试</div>
<div>
<div
style={{ overflow: 'auto', width: '100%', height: '90px' }}
id="table1"
>
<table
id="table"
style={{
border: '1px solid #000',
borderCollapse: 'collapse',
width: '130%',
}}
>
<thead>
<tr>
<th>name1</th>
<th>name2</th>
<th>name3</th>
<th>name1</th>
<th>name2</th>
<th>name3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<WhiteSpace style={{ height: 15 }} />
<Button type="primary" onClick={this.printTable}>
print
</Button>
<WhiteSpace style={{ height: 15 }} />
<Button type="primary" onClick={this.tbToExcel}>
excel
</Button>
</div>
</div>
);
}
}
export default index;
https://blog.csdn.net/xiaoxiaohai0000/article/details/86569943
网友评论