Search results

Print the single/multiple sheets in React Spreadsheet component

15 Oct 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.tsx
datasource.tsx
index.html
app.jsx
Copied to clipboard
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { SpreadsheetComponent, SheetsDirective, SheetDirective, RangesDirective, RowsDirective, RowDirective, CellDirective, CellsDirective, protectSheet, ProtectSettings } from '@syncfusion/ej2-react-spreadsheet';
import { RangeDirective, ColumnsDirective, ColumnDirective} from '@syncfusion/ej2-react-spreadsheet';
import { budgetData, salaryData, printElement, isPrint } from './datasource';
import { DropDownButtonComponent, ItemModel } from '@syncfusion/ej2-react-splitbuttons';
import { createElement, print, getComponent } from '@syncfusion/ej2-base';

export default class App extends React.Component<{}, {}> {
       public spreadsheet: SpreadsheetComponent;
       public items: ItemModel[] = [
        {
            text: "Print"
        },
        {
            text: "Print All"
        }];
       public dataBound(): void{
        if (isPrint) {
            printElement.querySelector(".e-sheet-content").innerHTML += document
                .querySelector(".e-sheet-content").outerHTML;
            let usedRange: UsedRangeModel = this.spreadsheet.getActiveSheet().usedRange;
            let tbody: Element = printElement.querySelector('.e-sheet-content').children[this.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[] = this.spreadsheet.sheets;
            if (sheets.length - 1 === this.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[this.spreadsheet.activeSheetIndex + 1]) {
                this.spreadsheet.goTo(sheets[this.spreadsheet.activeSheetIndex + 1].name + "!A1");
                }
            }
        }
    }
   public created(): void{
        this.spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:D1');
        this.spreadsheet.cellFormat({ fontWeight: 'bold'}, 'A11:D11');
        this.spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'Salary!A1:D1');
    }
    public itemSelect(args): void {
        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;
                }
            }
        }
    }
     render() {
        return  ( <div> <DropDownButtonComponent id="element" items={this.items} select={this.itemSelect}> Print </DropDownButtonComponent>
        <SpreadsheetComponent id ='spreadsheet'
                        ref={(ssObj) => { this.spreadsheet = ssObj }} dataBound={this.dataBound.bind(this)} created={this.created.bind(this)}>
                        <SheetsDirective>
                            <SheetDirective name={"Budget"}>
                                <RangesDirective>
                                    <RangeDirective dataSource={budgetData}></RangeDirective>
                                </RangesDirective>
                                <ColumnsDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                </ColumnsDirective>
                            </SheetDirective>
                            <SheetDirective name={"Salary"}>
                                <RangesDirective>
                                    <RangeDirective dataSource={salaryData}></RangeDirective>
                                </RangesDirective>
                                <ColumnsDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                </ColumnsDirective>
                            </SheetDirective>
                        </SheetsDirective>
                    </SpreadsheetComponent> </div>);
    }
}
ReactDOM.render(<App />, document.getElementById('root'));
Copied to clipboard
import { createElement, getComponent } from '@syncfusion/ej2-base';
import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet';

export let budgetData: 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 salaryData: 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
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React Spreadsheet</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="https://cdn.syncfusion.com/ej2/material.css" rel="stylesheet" type="text/css"/>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
        body {
            overflow: hidden;
        }
        .customClass.e-cell {
                        background-color: red;
                }
    </style>
</head>

<body>
    <div id='root'>
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>
Copied to clipboard
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { SpreadsheetComponent, SheetsDirective, SheetDirective, RangesDirective } from '@syncfusion/ej2-react-spreadsheet';
import { RangeDirective, ColumnsDirective, ColumnDirective } from '@syncfusion/ej2-react-spreadsheet';
import { budgetData, salaryData, printElement, isPrint } from './datasource';
import { DropDownButtonComponent } from '@syncfusion/ej2-react-splitbuttons';
import { print, getComponent } from '@syncfusion/ej2-base';
export default class App extends React.Component {
    constructor() {
        super(...arguments);
        this.items = [
            {
                text: "Print"
            },
            {
                text: "Print All"
            }
        ];
    }
    dataBound() {
        if (isPrint) {
            printElement.querySelector(".e-sheet-content").innerHTML += document
                .querySelector(".e-sheet-content").outerHTML;
            let usedRange = this.spreadsheet.getActiveSheet().usedRange;
            let tbody = printElement.querySelector('.e-sheet-content').children[this.spreadsheet.activeSheetIndex].querySelector('tbody');
            for (let i = 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 = this.spreadsheet.sheets;
            if (sheets.length - 1 === this.spreadsheet.activeSheetIndex) {
                let count = printElement.querySelector(".e-sheet-content").childElementCount;
                if (count > 1) {
                    for (let i = 0; i < count; i++) {
                        printElement.querySelector('.e-sheet-content').children[i].getElementsByClassName('e-virtualtrack')[0].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[this.spreadsheet.activeSheetIndex + 1]) {
                    this.spreadsheet.goTo(sheets[this.spreadsheet.activeSheetIndex + 1].name + "!A1");
                }
            }
        }
    }
    created() {
        this.spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:D1');
        this.spreadsheet.cellFormat({ fontWeight: 'bold' }, 'A11:D11');
        this.spreadsheet.cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'Salary!A1:D1');
    }
    itemSelect(args) {
        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 = spreadsheet.getActiveSheet().usedRange;
            let tbody = printElement.querySelector('tbody');
            for (let i = 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].style.height = 'auto';
            print(printElement);
            printElement.querySelector(".e-sheet-content").innerHTML = '';
        }
        if (args.item.text === 'Print All') {
            let sheets = 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 = spreadsheet.getActiveSheet().usedRange;
                let tbody = printElement.querySelector('tbody');
                for (let i = 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;
                }
            }
        }
    }
    render() {
        return (<div> <DropDownButtonComponent id="element" items={this.items} select={this.itemSelect}> Print </DropDownButtonComponent>
        <SpreadsheetComponent id='spreadsheet' ref={(ssObj) => { this.spreadsheet = ssObj; }} dataBound={this.dataBound.bind(this)} created={this.created.bind(this)}>
                        <SheetsDirective>
                            <SheetDirective name={"Budget"}>
                                <RangesDirective>
                                    <RangeDirective dataSource={budgetData}></RangeDirective>
                                </RangesDirective>
                                <ColumnsDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                </ColumnsDirective>
                            </SheetDirective>
                            <SheetDirective name={"Salary"}>
                                <RangesDirective>
                                    <RangeDirective dataSource={salaryData}></RangeDirective>
                                </RangesDirective>
                                <ColumnsDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                    <ColumnDirective width={100}></ColumnDirective>
                                </ColumnsDirective>
                            </SheetDirective>
                        </SheetsDirective>
                    </SpreadsheetComponent> </div>);
    }
}
ReactDOM.render(<App />, document.getElementById('root'));