参考
outerHTML:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/outerHTML
Blob:https://developer.mozilla.org/zh-CN/docs/Web/API/Blob#方法
js
* 导出excel
*/
exportTable(ele) {
// 使用outerHTML属性获取整个table元素的HTML代码(包括<table>标签),然后包装成一个完整的HTML文档,设置charset为urf-8以防止中文乱码
const html = '<html><head><meta charset="utf-8" /></head><body>' + ele.outerHTML + '</body></html>';
// 实例化一个Blob对象,其构造函数的第一个参数是包含文件内容的数组,第二个参数是包含文件类型属性的对象
const blob = new Blob([html], { type: 'application/vnd.ms-excel' });
// 利用URL.createObjectURL()方法为a元素生成blob URL
window.location.href = URL.createObjectURL(blob);
}
html
<button (click)="exportTable(table)" class="btn btn-white" type="button">导出表格</button>
<!-- 导出excel -->
<table #table style="display: none;">
<tr>
<td *ngFor="let th of theads">{{th}}</td>
</tr>
<tr *ngFor="let item of list_datas;index as i" class="mat-cell">
<td>{{pagination.offset+i+1}}</td>
<td>{{item.name}}</td>
<td [hidden]="search.params.type===1">{{item.shopkeeper}}</td>
<td [hidden]="search.params.type===1">{{item.province+item.city+item.county}}</td>
<td [hidden]="search.params.type===1">{{item.mobile}}</td>
<td *ngIf="search.params.type===0 || search.params.type===''; else elseBlock">{{item.shop_avg}}</td>
<ng-template #elseBlock>
<td>{{item.company_avg}}</td>
</ng-template>
<td>{{item.count_time}}</td>
</tr>
</table>
备注
为何只有table标签可以使用