Tool bar in Vue Pivotview component
11 Jun 202424 minutes to read
Toolbar option allows to access the frequently used features like switching between pivot table and pivot chart, changing chart types, conditional formatting, exporting, etc… with ease at runtime. This option can be enabled by setting the showToolbar
property in pivot table to true. The toolbar
property in pivot table accepts the collection of built-in toolbar options.
Built-in Toolbar Options
The following table shows built-in toolbar options and its actions.
Built-in Toolbar Options | Actions |
---|---|
New | Creates a new report |
Save | Saves the current report |
Save As | Save as current report |
Rename | Renames the current report |
Delete | Deletes the current report |
Load | Loads any report from the report list |
Grid | Shows pivot table |
Chart | Shows a chart in any type from the built-in list and and option to enable/disable multiple axes |
Exporting | Exports the pivot table as PDF/Excel/CSV and the pivot chart as PDF and image |
Sub-total | Shows or hides sub totals |
Grand Total | Shows or hides grand totals |
Conditional Formatting | Shows the conditional formatting pop-up to apply formatting |
Number Formatting | Shows the number formatting pop-up to apply number formatting |
Field List | Shows the fieldlist pop-up |
MDX | Shows the MDX query that was run to retrieve data from the OLAP data source. NOTE: This applies only to the OLAP data source. |
The order of toolbar options can be changed by simply moving the position of items in the ToolbarItems collection. Also if end user wants to remove any toolbar option from getting displayed, it can be simply ignored from adding into the ToolbarItems collection.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:saveReport="saveReport" :loadReport="loadReport" :fetchReport="fetchReport" :renameReport="renameReport"
:removeReport="removeReport" :newReport="newReport" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, FieldList, CalculatedField, Toolbar, PDFExport, ExcelExport, ConditionalFormatting, NumberFormatting } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const allowExcelExport = true;
const allowConditionalFormatting = true;
const allowNumberFormatting = true;
const allowPdfExport = true;
const displayOption = { view: 'Both' };
const showToolbar = true;
const allowCalculatedField = true;
const showFieldList = true;
const toolbar = [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
];
const saveReport = (args) => {
let reports = [];
let isSaved = false;
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reports = JSON.parse(localStorage.pivotviewReports);
}
if (args.report && args.reportName && args.reportName !== "") {
reports.map(function (item) {
if (args.reportName === item.reportName) {
item.report = args.report;
isSaved = true;
}
});
if (!isSaved) {
reports.push(args);
}
localStorage.pivotviewReports = JSON.stringify(reports);
}
};
const fetchReport = (args) => {
let reportCollection = [];
let reeportList = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
reeportList.push(item.reportName);
});
args.reportName = reeportList;
};
const loadReport = (args) => {
let pivotObj = document.getElementById('pivotview').ej2_instances[0];
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
args.report = item.report;
}
});
if (args.report) {
pivotObj.dataSourceSettings = JSON.parse(args.report).dataSourceSettings;
}
};
const removeReport = (args) => {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
for (let i = 0; i < reportCollection.length; i++) {
if (reportCollection[i].reportName === args.reportName) {
reportCollection.splice(i, 1);
}
}
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
};
const renameReport = (args) => {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
item.reportName = args.rename;
}
});
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
};
const newReport = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.setProperties(
{
dataSourceSettings: {
columns: [],
rows: [],
values: [],
filters: []
}
},
false
);
};
provide('pivotview', [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:saveReport="saveReport" :loadReport="loadReport" :fetchReport="fetchReport" :renameReport="renameReport"
:removeReport="removeReport" :newReport="newReport" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script>
import {
PivotViewComponent,
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
allowExcelExport: true,
allowConditionalFormatting: true,
allowNumberFormatting: true,
allowPdfExport: true,
displayOption: { view: 'Both' },
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
toolbar: [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
]
};
},
methods: {
saveReport: function (args) {
let reports = [];
let isSaved = false;
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reports = JSON.parse(localStorage.pivotviewReports);
}
if (args.report && args.reportName && args.reportName !== "") {
reports.map(function (item) {
if (args.reportName === item.reportName) {
item.report = args.report;
isSaved = true;
}
});
if (!isSaved) {
reports.push(args);
}
localStorage.pivotviewReports = JSON.stringify(reports);
}
},
fetchReport: function (args) {
let reportCollection = [];
let reeportList = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
reeportList.push(item.reportName);
});
args.reportName = reeportList;
},
loadReport: function (args) {
let pivotObj = document.getElementById('pivotview').ej2_instances[0];
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
args.report = item.report;
}
});
if (args.report) {
pivotObj.dataSourceSettings = JSON.parse(args.report).dataSourceSettings;
}
},
removeReport: function (args) {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
for (let i = 0; i < reportCollection.length; i++) {
if (reportCollection[i].reportName === args.reportName) {
reportCollection.splice(i, 1);
}
}
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
},
renameReport: function (args) {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
item.reportName = args.rename;
}
});
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
},
newReport: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.setProperties(
{
dataSourceSettings: {
columns: [],
rows: [],
values: [],
filters: []
}
},
false
);
},
},
provide: {
pivotview: [FieldList, CalculatedField, Toolbar, PDFExport, ExcelExport, ConditionalFormatting, NumberFormatting]
}
}
</script>
<style>@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";</style>
Show desired chart types in the dropdown menu
By default, all chart types are displayed in the dropdown menu included in the toolbar. However, based on the request for an application, we may need to show selective chart types on our own. This can be achieved using the chartTypes
property. To know more about supporting chart types, click here
.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :height="height"
:showToolbar="showToolbar" :toolbar="toolbar" :displayOption="displayOption" :chartTypes="chartTypes">
</ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, Toolbar, } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const displayOption = { view: 'Both' };
const showToolbar = true;
const chartTypes = ['Column', 'Bar', 'Line', 'Area'];
const toolbar = ['Grid', 'Chart'];
provide('pivotview', [
Toolbar,
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :height="height"
:showToolbar="showToolbar" :toolbar="toolbar" :displayOption="displayOption" :chartTypes="chartTypes">
</ejs-pivotview>
</div>
</template>
<script>
import { PivotViewComponent, Toolbar, } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
displayOption: { view: 'Both' },
showToolbar: true,
chartTypes: ['Column', 'Bar', 'Line', 'Area'],
toolbar: ['Grid', 'Chart']
};
},
provide: {
pivotview: [Toolbar]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";</style>
Switch the chart to multiple axes
In the chart, the user can switch from single axis to multiple axes with the help of the built-in checkbox available inside the chart type dropdown menu in the toolbar. For more information refer here
.
There are three modes available in Multiple Axis option: Stacked
, Single
and Combined
. The modes can be changed using “Multiple Axis Mode” drop-down list which appears while clicking the More… option.
Show or hide legend
In the chart, legend can be shown or hidden dynamically with the help of the built-in option available in the chart type drop-down menu.
By default, the legend is not be visible for the accumulation chart types like pie, doughnut, pyramid, and funnel. Users can enable or disable using the built-in checkbox option.
Adding custom option to the toolbar
In addition to the existing built-in toolbar items, new toolbar item(s) may also be included. This can be achieved by using the toolbarRender
event. The action of the new toolbar item(s) can also be defined within this event.
The new toolbar item(s) can be added to the desired position in the toolbar using the
splice
option.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbar="toolbar" :toolbarRender="beforeToolbarRender"
:displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, Toolbar, } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const displayOption = { view: 'Both' };
const showToolbar = true;
const toolbar = [
"Expand/Collpase",
];
const beforeToolbarRender = (args) => {
args.customToolbar.splice(12, 0, {
prefixIcon: 'e-pivotview-expand e-icons', tooltipText: 'Expand/Collapse',
click: toolbarClicked.bind(),
});
};
const toolbarClicked = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = !pivotGridObj.dataSourceSettings.expandAll;
};
provide('pivotview', [
Toolbar,
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbar="toolbar" :toolbarRender="beforeToolbarRender"
:displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script>
import { PivotViewComponent, Toolbar, } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
displayOption: { view: 'Both' },
showToolbar: true,
toolbar: [
"Expand/Collpase",
]
};
},
methods: {
beforeToolbarRender: function (args) {
args.customToolbar.splice(12, 0, {
prefixIcon: 'e-pivotview-expand e-icons', tooltipText: 'Expand/Collapse',
click: this.toolbarClicked.bind(this),
});
},
toolbarClicked: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = !pivotGridObj.dataSourceSettings.expandAll;
}
},
provide: {
pivotview: [Toolbar]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
In the above topic, we have seen how to add an icon as one of the toolbar item in toolbar panel. In the next topic, we are going to see how to frame the entire toolbar panel and how to add a custom control in it.
Toolbar Template
It allows to customize the toolbar panel by using template option. It allows any custom control to be used as one of the toolbar item inside the toolbar panel. It can be achieved by two ways,
Here, the entire toolbar panel can be framed in HTML elements that are appended at the top of the pivot table. The id of the HTML element needs to be set in the toolbarTemplate
property in-order to map it to the pivot table.
<template>
<div id="app">
<div id="template">
<div>
<ejs-button id="expandall" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="expandAll">EXPAND
ALL</ejs-button>
<ejs-button id="collapseall" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="collapseAll">COLLAPSE
ALL</ejs-button>
</div>
</div>
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbarTemplate="toolbarTemplate"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { ButtonComponent as EjsButton } from '@syncfusion/ej2-vue-buttons';
import { PivotViewComponent as EjsPivotview, Toolbar, } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const showToolbar = true;
const toolbarTemplate = '#template';
const isPrimary = true;
const expandAll = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = true;
};
const collapseAll = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = false;
};
provide('pivotview', [
Toolbar,
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<div id="template">
<div>
<ejs-button id="expandall" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="expandAll">EXPAND ALL</ejs-button>
<ejs-button id="collapseall" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="collapseAll">COLLAPSE
ALL</ejs-button>
</div>
</div>
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbarTemplate="toolbarTemplate"> </ejs-pivotview>
</div>
</template>
<script>
import { ButtonComponent } from '@syncfusion/ej2-vue-buttons';
import { PivotViewComponent, Toolbar, } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-button": ButtonComponent,
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
showToolbar: true,
toolbarTemplate: '#template',
isPrimary: true
};
},
methods: {
expandAll: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = true;
},
collapseAll: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = false;
}
},
provide: {
pivotview: [
Toolbar,
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
Another option allows to frame a custom toolbar item using HTML elements and include in the toolbar panel at the desired position. The custom toolbar items can be declared as control instance or element id in the toolbar
property in pivot table.
<template>
<div id="app">
<ejs-button id="enablertl" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="enableRtl">ENABLE RTL</ejs-button>
<ejs-button id="disablertl" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="disableRtl">DISABLE RTL</ejs-button>
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbar="toolbar"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { ButtonComponent as EjsButton } from '@syncfusion/ej2-vue-buttons';
import { PivotViewComponent as EjsPivotview, Toolbar } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const showToolbar = true;
const toolbar = [{ template: '#enablertl' }, { template: '#disablertl' }];
const isPrimary = true;
const enableRtl = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.enableRtl = true;
};
const disableRtl = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.enableRtl = false;
};
provide('pivotview', [
Toolbar,
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-button id="enablertl" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="enableRtl">ENABLE RTL</ejs-button>
<ejs-button id="disablertl" :isPrimary="isPrimary" cssClass='e-flat' v-on:click="disableRtl">DISABLE RTL</ejs-button>
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbar="toolbar"> </ejs-pivotview>
</div>
</template>
<script>
import { ButtonComponent } from '@syncfusion/ej2-vue-buttons';
import { PivotViewComponent, Toolbar } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-button": ButtonComponent,
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
showToolbar: true,
toolbar: [{ template: '#enablertl' }, { template: '#disablertl' }],
isPrimary: true
};
},
methods: {
enableRtl: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.enableRtl = true;
},
disableRtl: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.enableRtl = false;
}
},
provide: {
pivotview: [
Toolbar,
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
Note: For both options, the actions for the toolbar template items can be defined in the event
toolbarClick
. Also, if the toolbar item is a custom control then its built-in events can also be accessed.
Save and load report as a JSON file
The current pivot report can be saved as a JSON file in the desired path and loaded back to the pivot table at any time.
<template>
<div id="app">
<div>
<ejs-pivotview id="pivotview" :dataSourceSettings="dataSourceSettings" :height="height"
:showFieldList="showFieldList" :dataBound="ondataBound"></ejs-pivotview>
</div>
<a id="save" class="btn btn-primary">Save</a>
<div class="fileUpload btn btn-primary"><span>Load</span><input id="files" type="file" class="upload" /></div>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, FieldList } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
expandAll: false,
drilledMembers: [{ name: 'Country', items: ['France'] }],
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const showFieldList = true;
const ondataBound = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
var dataSource = JSON.parse(pivotGridObj.getPersistData()).dataSourceSettings.dataSource;
var a = document.getElementById('save');
var mime_type = 'application/octet-stream'; // text/html, image/png, et c
a.setAttribute('download', 'pivot.JSON');
a.href = 'data:' + mime_type + ';base64,' + btoa(JSON.stringify(dataSource) || '');
document.getElementById('files').addEventListener('change', readBlob, false);
};
const readBlob = () => {
var files = document.getElementById('load').files;
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSource = JSON.parse(evt.target.result);
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
provide('pivotview', [FieldList]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
@import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
<template>
<div id="app">
<div>
<ejs-pivotview id="pivotview" :dataSourceSettings="dataSourceSettings" :height="height"
:showFieldList="showFieldList" :dataBound="ondataBound"></ejs-pivotview>
</div>
<a id="save" class="btn btn-primary">Save</a>
<div class="fileUpload btn btn-primary"><span>Load</span><input id="files" type="file" class="upload" /></div>
</div>
</template>
<script>
import { PivotViewComponent, FieldList } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
expandAll: false,
drilledMembers: [{ name: 'Country', items: ['France'] }],
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
showFieldList: true
}
},
methods: {
ondataBound: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
var dataSource = JSON.parse(pivotGridObj.getPersistData()).dataSourceSettings.dataSource;
var a = document.getElementById('save');
var mime_type = 'application/octet-stream'; // text/html, image/png, et c
a.setAttribute('download', 'pivot.JSON');
a.href = 'data:' + mime_type + ';base64,' + btoa(JSON.stringify(dataSource) || '');
document.getElementById('files').addEventListener('change', this.readBlob, false);
},
readBlob: function () {
var files = document.getElementById('load').files;
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSource = JSON.parse(evt.target.result);
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
},
provide: {
pivotview: [FieldList]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
@import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
Save and load reports to a SQL database
SQL Server is a relational database management system (RDBMS) that can be used to store and manage large amounts of data. In this topic, we will see how to save, save as, rename, load, delete, and add reports between a SQL Server database and a Vue Pivot Table at runtime.
Create a Web API service to connect to a SQL Server database
1. Open Visual Studio and create an ASP.NET Core Web App project type, naming it MyWebService. To create an ASP.NET Core Web application, follow the document link.
2. To connect a SQL Server database using the Microsoft SqlClient in our application, we need to install the Microsoft.Data.SqlClient NuGet package. To do so, open the NuGet package manager of the project solution, search for the package Microsoft.Data.SqlClient and install it.
3. Under the Controllers folder, create a Web API controller (aka, PivotController.cs) file that aids in data communication with the Pivot Table.
4. In the Web API Controller (aka, PivotController), the OpenConnection method is used to connect to the SQL database. The GetDataTable method then processes the specified SQL query string, retrieves data from the database, and converts it into a DataTable using SqlCommand and SqlDataAdapter. This DataTable can be used to retrieve saved reports and modify them further as shown in the code block below.
[PivotController.cs]
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
namespace MyWebService.Controllers
{
[ApiController]
[Route("[controller]")]
public class PivotController : ControllerBase
{
[HttpPost]
[Route("Pivot/SaveReport")]
public void SaveReport([FromBody] Dictionary<string, string> reportArgs)
{
SaveReportToDB(reportArgs["reportName"], reportArgs["report"]);
}
[HttpPost]
[Route("Pivot/FetchReport")]
public IActionResult FetchReport()
{
return Ok((FetchReportListFromDB()));
}
[HttpPost]
[Route("Pivot/LoadReport")]
public IActionResult LoadReport([FromBody] Dictionary<string, string> reportArgs)
{
return Ok((LoadReportFromDB(reportArgs["reportName"])));
}
[HttpPost]
[Route("Pivot/RemoveReport")]
public void RemoveReport([FromBody] Dictionary<string, string> reportArgs)
{
RemoveReportFromDB(reportArgs["reportName"]);
}
[HttpPost]
[Route("Pivot/RenameReport")]
public void RenameReport([FromBody] RenameReportDB reportArgs)
{
RenameReportInDB(reportArgs.ReportName, reportArgs.RenameReport, reportArgs.isReportExists);
}
public class RenameReportDB
{
public string ReportName { get; set; }
public string RenameReport { get; set; }
public bool isReportExists { get; set; }
}
private void SaveReportToDB(string reportName, string report)
{
SqlConnection sqlConn = OpenConnection();
bool isDuplicate = true;
SqlCommand cmd1 = null;
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
isDuplicate = false;
cmd1 = new SqlCommand("update ReportTable set Report=@Report where ReportName like @ReportName", sqlConn);
}
}
if (isDuplicate)
{
cmd1 = new SqlCommand("insert into ReportTable (ReportName,Report) Values(@ReportName,@Report)", sqlConn);
}
cmd1.Parameters.AddWithValue("@ReportName", reportName);
cmd1.Parameters.AddWithValue("@Report", report.ToString());
cmd1.ExecuteNonQuery();
sqlConn.Close();
}
private string LoadReportFromDB(string reportName)
{
SqlConnection sqlConn = OpenConnection();
string report = string.Empty;
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
report = (string)row["Report"];
break;
}
}
sqlConn.Close();
return report;
}
private List<string> FetchReportListFromDB()
{
SqlConnection sqlConn = OpenConnection();
List<string> reportNames = new List<string>();
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if (!string.IsNullOrEmpty(row["ReportName"] as string))
{
reportNames.Add(row["ReportName"].ToString());
}
}
sqlConn.Close();
return reportNames;
}
private void RenameReportInDB(string reportName, string renameReport, bool isReportExists)
{
SqlConnection sqlConn = OpenConnection();
SqlCommand cmd1 = null;
if (isReportExists)
{
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
cmd1 = new SqlCommand("delete from ReportTable where ReportName like '%" + reportName + "%'", sqlConn);
break;
}
}
cmd1.ExecuteNonQuery();
}
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
cmd1 = new SqlCommand("update ReportTable set ReportName=@RenameReport where ReportName like '%" + reportName + "%'", sqlConn);
break;
}
}
cmd1.Parameters.AddWithValue("@RenameReport", renameReport);
cmd1.ExecuteNonQuery();
sqlConn.Close();
}
private void RemoveReportFromDB(string reportName)
{
SqlConnection sqlConn = OpenConnection();
SqlCommand cmd1 = null;
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
cmd1 = new SqlCommand("delete from ReportTable where ReportName like '%" + reportName + "%'", sqlConn);
break;
}
}
cmd1.ExecuteNonQuery();
sqlConn.Close();
}
private SqlConnection OpenConnection()
{
// Replace with your own connection string.
string connectionString = @"<Enter your valid connection string here>";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
return sqlConn;
}
private DataTable GetDataTable(SqlConnection sqlConn)
{
string xquery = "select * from ReportTable";
SqlCommand cmd = new SqlCommand(xquery, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
5. When you run the app, it will be hosted at https://localhost:44313
. You can use the hosted URL to save and load reports in the SQL database from the Pivot Table.
Further, let us explore more on how to save, load, rename, delete, and add reports using the built-in toolbar options via Web API controller (aka, PivotController) one-by-one.
Saving a report
When you select the “Save a report” option from the toolbar, the saveReport event is triggered. In this event, an AJAX request is made to the Web API controller’s SaveReport method, passing the name of the current report and the current report, which you can use to check and save in the SQL database.
For example, the report shown in the following code snippet will be passed to the SaveReport method along with the report name “Sample Report” and saved in the SQL database.
[App.vue]
<template>
<div>
<div class="control-section" style="overflow: auto">
<div class="content-wrapper">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings"
:width="width" :allowExcelExport="allowExcelExport"
:allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowCalculatedField="allowCalculatedField"
:showFieldList="showFieldList" :toolbar="toolbar" :saveReport="saveReport" :loadReport="loadReport"
:fetchReport="fetchReport" :renameReport="renameReport" :removeReport="removeReport" :newReport="newReport"
:toolbarRender="beforeToolbarRender" :displayOption="displayOption"
:chartSettings="chartSettings"></ejs-pivotview>
</div>
</div>
</div>
</template>
<script>
import Vue from "vue";
import {
PivotViewPlugin, FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { enableRipple } from "@syncfusion/ej2-base";
enableRipple(false);
Vue.use(PivotViewPlugin);
export default {
data() {
return {
dataSourceSettings: {
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
dataSource: data,
expandAll: false,
filters: [],
formatSettings: [{ name: 'Amount', format: 'C0' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }]
},
displayOption: { view: "Both" },
chartSettings: {
value: "Amount",
enableExport: true,
chartSeries: { type: "Column", animation: { enable: false } },
enableMultipleAxis: false,
},
toolbar: [
"New", "Save", "SaveAs", "Rename", "Remove", "Load", "Grid", "Chart", "MDX", "Export", "SubTotal", "GrandTotal",
"ConditionalFormatting", "FieldList"
],
allowExcelExport: true,
allowConditionalFormatting: true,
allowPdfExport: true,
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
width: "700",
};
},
methods: {
saveReport(args) {
var report = JSON.parse(args.report);
report.dataSourceSettings.dataSource = [];
fetch('https://localhost:44313/Pivot/SaveReport', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ reportName: args.reportName, report: JSON.stringify(report) })
}).then(response => {
this.fetchReport(args);
});
}
},
provide: {
pivotview: [FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting]
}
}
[PivotController.cs]
namespace MyWebApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class PivotController : ControllerBase
{
[HttpPost]
[Route("Pivot/SaveReport")]
public void SaveReport([FromBody] Dictionary<string, string> reportArgs)
{
SaveReportToDB(reportArgs["reportName"], reportArgs["report"]);
}
private void SaveReportToDB(string reportName, string report)
{
SqlConnection sqlConn = OpenConnection();
bool isDuplicate = true;
SqlCommand cmd1 = null;
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
isDuplicate = false;
cmd1 = new SqlCommand("update ReportTable set Report=@Report where ReportName like @ReportName", sqlConn);
}
}
if (isDuplicate)
{
cmd1 = new SqlCommand("insert into ReportTable (ReportName,Report) Values(@ReportName,@Report)", sqlConn);
}
cmd1.Parameters.AddWithValue("@ReportName", reportName);
cmd1.Parameters.AddWithValue("@Report", report.ToString());
cmd1.ExecuteNonQuery();
sqlConn.Close();
}
private SqlConnection OpenConnection()
{
// Replace with your own connection string.
string connectionString = @"<Enter your valid connection string here>";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
return sqlConn;
}
private DataTable GetDataTable(SqlConnection sqlConn)
{
string xquery = "select * from ReportTable";
SqlCommand cmd = new SqlCommand(xquery, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
In the meantime, you can save a duplicate of the current report to the SQL Server database with a different name by selecting “Save as current report” from the toolbar. The saveReport event will then be triggered with the new report name “Sample Report 1” and the current report. You can save them to the SQL Server database after passing them to the Web API service, as mentioned above.
Loading a report
When you select the dropdown menu item from the toolbar, the loadReport event is triggered. In this event, an AJAX request is made to the LoadReport method of the Web API controller, passing the name of the selected report. The method uses this information to search for the report in the SQL database, fetch it, and load it into the pivot table.
For example, if the report name “Sample Report 1” is selected from a dropdown menu and passed, the LoadReport method will use that name to search for the report in the SQL database, retrieve it, and then load it into the pivot table.
[App.vue]
<template>
<div>
<div class="control-section" style="overflow: auto">
<div class="content-wrapper">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings"
:width="width" :allowExcelExport="allowExcelExport"
:allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowCalculatedField="allowCalculatedField"
:showFieldList="showFieldList" :toolbar="toolbar" :saveReport="saveReport" :loadReport="loadReport"
:fetchReport="fetchReport" :renameReport="renameReport" :removeReport="removeReport" :newReport="newReport"
:toolbarRender="beforeToolbarRender" :displayOption="displayOption"
:chartSettings="chartSettings"></ejs-pivotview>
</div>
</div>
</div>
</template>
<script>
import Vue from "vue";
import {
PivotViewPlugin, FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { enableRipple } from "@syncfusion/ej2-base";
enableRipple(false);
Vue.use(PivotViewPlugin);
export default {
data() {
return {
dataSourceSettings: {
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
dataSource: data,
expandAll: false,
filters: [],
formatSettings: [{ name: 'Amount', format: 'C0' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }]
},
displayOption: { view: "Both" },
chartSettings: {
value: "Amount",
enableExport: true,
chartSeries: { type: "Column", animation: { enable: false } },
enableMultipleAxis: false,
},
toolbar: [
"New", "Save", "SaveAs", "Rename", "Remove", "Load", "Grid", "Chart", "MDX", "Export", "SubTotal", "GrandTotal",
"ConditionalFormatting", "FieldList"
],
allowExcelExport: true,
allowConditionalFormatting: true,
allowPdfExport: true,
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
width: "700",
};
},
methods: {
loadReport(args) {
fetch('https://localhost:44313/Pivot/LoadReport', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ reportName: args.reportName })
}).then(res => res.json())
.then(response => {
if (response) {
var report = JSON.parse(response);
var pivotTableObj = (this.$refs.pivotview).ej2Instances;
report.dataSourceSettings.dataSource = pivotTableObj.dataSourceSettings.dataSource;
pivotTableObj.dataSourceSettings = report.dataSourceSettings;
}
});
}
},
provide: {
pivotview: [FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting]
}
}
[PivotController.cs]
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
namespace MyWebApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class PivotController : ControllerBase
{
[HttpPost]
[Route("Pivot/LoadReport")]
public IActionResult LoadReport([FromBody] Dictionary<string, string> reportArgs)
{
return Ok((LoadReportFromDB(reportArgs["reportName"])));
}
private string LoadReportFromDB(string reportName)
{
SqlConnection sqlConn = OpenConnection();
string report = string.Empty;
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
report = (string)row["Report"];
break;
}
}
sqlConn.Close();
return report;
}
private SqlConnection OpenConnection()
{
// Replace with your own connection string.
string connectionString = @"<Enter your valid connection string here>";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
return sqlConn;
}
private DataTable GetDataTable(SqlConnection sqlConn)
{
string xquery = "select * from ReportTable";
SqlCommand cmd = new SqlCommand(xquery, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Renaming a report
When you select the “Rename a current report” option from the toolbar, the renameReport event is triggered. In this event, an AJAX request is made to the RenameReport method of the Web API controller, passing the current and new report names, where you can use the current report name to identify the report and resave it with the new report name in the SQL database.
For example, if we rename the current report from “Sample Report 1” to “Sample Report 2”, both “Sample Report 1” and “Sample Report 2” will be passed to the RenameReport method, which will rename the current report with the new report name “Sample Report 2” in the SQL database.
[App.vue]
<template>
<div>
<div class="control-section" style="overflow: auto">
<div class="content-wrapper">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings"
:width="width" :allowExcelExport="allowExcelExport"
:allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowCalculatedField="allowCalculatedField"
:showFieldList="showFieldList" :toolbar="toolbar" :saveReport="saveReport" :loadReport="loadReport"
:fetchReport="fetchReport" :renameReport="renameReport" :removeReport="removeReport" :newReport="newReport"
:toolbarRender="beforeToolbarRender" :displayOption="displayOption"
:chartSettings="chartSettings"></ejs-pivotview>
</div>
</div>
</div>
</template>
<script>
import Vue from "vue";
import {
PivotViewPlugin, FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { enableRipple } from "@syncfusion/ej2-base";
enableRipple(false);
Vue.use(PivotViewPlugin);
export default {
data() {
return {
dataSourceSettings: {
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
dataSource: data,
expandAll: false,
filters: [],
formatSettings: [{ name: 'Amount', format: 'C0' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }]
},
displayOption: { view: "Both" },
chartSettings: {
value: "Amount",
enableExport: true,
chartSeries: { type: "Column", animation: { enable: false } },
enableMultipleAxis: false,
},
toolbar: [
"New", "Save", "SaveAs", "Rename", "Remove", "Load", "Grid", "Chart", "MDX", "Export", "SubTotal", "GrandTotal",
"ConditionalFormatting", "FieldList"
],
allowExcelExport: true,
allowConditionalFormatting: true,
allowPdfExport: true,
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
width: "700",
};
},
methods: {
renameReport(args) {
fetch('https://localhost:44313/Pivot/RenameReport', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ reportName: args.reportName, renameReport: args.rename, isReportExists: args.isReportExists })
}).then(response => {
this.fetchReport(args);
});
}
},
provide: {
pivotview: [FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting]
}
}
[PivotController.cs]
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
namespace MyWebApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class PivotController : ControllerBase
{
[HttpPost]
[Route("Pivot/RenameReport")]
public void RenameReport([FromBody] RenameReportDB reportArgs)
{
RenameReportInDB(reportArgs.ReportName, reportArgs.RenameReport, reportArgs.isReportExists);
}
public class RenameReportDB
{
public string ReportName { get; set; }
public string RenameReport { get; set; }
public bool isReportExists { get; set; }
}
private void RenameReportInDB(string reportName, string renameReport, bool isReportExists)
{
SqlConnection sqlConn = OpenConnection();
SqlCommand cmd1 = null;
if (isReportExists)
{
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
cmd1 = new SqlCommand("delete from ReportTable where ReportName like '%" + reportName + "%'", sqlConn);
break;
}
}
cmd1.ExecuteNonQuery();
}
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
cmd1 = new SqlCommand("update ReportTable set ReportName=@RenameReport where ReportName like '%" + reportName + "%'", sqlConn);
break;
}
}
cmd1.Parameters.AddWithValue("@RenameReport", renameReport);
cmd1.ExecuteNonQuery();
sqlConn.Close();
}
private SqlConnection OpenConnection()
{
// Replace with your own connection string.
string connectionString = @"<Enter your valid connection string here>";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
return sqlConn;
}
private DataTable GetDataTable(SqlConnection sqlConn)
{
string xquery = "select * from ReportTable";
SqlCommand cmd = new SqlCommand(xquery, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Deleting a report
When you select the “Delete a current report” option from the toolbar, the removeReport event is triggered. In this event, an AJAX request is made to the RemoveReport method of the Web API controller, passing the current report name to identify and delete the appropriate report from the SQL database.
NOTE
- If the current report n from the pivot table is deleted, the pivot table will automatically load the last report from the report list.
- When a report is removed from a pivot table with only one report, the SQL database refreshes; however, the pivot table will continue to show the removed report until a new report is added to the pivot table.
For example, if we delete the current report “Sample Report 2” from the pivot table, the current report name “Sample Report 2” is passed to the RemoveReport method, which allows you to identify and delete the report from the SQL database.
[App.vue]
<template>
<div>
<div class="control-section" style="overflow: auto">
<div class="content-wrapper">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings"
:width="width" :allowExcelExport="allowExcelExport"
:allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowCalculatedField="allowCalculatedField"
:showFieldList="showFieldList" :toolbar="toolbar" :saveReport="saveReport" :loadReport="loadReport"
:fetchReport="fetchReport" :renameReport="renameReport" :removeReport="removeReport" :newReport="newReport"
:toolbarRender="beforeToolbarRender" :displayOption="displayOption"
:chartSettings="chartSettings"></ejs-pivotview>
</div>
</div>
</div>
</template>
<script>
import Vue from "vue";
import {
PivotViewPlugin, FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { enableRipple } from "@syncfusion/ej2-base";
enableRipple(false);
Vue.use(PivotViewPlugin);
export default {
data() {
return {
dataSourceSettings: {
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
dataSource: data,
expandAll: false,
filters: [],
formatSettings: [{ name: 'Amount', format: 'C0' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }]
},
displayOption: { view: "Both" },
chartSettings: {
value: "Amount",
enableExport: true,
chartSeries: { type: "Column", animation: { enable: false } },
enableMultipleAxis: false,
},
toolbar: [
"New", "Save", "SaveAs", "Rename", "Remove", "Load", "Grid", "Chart", "MDX", "Export", "SubTotal", "GrandTotal",
"ConditionalFormatting", "FieldList"
],
allowExcelExport: true,
allowConditionalFormatting: true,
allowPdfExport: true,
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
width: "700",
};
},
methods: {
removeReport(args) {
fetch('https://localhost:44313/Pivot/RemoveReport', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ reportName: args.reportName })
}).then(response => {
this.fetchReport(args);
});
}
},
provide: {
pivotview: [FieldList, CalculatedField, Toolbar, ConditionalFormatting, NumberFormatting]
}
}
[PivotController.cs]
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System.Data;
namespace MyWebApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class PivotController : ControllerBase
{
[HttpPost]
[Route("Pivot/RemoveReport")]
public void RemoveReport([FromBody] Dictionary<string, string> reportArgs)
{
RemoveReportFromDB(reportArgs["reportName"]);
}
private void RemoveReportFromDB(string reportName)
{
SqlConnection sqlConn = OpenConnection();
SqlCommand cmd1 = null;
foreach (DataRow row in GetDataTable(sqlConn).Rows)
{
if ((row["ReportName"] as string).Equals(reportName))
{
cmd1 = new SqlCommand("delete from ReportTable where ReportName like '%" + reportName + "%'", sqlConn);
break;
}
}
cmd1.ExecuteNonQuery();
sqlConn.Close();
}
private SqlConnection OpenConnection()
{
// Replace with your own connection string.
string connectionString = @"<Enter your valid connection string here>";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
return sqlConn;
}
private DataTable GetDataTable(SqlConnection sqlConn)
{
string xquery = "select * from ReportTable";
SqlCommand cmd = new SqlCommand(xquery, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Adding a report
When you select the “Create a new report” option from the toolbar, the newReport event is triggered, followed by the saveReport event. To save this new report to the SQL database, use the saveReport event triggered later, and then follow the save report briefing in the preceding topic.
Limitations with respect to report manipulation
Below points need to be considered when saving the report to SQL Server database.
- Data source: Both raw data and aggregated data won’t be saved and loaded from the database.
- Hyperlinks: Option to link external facts via pivot table cells won’t be saved and loaded from the database.
- The pivot table should always load reports from the SQL database based on the data source that is currently bound to it.
In this GitHub repository, you can find our Vue Pivot Table sample and ASP.NET Core Web Application to save and load reports from SQL Server database.
Events
FetchReport
The event fetchReport
is triggered when dropdown list is clicked in the toolbar in-order to retrieve and populate saved reports. It has following parameter - reportName
. This event allows user to fetch the report names from local storage and populate the dropdown list.
LoadReport
The event loadReport
is triggered when a report is selected from the dropdown list in the toolbar. It has following parameters - report
and reportName
. This event allows user to load the selected report to the pivot table.
NewReport
The event newReport
is triggered when the new report icon is clicked in the toolbar. It has following parameter - report
. This event allows user to create new report and add to the report list.
RenameReport
The event renameReport
is triggered when rename report icon is clicked in the toolbar. It has following parameters - rename
, report
and reportName
. This event allows user to rename the selected report from the report list.
RemoveReport
The event removeReport
is triggered when remove report icon is clicked in the toolbar. It has following parameters - report
and reportName
. This event allows user to remove the selected report from the report list.
SaveReport
The event saveReport
is triggered when save report icon is clicked in the toolbar. It has following parameters - report
and reportName
. This event allows user to save the altered report to the report list.
ToolbarRender
The toolbarRender
event is triggered when the toolbar is rendered. It has the customToolbar
parameter. This event helps to customize the built-in toolbar items and to include new toolbar item(s)
.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbar="toolbar" :toolbarRender="beforeToolbarRender"
:displayOption="displayOption" :saveReport="saveReport" :showFieldList="showFieldList"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, Toolbar, FieldList } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const displayOption = { view: 'Both' };
const showToolbar = true;
const showFieldList = true;
const toolbar = [
"Save",
"Export",
"FieldList"
];
const saveReport = (args) => {
let reports = [];
let isSaved = false;
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reports = JSON.parse(localStorage.pivotviewReports);
}
if (args.report && args.reportName && args.reportName !== "") {
reports.map(function (item) {
if (args.reportName === item.reportName) {
item.report = args.report;
isSaved = true;
}
});
if (!isSaved) {
reports.push(args);
}
localStorage.pivotviewReports = JSON.stringify(reports);
}
};
const beforeToolbarRender = (args) => {
args.customToolbar.splice(2, 0, {
prefixIcon: 'e-rename-report e-icons', tooltipText: 'Custom Button',
click: customButton.bind()
});
args.customToolbar.splice(3, 0, {
prefixIcon: 'e-pivotview-expand e-icons', tooltipText: 'Expand/Collapse',
click: toolbarClicked.bind()
});
args.customToolbar[0].align = "Left";
args.customToolbar[1].align = "Center";
args.customToolbar[2].align = "Right";
};
const customButton = () => {
// Here you can customize the click event for custom button
};
const toolbarClicked = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = !pivotGridObj.dataSourceSettings.expandAll;
};
provide('pivotview', [
Toolbar, FieldList
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :showToolbar="showToolbar" :toolbar="toolbar" :toolbarRender="beforeToolbarRender"
:displayOption="displayOption" :saveReport="saveReport" :showFieldList="showFieldList"> </ejs-pivotview>
</div>
</template>
<script>
import { PivotViewComponent, Toolbar, FieldList } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
displayOption: { view: 'Both' },
showToolbar: true,
showFieldList: true,
toolbar: [
"Save",
"Export",
"FieldList"
]
};
},
methods: {
saveReport: function (args) {
let reports = [];
let isSaved = false;
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reports = JSON.parse(localStorage.pivotviewReports);
}
if (args.report && args.reportName && args.reportName !== "") {
reports.map(function (item) {
if (args.reportName === item.reportName) {
item.report = args.report;
isSaved = true;
}
});
if (!isSaved) {
reports.push(args);
}
localStorage.pivotviewReports = JSON.stringify(reports);
}
},
beforeToolbarRender: function (args) {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
args.customToolbar.splice(2, 0, {
prefixIcon: 'e-rename-report e-icons', tooltipText: 'Custom Button',
click: this.customButton.bind(this),
});
args.customToolbar.splice(3, 0, {
prefixIcon: 'e-pivotview-expand e-icons', tooltipText: 'Expand/Collapse',
click: this.toolbarClicked.bind(this),
});
args.customToolbar[0].align = "Left";
args.customToolbar[1].align = "Center";
args.customToolbar[2].align = "Right";
},
customButton: function () {
// Here you can customize the click event for custom button
},
toolbarClicked: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.dataSourceSettings.expandAll = !pivotGridObj.dataSourceSettings.expandAll;
}
},
provide: {
pivotview: [
Toolbar, FieldList
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
BeforeExport
The pivot table (or) pivot chart can be exported as a pdf, excel, csv etc., document using the toolbar options. And, you can customize the export settings for exporting document by using the beforeExport
event in the toolbar.
For example, you can add the header and footer for the pdf document by setting the header
and footer
properties for the pdfExportProperties
in the beforeExport
event.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowCalculatedField="allowCalculatedField"
:showFieldList="showFieldList" :toolbar="toolbar" :saveReport="saveReport" :loadReport="loadReport"
:fetchReport="fetchReport" :renameReport="renameReport" :removeReport="removeReport" :newReport="newReport"
:beforeExport="beforeExport" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, FieldList, CalculatedField, Toolbar, PDFExport, ExcelExport, ConditionalFormatting } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const allowExcelExport = true;
const allowConditionalFormatting = true;
const allowPdfExport = true;
const displayOption = { view: 'Both' };
const showToolbar = true;
const allowCalculatedField = true;
const showFieldList = true;
const toolbar = [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"FieldList"
];
const saveReport = (args) => {
let reports = [];
let isSaved = false;
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reports = JSON.parse(localStorage.pivotviewReports);
}
if (args.report && args.reportName && args.reportName !== "") {
reports.map(function (item) {
if (args.reportName === item.reportName) {
item.report = args.report;
isSaved = true;
}
});
if (!isSaved) {
reports.push(args);
}
localStorage.pivotviewReports = JSON.stringify(reports);
}
};
const fetchReport = (args) => {
let reportCollection = [];
let reportList = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
reportList.push(item.reportName);
});
args.reportName = reportList;
};
const loadReport = (args) => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
args.report = item.report;
}
});
if (args.report) {
pivotGridObj.dataSourceSettings = JSON.parse(args.report).dataSourceSettings;
}
};
const removeReport = (args) => {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
for (let i = 0; i < reportCollection.length; i++) {
if (reportCollection[i].reportName === args.reportName) {
reportCollection.splice(i, 1);
}
}
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
};
const renameReport = (args) => {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
item.reportName = args.rename;
}
});
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
};
const newReport = () => {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.setProperties(
{
dataSourceSettings: {
columns: [],
rows: [],
values: [],
filters: []
}
},
false
);
};
const beforeExport = (args) => {
args.excelExportProperties = {
header: {
headerRows: 2,
rows: [
{ cells: [{ colSpan: 4, value: "Pivot Table", style: { fontColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, underline: true } }] }
]
},
footer: {
footerRows: 4,
rows: [
{ cells: [{ colSpan: 4, value: "Thank you for your business!", style: { hAlign: 'Center', bold: true } }] },
{ cells: [{ colSpan: 4, value: "!Visit Again!", style: { hAlign: 'Center', bold: true } }] }
]
}
};
args.pdfExportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'Text',
value: "Pivot Table",
position: { x: 0, y: 50 },
style: { textBrushColor: '#000000', fontSize: 13, dashStyle: 'Solid', hAlign: 'Center' }
}
]
},
footer: {
fromBottom: 160,
height: 150,
contents: [
{
type: 'PageNumber',
pageNumberType: 'Arabic',
format: 'Page {$current} of {$total}',
position: { x: 0, y: 25 },
style: { textBrushColor: '#02007a', fontSize: 15 }
}
]
}
};
};
provide('pivotview', [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowCalculatedField="allowCalculatedField"
:showFieldList="showFieldList" :toolbar="toolbar" :saveReport="saveReport" :loadReport="loadReport"
:fetchReport="fetchReport" :renameReport="renameReport" :removeReport="removeReport" :newReport="newReport"
:beforeExport="beforeExport" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script>
import { PivotViewComponent, FieldList, CalculatedField, Toolbar, PDFExport, ExcelExport, ConditionalFormatting } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
allowExcelExport: true,
allowConditionalFormatting: true,
allowPdfExport: true,
displayOption: { view: 'Both' },
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
toolbar: [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"FieldList"
]
};
},
methods: {
saveReport: function (args) {
let reports = [];
let isSaved = false;
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reports = JSON.parse(localStorage.pivotviewReports);
}
if (args.report && args.reportName && args.reportName !== "") {
reports.map(function (item) {
if (args.reportName === item.reportName) {
item.report = args.report;
isSaved = true;
}
});
if (!isSaved) {
reports.push(args);
}
localStorage.pivotviewReports = JSON.stringify(reports);
}
},
fetchReport: function (args) {
let reportCollection = [];
let reportList = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
reportList.push(item.reportName);
});
args.reportName = reportList;
},
loadReport: function (args) {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
args.report = item.report;
}
});
if (args.report) {
pivotGridObj.dataSourceSettings = JSON.parse(args.report).dataSourceSettings;
}
},
removeReport: function (args) {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
for (let i = 0; i < reportCollection.length; i++) {
if (reportCollection[i].reportName === args.reportName) {
reportCollection.splice(i, 1);
}
}
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
},
renameReport: function (args) {
let reportCollection = [];
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
reportCollection = JSON.parse(localStorage.pivotviewReports);
}
reportCollection.map(function (item) {
if (args.reportName === item.reportName) {
item.reportName = args.rename;
}
});
if (
localStorage.pivotviewReports &&
localStorage.pivotviewReports !== ""
) {
localStorage.pivotviewReports = JSON.stringify(reportCollection);
}
},
newReport: function () {
let pivotGridObj = document.getElementById('pivotview').ej2_instances[0];
pivotGridObj.setProperties(
{
dataSourceSettings: {
columns: [],
rows: [],
values: [],
filters: []
}
},
false
);
},
beforeExport: function (args) {
args.excelExportProperties = {
header: {
headerRows: 2,
rows: [
{ cells: [{ colSpan: 4, value: "Pivot Table", style: { fontColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, underline: true } }] }
]
},
footer: {
footerRows: 4,
rows: [
{ cells: [{ colSpan: 4, value: "Thank you for your business!", style: { hAlign: 'Center', bold: true } }] },
{ cells: [{ colSpan: 4, value: "!Visit Again!", style: { hAlign: 'Center', bold: true } }] }
]
}
};
args.pdfExportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'Text',
value: "Pivot Table",
position: { x: 0, y: 50 },
style: { textBrushColor: '#000000', fontSize: 13, dashStyle: 'Solid', hAlign: 'Center' }
}
]
},
footer: {
fromBottom: 160,
height: 150,
contents: [
{
type: 'PageNumber',
pageNumberType: 'Arabic',
format: 'Page {$current} of {$total}',
position: { x: 0, y: 25 },
style: { textBrushColor: '#02007a', fontSize: 15 }
}
]
}
};
}
},
provide: {
pivotview: [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
ActionBegin
The event actionBegin
triggers when the UI actions such as switching between pivot table and pivot chart, changing chart types, conditional formatting, exporting, etc. that are present in toolbar UI begin. This allows user to identify the current action being performed at runtime. It has the following parameters:
-
dataSourceSettings
: It holds the current data source settings such as input data source, rows, columns, values, filters, format settings and so on. -
actionName
: It holds the name of the current action began. The following are the UI actions and their names:Action Action Name New report Add new report Save report Save current report Save as report Save as current report Rename report Rename current report Remove report Remove current report Report change Report change Conditional Formatting Open conditional formatting dialog Number Formatting Open number formatting dialog Export menu PDF export, Excel export, CSV export Show Fieldlist Open field list Show Table Show table view Chart menu Show chart view Sub-totals menu Hide sub-totals, Show row sub-totals, Show column sub-totals, Show sub-totals Grand totals menu Hide grand totals, Show row grand totals, Show column grand totals, Show grand totals -
cancel
: It allows user to restrict the current action.
In the below sample, toolbar UI actions such as add new report and save current report can be restricted by setting the args.cancel option to true in the actionBegin
event.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:actionBegin="actionBegin" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import {
PivotViewComponent as EjsPivotview,
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const allowExcelExport = true;
const allowConditionalFormatting = true;
const allowNumberFormatting = true;
const allowPdfExport = true;
const displayOption = { view: 'Both' };
const showToolbar = true;
const allowCalculatedField = true;
const showFieldList = true;
const toolbar = [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
];
const actionBegin = (args) => {
if (args.actionName == 'Add new report' || args.actionName == 'Save current report') {
args.cancel = true;
}
};
provide('pivotview', [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:actionBegin="actionBegin" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script>
import {
PivotViewComponent,
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
allowExcelExport: true,
allowConditionalFormatting: true,
allowNumberFormatting: true,
allowPdfExport: true,
displayOption: { view: 'Both' },
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
toolbar: [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
]
};
},
methods: {
actionBegin: function (args) {
if (args.actionName == 'Add new report' || args.actionName == 'Save current report') {
args.cancel = true;
}
}
},
provide: {
pivotview: [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
ActionComplete
The event actionComplete
triggers when the UI actions such as as switching between pivot table and pivot chart, changing chart types, conditional formatting, exporting, etc. that are present in toolbar UI, is completed. This allows user to identify the current UI actions being completed at runtime. It has the following parameters:
-
dataSourceSettings
: It holds the current data source settings such as input data source, rows, columns, values, filters, format settings and so on. -
actionName
: It holds the name of the current action completed. The following are the UI actions and their names:Action Action Name New report New report added Save report Report saved Save as report Report re-saved Rename report Report renamed Remove report Report removed Report change Report changed Conditional Formatting Conditionally formatted Number Formatting Number formatted Export menu PDF exported, Excel exported, CSV exported Show Fieldlist Field list closed Show Table Table view shown Sub-totals menu Sub-totals hidden, Row sub-totals shown, Column sub-totals shown, Sub-totals shown Grand totals menu Grant totals hidden, Row grand totals shown, Column grand totals shown, Grand totals shown -
actionInfo
: It holds the unique information about the current UI action. For example, while adding new report, the event argument contains information such as report name and the action name.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:actionComplete="actionComplete" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import { PivotViewComponent as EjsPivotview, FieldList, CalculatedField, Toolbar, PDFExport, ExcelExport, ConditionalFormatting, NumberFormatting } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const allowExcelExport = true;
const allowConditionalFormatting = true;
const allowNumberFormatting = true;
const allowPdfExport = true;
const displayOption = { view: 'Both' };
const showToolbar = true;
const allowCalculatedField = true;
const showFieldList = true;
const toolbar = [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
];
const actionComplete = (args) => {
if (args.actionName == 'New report added' || args.actionName == 'Report saved') {
// Triggers when the toolbar UI actions such as add new report and save current report icon are completed.
}
};
provide('pivotview', [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:actionComplete="actionComplete" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script>
import { PivotViewComponent, FieldList, CalculatedField, Toolbar, PDFExport, ExcelExport, ConditionalFormatting, NumberFormatting } from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
allowExcelExport: true,
allowConditionalFormatting: true,
allowNumberFormatting: true,
allowPdfExport: true,
displayOption: { view: 'Both' },
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
toolbar: [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
]
};
},
methods: {
actionComplete: function (args) {
if (args.actionName == 'New report added' || args.actionName == 'Report saved') {
// Triggers when the toolbar UI actions such as add new report and save current report icon are completed.
}
}
},
provide: {
pivotview: [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
ActionFailure
The event actionFailure
triggers when the current UI action fails to achieve the desired result. It has the following parameters:
-
actionName
: It holds the name of the current action failed. The following are the UI actions and their names:Action Action Name New report Add new report Save report Save current report Save as report Save as current report Rename report Rename current report Remove report Remove current report Report change Report change Conditional Formatting Open conditional formatting dialog Number Formatting Open number formatting dialog Export menu PDF export, Excel export, CSV export Show Fieldlist Open field list Show Table Show table view Chart menu Show chart view Sub-totals menu Hide sub-totals, Show row sub-totals, Show column sub-totals, Show sub-totals Grand totals menu Hide grand totals, Show row grand totals, Show column grand totals, Show grand totals -
errorInfo
: It holds the error information of the current UI action.
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:actionFailure="actionFailure" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script setup>
import { provide } from "vue";
import {
PivotViewComponent as EjsPivotview,
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
const dataSourceSettings = {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
};
const height = 350;
const gridSettings = { columnWidth: 140 };
const allowExcelExport = true;
const allowConditionalFormatting = true;
const allowNumberFormatting = true;
const allowPdfExport = true;
const displayOption = { view: 'Both' };
const showToolbar = true;
const allowCalculatedField = true;
const showFieldList = true;
const toolbar = [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
];
const actionFailure = (args) => {
if (args.actionName == 'Add new report' || args.actionName == 'Save current report') {
// Triggers when the current UI action fails to achieve the desired result.
}
};
provide('pivotview', [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]);
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>
<template>
<div id="app">
<ejs-pivotview id="pivotview" ref="pivotview" :dataSourceSettings="dataSourceSettings" :gridSettings="gridSettings"
:height="height" :allowExcelExport="allowExcelExport" :allowConditionalFormatting="allowConditionalFormatting"
:allowPdfExport="allowPdfExport" :showToolbar="showToolbar" :allowNumberFormatting="allowNumberFormatting"
:allowCalculatedField="allowCalculatedField" :showFieldList="showFieldList" :toolbar="toolbar"
:actionFailure="actionFailure" :displayOption="displayOption"> </ejs-pivotview>
</div>
</template>
<script>
import {
PivotViewComponent,
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
} from "@syncfusion/ej2-vue-pivotview";
import { pivotData } from './pivotData.js';
export default {
name: "App",
components: {
"ejs-pivotview": PivotViewComponent
},
data() {
return {
dataSourceSettings: {
dataSource: pivotData,
expandAll: false,
columns: [{ name: 'Year', caption: 'Production Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' }],
rows: [{ name: 'Country' }, { name: 'Products' }],
formatSettings: [{ name: 'Amount', format: 'C0' }],
filters: []
},
height: 350,
gridSettings: { columnWidth: 140 },
allowExcelExport: true,
allowConditionalFormatting: true,
allowNumberFormatting: true,
allowPdfExport: true,
displayOption: { view: 'Both' },
showToolbar: true,
allowCalculatedField: true,
showFieldList: true,
toolbar: [
"New",
"Save",
"SaveAs",
"Rename",
"Remove",
"Load",
"Grid",
"Chart",
"Export",
"SubTotal",
"GrandTotal",
"ConditionalFormatting",
"NumberFormatting",
"FieldList"
]
};
},
methods: {
actionFailure: function (args) {
if (args.actionName == 'Add new report' || args.actionName == 'Save current report') {
// Triggers when the current UI action fails to achieve the desired result.
}
}
},
provide: {
pivotview: [
FieldList,
CalculatedField,
Toolbar,
PDFExport,
ExcelExport,
ConditionalFormatting,
NumberFormatting
]
}
}
</script>
<style>
@import "../node_modules/@syncfusion/ej2-vue-pivotview/styles/material.css";
</style>