Angular 5中Syncfusion EJ2 Grid实现Word导出的方法咨询
实现Syncfusion EJ2 Angular Grid的Word导出功能
首先明确:Syncfusion EJ2 Angular Grid本身没有内置的Word导出API,但我们可以通过两种可靠的方式来实现这个需求,下面结合你的现有代码详细说明:
方式一:利用Grid导出数据 + Docx.js生成Word文档
这种方式是先从Grid获取格式化的数据,再用docx库构建Word文档,优点是可以精准控制文档结构和样式。
步骤1:安装依赖
首先安装docx库:
npm install docx --save
步骤2:修改Grid配置(HTML部分)
先在toolbar中添加Word导出按钮(保持你原有列配置不变):
<ejs-grid #schoolsGrid id="schoolsGrid" [dataSource]="schools" [allowSorting]="true" [allowGrouping]="true" [allowExcelExport]="true" [toolbar]="toolbar" [allowPdfExport]="true" [allowSelection]="true" [selectionSettings]="schoolsSelectionOptions" (rowSelected)="schoolsRowSelected($event)" [allowFiltering]="true" [filterSettings]="schoolsFilteringSettings" [allowPaging]="true" [pageSettings]="schoolsPageSettings" (toolbarClick)="schoolsToolbarClick($event)" (actionComplete)="gridActionHandler($event)" width="100%"> <!-- 你的列配置保持不变 --> </ejs-grid>
步骤3:修改组件代码
更新toolbar配置并添加Word导出逻辑:
import { Component, OnInit, ViewChild } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { SchoolsService, ISchool } from '../services/schools.service'; import { GridComponent, ToolbarItems, ToolbarService, ExcelExportService, SortEventArgs, PdfExportService, RowSelectEventArgs, SelectionSettingsModel, ToolbarItem } from '@syncfusion/ej2-ng-grids'; import { ClickEventArgs } from '@syncfusion/ej2-navigations'; import { DataManager } from '@syncfusion/ej2-data'; @Component({ selector: 'app-school-list', templateUrl: './school-list.component.html', styleUrls: ['./school-list.component.less'] }) export class SchoolListComponent implements OnInit { constructor(private router: Router, private route: ActivatedRoute, private schoolsService: SchoolsService) { } public schools: ISchool[]; schoolsGridId = 'schoolsGrid'; @ViewChild('schoolsGrid') public schoolsGrid: GridComponent; public toolbar: ToolbarItems[]; public schoolsFilteringSettings = {}; public schoolsSelectionOptions: SelectionSettingsModel; ngOnInit() { // 初始化自定义工具栏,添加Word导出按钮 this.toolbar = [ { text: 'Excel Export', tooltipText: 'Excel Export', prefixIcon: 'e-excel', id: 'excelexport' }, { text: 'PDF Export', tooltipText: 'PDF Export', prefixIcon: 'e-pdf', id: 'pdfexport' }, { text: 'Word Export', tooltipText: 'Word Export', prefixIcon: 'e-word', id: 'wordexport' } ]; // 其他初始化逻辑保持不变 } schoolsToolbarClick(args: ClickEventArgs) { // 保留原有Excel/PDF导出逻辑 if (args.item.id === (this.schoolsGridId + '_excelexport')) { this.schoolsGrid.excelExport(); } if (args.item.id === (this.schoolsGridId + '_pdfexport')) { this.schoolsGrid.pdfExport(); } // 添加Word导出触发逻辑 if (args.item.id === (this.schoolsGridId + '_wordexport')) { this.exportToWord(); } } // 新增Word导出核心函数 private exportToWord() { // 获取Grid当前视图的所有数据(过滤、分页后的数据) const gridData = this.schoolsGrid.getCurrentViewRecords(); // 动态导入docx库,避免初始包体积过大 import('docx').then(({ Document, Paragraph, Table, TableRow, TableCell, TextRun, Packer }) => { const doc = new Document(); // 添加文档标题 doc.addSection({ children: [ new Paragraph({ children: [new TextRun({ text: 'School List', bold: true, size: 24 })], alignment: 'center' }) ] }); // 构建表格表头 const headerCells = [ 'School Number', 'Campus Number', 'School Name', 'ABN', 'Created' // 可根据你的列需求添加更多表头字段 ].map(headerText => new TableCell({ children: [new Paragraph(headerText)], shading: { fill: '#f0f0f0' }, bold: true })); const headerRow = new TableRow({ children: headerCells }); // 构建表格数据行 const dataRows = gridData.map(item => { const cells = [ item.schoolNumber, item.campusNumber, item.fullSchoolName, item.abn, item.created // 对应表头的字段值,空值处理为空白字符串 ].map(cellValue => new TableCell({ children: [new Paragraph(cellValue ? cellValue.toString() : '')] })); return new TableRow({ children: cells }); }); // 将表格添加到文档 doc.addSection({ children: [new Table({ rows: [headerRow, ...dataRows] })] }); // 生成并下载Word文档 Packer.toBlob(doc).then(blob => { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'schools-list.docx'; a.click(); URL.revokeObjectURL(url); }); }); } // 其他原有方法(schoolsRowSelected等)保持不变 }
方式二:将Grid导出为HTML再转换为Word
这种方式更简单,直接把Grid的HTML内容导出,利用浏览器的Word转换能力,优点是快速实现,样式接近Grid的显示效果。
修改组件中的Word导出逻辑
把上面的exportToWord函数替换为以下代码即可:
private exportToWord() { // 获取Grid的完整HTML内容 const gridElement = document.getElementById('schoolsGrid'); if (!gridElement) return; const gridHtml = gridElement.outerHTML; // 构建带样式的完整HTML文档,保证Word中显示正常 const fullHtml = ` <html> <head> <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body>${gridHtml}</body> </html> `; // 创建Blob并触发下载 const blob = new Blob([fullHtml], { type: 'application/msword' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'schools-list.doc'; a.click(); URL.revokeObjectURL(url); }
注意事项
- 如果你使用的16.1.32版本中
getCurrentViewRecords()方法不存在,可以改用this.schoolsGrid.dataSource获取全量数据,或者this.schoolsGrid.getFilteredRecords()获取过滤后的数据。 - 方式一中的
docx库支持更多样式自定义(字体、颜色、表格边框等),可根据需求调整文档结构。 - 方式二生成的是
.doc格式,方式一生成的是更现代的.docx格式,可根据需求选择。
内容的提问来源于stack exchange,提问作者Kushan Randima
相关产品推荐
相关产品推荐

