Search results

Print the single/multiple sheets in Angular Spreadsheet component

28 Jul 2021 / 3 minutes to read

You can use the print method by importing from ej2-base package. Here, the Select event in the dropdown and the dataBound event are used to print the single/multiple sheets of data. To print the single/multiple sheets, use the dropdown button and select the Print (or) Print All option. In the following sample, you can be able to print the single/multiple sheets.

Source
Preview
app.component.ts
app.module.ts
datasource.ts
main.ts
Copied to clipboard
import { Component, OnInit,ViewChild } from '@angular/core';
import { dataSource1, dataSource2, printElement, isPrint } from './datasource';
import { SpreadsheetComponent, CellModel } from '@syncfusion/ej2-angular-spreadsheet';
import { ItemModel, MenuEventArgs } from '@syncfusion/ej2-angular-splitbuttons';
import { getComponent, print } from '@syncfusion/ej2-base';

@Component({
    selector: 'app-container',
    template: `<button ejs-dropdownbutton [items]='items' content='Print' (select)='itemSelect($event)'></button>
    <ejs-spreadsheet #spreadsheet id="spreadsheet" (created)="created()" (dataBound)="dataBound()">
                <e-sheets>
                  <e-sheet name="Budget">
                    <e-ranges>
                      <e-range [dataSource]="budgetData"></e-range>
                    </e-ranges>
                    <e-columns>
                      <e-column [width]=100></e-column>
                      <e-column [width]=100></e-column>
                      <e-column [width]=100></e-column>
                      <e-column [width]=100></e-column>
                    </e-columns>
                  </e-sheet>
                  <e-sheet name="Salary">
                    <e-ranges>
                      <e-range [dataSource]="salaryData"></e-range>
                    </e-ranges>
                    <e-columns>
                      <e-column [width]=100></e-column>
                      <e-column [width]=100></e-column>
                      <e-column [width]=100></e-column>
                      <e-column [width]=100></e-column>
                      </e-columns>
                  </e-sheet>
                </e-sheets>
              </ejs-spreadsheet>`
})
export class AppComponent implements OnInit {

    @ViewChild('spreadsheet') public spreadsheetObj: SpreadsheetComponent;

    budgetData: object[] = dataSource1;

