Установите пользовательское имя файла для функции экспорта представления сетки Syncfusion с помощью Angular

Я использовал это представление сетки Syncfusion. в моем приложении Angular (v6.8). Все, что я хочу добиться, - это показывать настраиваемое имя файла, когда содержимое сетки загружается в виде листа Excel. В настоящее время. после загрузки имя файла отображается как «Export.xlsx».

Я прошел через это документация (это немного другая версия), и в ней четко объясняется, как задать имя файла. К сожалению, когда я пытаюсь повторить то же самое в версии, которую использую сейчас ("@ syncfusion / ej2-ng-grids": "^ 16.1.48"), ExcelExportProperties не распознает это как допустимое свойство.

PS: Я добавляю следующий исходный код для вашей справки.

SpecialistAssessmentReportsComponent.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { DashboardService, IspecialistAssessmentReport } from '../services/dashboard.service';
import { GridComponent, ToolbarItems, PdfExportProperties, ExcelExportProperties, FilterService, ToolbarService, ExcelExportService, SortEventArgs, PdfExportService, RowSelectEventArgs, SelectionSettingsModel, ToolbarItem, GroupSettingsModel, GridLine } from '@syncfusion/ej2-ng-grids';
import { ClickEventArgs } from '@syncfusion/ej2-navigations';
import { Router } from '@angular/router';
import { FrameworkConfigService } from '../../fw/services/framework-config.service';
import { AuthService } from '../services/auth.service';


@Component({
  selector: 'app-specialist-assessment-reports',
  templateUrl: './specialist-assessment-reports.component.html',
  styleUrls: ['./specialist-assessment-reports.component.scss']
})

export class SpecialistAssessmentReportsComponent implements OnInit {

  constructor(private router: Router,
    private authService: AuthService,
    private configService: FrameworkConfigService,
    private dashboardService: DashboardService) { }

  public specialistAssessmentReportData: Array<IspecialistAssessmentReport>;

  specialistAssessmentReportGridId = 'specialistAssessmentReportGrid';
  @ViewChild('specialistAssessmentReportGrid')
  public specialistAssessmentReportGrid: GridComponent;

  public toolbar: ToolbarItems[];
  public filterSettings: Object;

  pdfexportproperties: PdfExportProperties;
  excelexportproperties: ExcelExportProperties;

  public gridFilterSettings = {}
  gridLines: GridLine = "Both";
  public gridPageSettings = {
    currentPage: 1,
    enableQueryString: true,
    pageSizes: [10, 25, 50, 100, 250],
    pageSize: 50
  };

  gridToolbarClick(args: ClickEventArgs) {
    if (args.item.id === (this.specialistAssessmentReportGridId + '_excelexport')) {
      this.specialistAssessmentReportGrid.excelExport(this.excelexportproperties);
    }
    if (args.item.id === (this.specialistAssessmentReportGridId + '_pdfexport')) {
      this.specialistAssessmentReportGrid.pdfExport(this.pdfexportproperties);
    }
  }

  ngOnInit() {
    if (!this.specialistAssessmentReportAuthorized()) {
      this.redirectToHome();
      return;
    }

    this.toolbar = ["ExcelExport", "Search"];
    this.gridFilterSettings = { type: 'Excel' };
    this.dashboardService.getspecialistAssessmentReport().subscribe(data => {
      this.specialistAssessmentReportData = data;
    });
  }

  specialistAssessmentReportAuthorized(): boolean {
    let authorized: boolean = false;

    if (this.authService.isAdministrator() || this.authService.isVsbaRFE()) {
      authorized = true;
    }
    return authorized;
  }

  redirectToHome(): void {
    this.router.navigate(['home']);
  }    
}

SpecialistAssessmentReportsComponent.html

<div class="col-12" style="min-height:660px">
  <app-sectiontitle [heading]="'Specialist assessment activity report'"></app-sectiontitle>
  <p>Use the grid below to view the specialist assessment activity report. You can filter, sort, group, export and search using the grid below.</p>
  <div class="empty20"></div>
  <!-- Grid -->
  <div id="gridContainer">
    <ejs-grid #specialistAssessmentReportGrid id="specialistAssessmentReportGrid" [dataSource]="specialistAssessmentReportData"
              [allowSorting]="true" [allowGrouping]="true" [allowExcelExport]="true" [allowTextWrap]="true"
              [toolbar]="toolbar" [allowPdfExport]="true"
              [allowFiltering]="true" [filterSettings]="gridFilterSettings"
              [allowPaging]="true" [pageSettings]="gridPageSettings"
              [gridLines]="gridLines"
              (toolbarClick)="gridToolbarClick($event)">
      <e-columns>
        <e-column width="7%" field="schoolNumber" headerText="School number" [allowGrouping]="false" [allowFiltering]="true"></e-column>
        <e-column width="20%" field="schoolName" headerText="School name" [allowGrouping]="false" [allowFiltering]="true"></e-column>
        <e-column width="20%" field="activity" headerText="Activity" [allowGrouping]="true" [allowFiltering]="true"></e-column>
        <e-column width="25%" field="additionalInfo" headerText="Additional info" [allowGrouping]="true" [allowFiltering]="true"></e-column>
        <e-column width="10%" field="createdByName" headerText="Actioned by" [allowGrouping]="true" [allowFiltering]="true"></e-column>
        <e-column width="10%" field="createdOn" headerText="Activity date" [allowGrouping]="true" [allowFiltering]="true">
          <ng-template #template let-data>
            {{data.createdOn| date:'dd/MM/y HH:mm'}}
          </ng-template>
        </e-column>
        <e-column width="8%" field="dayDifference" headerText="Days b/w activities" [allowGrouping]="true" [allowFiltering]="true"></e-column>
      </e-columns>
    </ejs-grid>
  </div>
</div>
<div class="empty40"></div>

введите описание изображения здесь

Согласно снимку выше, «fileName» не является допустимым свойством в объекте excelexportproperties. Я сделал объект как «любой» (без указания его как объекта типа «ExcelExportProperties»), как вы это сделали в своем примере кода. Затем он жаловался как «ERROR TypeError: Невозможно установить для свойства 'fileName' значение undefined»

Пожалуйста, посоветуй мне.


person Kushan Randima    schedule 13.06.2019    source источник


Ответы (1)


Мы подготовили образец по следующей ссылке на stackblitz, но мы не можем воспроизвести проблему с нашей стороны.

Пример: https://stackblitz.com/edit/angular-tlmwxa?file=package.json

Поэтому, пожалуйста, предоставьте следующую информацию, чтобы помочь вам лучше.

Поделитесь снимком экрана или видео, демонстрирующим проблему. Поделитесь подробностями трассировки стека, если вы столкнетесь с какой-либо ошибкой скрипта в окне консоли. Поделитесь полным примером кода Grid. Если возможно, попробуйте воспроизвести проблему в прилагаемом образце.

С уважением, Thavasianand S.

person S.T Anand    schedule 24.06.2019
comment
Пожалуйста, прочтите мой вопрос еще раз. Я добавил исходный код и изменил его. Большое спасибо за вашу заботу. - person Kushan Randima; 04.07.2019