我有一个应用程序,可以在 HTML 页面中积累来自服务器的数据。在早期版本中,我使用 JSP + JS,我的 follow 函数用于将生成的 html 数据复制到剪贴板(之后用户可以复制清晰的 HTML 并将其粘贴到 Mozila Thunderbird 程序):
function getHtml() {
var $div = $('#fullRezult');
var y = $div.html();
$("#myModal2").modal('show');
$('#paste').val(y);
}
但现在我使用 Angular 6,我的内容是通过这样的构造生成的:
<table class="table table-bordered table-sm">
<tbody>
<tr [ngClass]="{'green': el.id == 1}" *ngFor="let el of childElements">
<td>{{el.id}}</td>
<td>{{el.name}}</td>
<td>{{el.description}}</td>
<td><span class="badge badge-success">Success</span></td>
</tr>
</tbody>
</table>
那么,如何将生成的表的清晰纯 html 复制到 Angular 6 中的某个文本区域字段???
另一个选择是使用ViewEncapsulation。创建示例组件
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-mycomponent',
template: `<div class="mycomponent"><h1>It's my component!</h1><p *ngIf="!!variable">{{variable}}</p></div>`,
encapsulation: ViewEncapsulation.None
})
export class MycomponentComponent implements OnInit {
variable: 123;
constructor() { }
ngOnInit() {}
}
然后在父组件View中创建按钮来获取HTML代码
<button
type="button"
(click)="getHTML()">Get HTML</button>
最后在父组件编写方法中使用此代码从 DOM 元素获取 HTML
import { Component, OnInit, ElementRef } from '@angular/core';
...
constructor(
private el: ElementRef
)
getHTML() {
return this.el.nativeElement
.querySelector('.mycomponent')
.outerHTML
.replace(/<!--[\s\S]*?-->/g, '');
}
一种选择是定位并抓取要捕获其 HTML 的元素的外部 html。
以下是执行此操作的一种方法:
function getElementOuterHTML(element) {
if (typeof element === 'undefined' || element==null) {
return '';
}
if(!element || !element.tagName) return '';
if(element.outerHTML) return element.outerHTML;
try {
var wrapper = document.createElement('div');
wrapper.appendChild(node.cloneNode(true));
return wrapper.innerHTML;
} catch (e) { return ''; }
}
function getHtml() {
var tableNodes = document.querySelectorAll('table');
if (tableNodes.length>0) {
tableNodes.forEach(function(){
console.log(getElementOuterHTML(this));
});
}
}
或者,具体来说,您的代码可以是:
function getHtml() {
var $div = $('#fullRezult');
var y = getElementOuterHTML($div[0]);
$("#myModal2").modal('show');
$('#paste').val(y);
}
在这里,我尝试通过添加一些导出标题和搜索过滤器文本将表格数据保存为 pdf 和 excel。
导出为 Excel
exportToExcel(): void {
const customLines = [
['Search Filter'],
['Date', this.endDate],
['Search Text', this.SearchText],
['Balance > ', this.balance]
];
const headers = ['Sr. No.', 'Name', 'Balance', 'Amount'];
const excelData = [
...customLines,
headers,
...this.invoiceList.map((item, index) => [
index + 1,
`${item.LedgerName} - ${item.Place}`,
item.Balance,
item.Amount
])
];
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(excelData);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, 'PaymentWiseList');
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], { type: 'application/octet-stream' });
const url: string = window.URL.createObjectURL(data);
const a: HTMLAnchorElement = document.createElement('a');
a.href = url;
a.download = fileName + '.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
导出为PDF
exportPdf(data: any[], pdf: string) {
const customLines = [
['Search Filter'],
['Date', this.endDate],
['Search Text', this.SearchText],
['Balance > ', this.balance]
];
const documentDefinition = {
content: [
{
table: {
...customLines,
headerRows: 1,
widths: ['*', '*', '*'],
body: [
['Name', 'Balance', 'Amount'],
...data.map(item => [
item.Name + '-' + item.Place || '-',
item.Balance || '-',
item.Amount || '-'
])
]
}
}
],
layout: {
defaultBorder: false
}
};
try {
pdfMake.createPdf(documentDefinition, null, null, pdfFonts.pdfMake.vfs).download('Report.' + pdf);
} catch (error) {
console.error('Error generating PDF:', error);
}
}