    salaryData: object[] = dataSource2;
    public items: ItemModel[] = [
    {
      text: "Print"
    },
    {
      text: "Print All"
    }];
    public itemSelect(args: MenuEventArgs) {
      let spreadsheet = getComponent(document.getElementById("spreadsheet"), "spreadsheet");
      if (args.item.text === 'Print') {
      printElement.querySelector(".e-sheet-content").innerHTML = document.querySelector(
        ".e-sheet-content"
      ).outerHTML; //  To add the spreadsheet table
      let usedRange: UsedRangeModel = spreadsheet.getActiveSheet().usedRange;
      let tbody: Element = printElement.querySelector('tbody');
      for (let i: number = tbody.getElementsByClassName('e-row').length; i >= 0; i--) {
        if (tbody.getElementsByClassName('e-row')[i] && parseInt(tbody.getElementsByClassName('e-row')[i].getAttribute('aria-rowindex')) > usedRange.rowIndex + 1) {
          tbody.getElementsByClassName('e-row')[i].remove();
        }
      }
      (printElement.querySelector('.e-sheet-content').children[0].getElementsByClassName('e-virtualtrack')[0] as HTMLElement).style.height = 'auto';
      print(printElement);
      printElement.querySelector(".e-sheet-content").innerHTML = '';
    }
    if (args.item.text === 'Print All') {
      let sheets: SheetModel[] = spreadsheet.sheets;
      if (spreadsheet.activeSheetIndex === 0) {
        printElement.querySelector(".e-sheet-content").innerHTML = document.querySelector(
          ".e-sheet-content"
        ).outerHTML; //  To add the spreadsheet table

        let usedRange: UsedRangeModel = spreadsheet.getActiveSheet().usedRange;
        let tbody: Element = printElement.querySelector('tbody');
        for (let i: number = tbody.getElementsByClassName('e-row').length; i >= 0; i--) {
          if (tbody.getElementsByClassName('e-row')[i] && parseInt(tbody.getElementsByClassName('e-row')[i].getAttribute('aria-rowindex')) > usedRange.rowIndex + 1) {
            tbody.getElementsByClassName('e-row')[i].remove();
          }
        }

        if (sheets[spreadsheet.activeSheetIndex + 1]) {
          spreadsheet.goTo(sheets[spreadsheet.activeSheetIndex + 1].name + "!A1");
          isPrint = true;
        } else {
          print(printElement);
          printElement.querySelector(".e-sheet-content").innerHTML = '';
        }
      } else {
        if (sheets[0]) {
          spreadsheet.goTo(sheets[0].name + "!A1");
          isPrint = true;
        }
      }
    }
    }
    created() {
        this.spreadsheetObj.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:D1');
        this.spreadsheetObj.cellFormat({ fontWeight: 'bold'}, 'A11:D11');
        this.spreadsheetObj.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'Salary!A1:D1');
        this.spreadsheetObj.cellFormat({ fontWeight: 'bold'}, 'Salary!A11:D11');
    }
  dataBound() {
    if (isPrint) {
      let spreadsheet = getComponent(document.getElementById("spreadsheet"), "spreadsheet");
      printElement.querySelector(
        '.e-sheet-content'
      ).innerHTML += document.querySelector('.e-sheet-content').outerHTML;
      let usedRange: UsedRangeModel = spreadsheet.getActiveSheet()
        .usedRange;
      let tbody: Element = printElement
        .querySelector('.e-sheet-content')
        .children[spreadsheet.activeSheetIndex].querySelector('tbody');
      for (
        let i: number = tbody.getElementsByClassName('e-row').length;
        i >= 0;
        i--
      ) {
        if (
          tbody.getElementsByClassName('e-row')[i] &&
          parseInt(
            tbody
              .getElementsByClassName('e-row')
              [i].getAttribute('aria-rowindex')
          ) >
            usedRange.rowIndex + 1
        ) {
          tbody.getElementsByClassName('e-row')[i].remove();
        }
      }
      let sheets: SheetModel[] = spreadsheet.sheets;
      if (sheets.length - 1 === spreadsheet.activeSheetIndex) {
        let count: number = printElement.querySelector('.e-sheet-content')
          .childElementCount;
        if (count > 1) {
          for (let i: number = 0; i < count; i++) {
            (printElement
              .querySelector('.e-sheet-content')
              .children[i].getElementsByClassName(
                'e-virtualtrack'
              )[0] as HTMLElement).style.height = 'auto';
            printElement
              .querySelector('.e-sheet-content')
              .children[i].setAttribute('style', 'page-break-after: always;');
          }
        }
        print(printElement);
        isPrint = false;
        printElement.querySelector('.e-sheet-content').innerHTML = '';
      } else {
        if (sheets[spreadsheet.activeSheetIndex + 1]) {
          spreadsheet.goTo(
            sheets[spreadsheet.activeSheetIndex + 1].name + '!A1'
          );
        }
      }
    }
  }
}
Copied to clipboard
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DropDownButtonModule } from '@syncfusion/ej2-angular-splitbuttons';
import { SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet';
import { AppComponent } from './app.component';

/**
 * Module
 */
@NgModule({
    imports: [
        BrowserModule,
        DropDownButtonModule,
        SpreadsheetAllModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
Copied to clipboard
import { createElement } from '@syncfusion/ej2-base';

/**
 * Protect sheet data source
 */
export let dataSource1: Object[] = [
    {
      'Expense Type': 'Housing',
      'Projected Cost': 7000,
      'Actual Cost': 7500,
      'Difference': -500,
    },
    {
      'Expense Type': 'Transportation',
      'Projected Cost': 500,
      'Actual Cost': 500,
      'Difference': 0,
    },
    {
      'Expense Type': 'Insurance',
      'Projected Cost': 1000,
      'Actual Cost': 1000,
      'Difference': 0,
    },
    {
      'Expense Type': 'Food',
      'Projected Cost': 2000,
      'Actual Cost': 1800,
      'Difference': 200,
    },
    {
      'Expense Type': 'Pets',
      'Projected Cost': 300,
      'Actual Cost': 200,
      'Difference': 100,
    },
    {
      'Expense Type': 'Personel Care',
      'Projected Cost': 500,
      'Actual Cost': 500,
      'Difference': 0,
    },{
      'Expense Type': 'Loan',
      'Projected Cost': 1000,
      'Actual Cost': 1000,
      'Difference': 0,
    },{
      'Expense Type': 'Tax',
      'Projected Cost': 200,
      'Actual Cost': 200,
      'Difference': 0,
    },{
      'Expense Type': 'Savings',
      'Projected Cost': 1000,
      'Actual Cost': 900,
      'Difference': 100,
    },
    {
      'Expense Type': 'Total',
      'Projected Cost': 13500,
      'Actual Cost': 13600,
      'Difference': -100,
    }
  ];

  export let dataSource2: Object[] = [
    {
      'Earnings': 'Basic',
      'Credit Amount': 20000,
      'Deductions': 'Provident Fund',
      'Debit Amount': 2400,
    },
    {
      'Earnings': 'HRA',
      'Credit Amount': 8000,
      'Deductions': 'ESI',
      'Debit Amount': 0,
    },
    {
      'Earnings': 'Special Allowance',
      'Credit Amount': 25000,
      'Deductions': 'Professional Tax',
      'Debit Amount': 200,
    },
    {
      'Earnings': 'Incentives',
      'Credit Amount': 2000,
      'Deductions': 'TDS',
      'Debit Amount': 2750,
    },
    {
      'Earnings': 'Bonus',
      'Credit Amount': 1500,
      'Deductions': 'Other Deduction',
      'Debit Amount': 0,
    },
    {
      'Earnings': 'Total Earnings',
      'Credit Amount': 56500,
      'Deductions': 'Total Deductions',
      'Debit Amount': 5350,
    }
  ];

  export let printElement: HTMLElement = createElement('div', {
    className: 'e-sheet-panel',
    innerHTML:
      '<div class="e-spreadsheet-print"></div><div class="e-sheet"><div class="e-main-panel style="height:100%" style="overflow: unset"><div class="e-sheet-content" ></div></div></div>'
  }); // creating same hierarchy of element as DOM

  export let isPrint: boolean = false;
Copied to clipboard
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';

enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);