Skip to content

Commit 34b52fb

Browse files
Merge grid-export-footer-2730 into production (#2733)
* kb(grid): Add KB for removing aggregate labels in Excel file footer * Update knowledge-base/grid-remove-aggregate-labels-in-excel-footer.md * Update knowledge-base/grid-remove-aggregate-labels-in-excel-footer.md --------- Co-authored-by: Dimo Dimov <961014+dimodi@users.noreply.github.com>
1 parent 6294708 commit 34b52fb

File tree

2 files changed

+187
-3
lines changed

2 files changed

+187
-3
lines changed

components/grid/export/events.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -410,8 +410,8 @@ The `OnAfterExport` event fires after [OnBeforeExport](#onbeforeexport) and befo
410410

411411
* [Grid Excel Export](slug://grid-export-excel)
412412
* [Grid CSV Export](slug://grid-export-csv)
413-
* [Custom cell formatting of the exported file with RadSpreadProcessing](slug://grid-kb-custom-cell-formatting-with-radspreadprocessing)
414-
* [Custom cell formatting of the exported file with RadSpreadStreamProcessing](slug://grid-kb-custom-cell-formatting-with-radspreadstreamprocessing)
413+
* [Apply custom cell formatting in the exported Excel file with RadSpreadProcessing](slug://grid-kb-custom-cell-formatting-with-radspreadprocessing)
414+
* [Apply custom cell formatting in the exported Excel file with RadSpreadStreamProcessing](slug://grid-kb-custom-cell-formatting-with-radspreadstreamprocessing)
415+
* [Remove the Sum and Count aggregate labels in the exported Excel file](slug://grid-kb-remove-aggregate-labels-in-excel-footer)
415416
* [Format numbers and dates in the exported CSV file from the Grid](slug://grid-kb-number-formatting-of-the-csv-export)
416417
* [Change the default CSV delimiter (comma) during Grid export](slug://grid-kb-csv-export-change-field-delimiter)
417-
* [Blazor Grid](slug://grid-overview)
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
---
2+
title: Remove the "Sum" and "Count" Strings from the Exported Excel File by the Grid
3+
description: Learn how to remove the "Sum" and "Count" strings from the exported Excel file by the Telerik Grid for Blazor. See how to add custom content to the footer cells in the generated Excel file.
4+
type: how-to
5+
page_title: How To Remove the "Sum" and "Count" Strings from the Exported Excel File by the Grid
6+
slug: grid-kb-remove-aggregate-labels-in-excel-footer
7+
tags: blazor, grid, treelist, excel, aggregates
8+
ticketid: 1676757, 1619584, 1610795
9+
res_type: kb
10+
---
11+
12+
## Environment
13+
14+
<table>
15+
<tbody>
16+
<tr>
17+
<td>Product</td>
18+
<td>Grid for Blazor, <br /> TreeList for Blazor</td>
19+
</tr>
20+
</tbody>
21+
</table>
22+
23+
## Description
24+
25+
This KB article answers the following questions:
26+
27+
* How to remove the **Sum:** and **Count:** strings in the Grid footer cells when using Excel export with `GridAggregates`?
28+
* How to get the customized text from the Grid `FooterTemplate` into the Excel download, instead of the aggregate function name itself?
29+
* How to make the exported Grid Excel file match the Grid footer template content?
30+
* How to remove the **Sum** word and the other aggregate labels in the footer of Grid when exporting data to Excel? I want to only keep the number in the footer of the Excel file.
31+
* How to customize the footer cell content in the exported Excel file?
32+
33+
## Solution
34+
35+
1. Install the required [Telerik Document Processing NuGet packages](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/getting-started). Note the [version compatibility requirements to avoid conflicts with Telerik UI for Blazor](slug://dpl-kb-version-conflict-detected-telerik-zip).
36+
* `Telerik.Documents.Spreadsheet`
37+
* `Telerik.Documents.Spreadsheet.FormatProviders.OpenXml`
38+
1. Subscribe to the [Grid `OnAfterExport` event for Excel export](slug://grid-export-events#onafterexport).
39+
1. In the `OnAfterExport` handler, obtain the generated Excel file as a byte array from the `Stream` property of the [`GridAfterExcelExportEventArgs` event argument](/blazor-ui/api/telerik.blazor.components.gridafterexcelexporteventargs).
40+
1. Create a new `MemoryStream` object and populate it with the Excel file byte array.
41+
42+
The steps below use the [Telerik RadSpreadProcessing API](https://docs.telerik.com/devtools/document-processing/api/) and are outside the scope of Telerik UI for Blazor.
43+
44+
1. Use an [`XlsxFormatProvider` to `Import()` the Excel file `MemoryStream` as a `Workbook`](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/formats-and-conversion/import-and-export-to-excel-file-formats/xlsx/xlsxformatprovider).
45+
1. Get the `Worksheet` object from the `Workbook`.
46+
1. [Find the footer cells by their row and column indexes](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/working-with-cells/accessing-cells-of-worksheet), which depend on the exported number of rows and [current Grid column state](slug://grid-kb-column-state). Alternatively, [iterate cell ranges](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/working-with-cells/iterating-used-cells).
47+
1. Get each footer cell value (`ICellValue` object) and use `ICellValue.RawValue` to obtain the actual cell content.
48+
1. [Set the modified footer cell values](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/working-with-cells/get-set-clear-properties), according to your business requirements. You can remove the predefined aggregate labels or add custom content that is similar to the [Grid `FooterTemplate`](slug://grid-templates-column-footer) content.
49+
1. [`Export()` the modified `Workbook`](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/formats-and-conversion/import-and-export-to-excel-file-formats/xlsx/xlsxformatprovider) to a new `MemoryStream` and then to a `byte[]`. Assign the byte array to the `Stream` property of the `GridAfterExcelExportEventArgs` event argument.
50+
51+
>caption Remove aggregate labels from footer cells in the exported Excel file by the Grid
52+
53+
````RAZOR.skip-repl
54+
@using Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml.Xlsx
55+
@using Telerik.Windows.Documents.Spreadsheet.Model
56+
57+
@using Telerik.Blazor.Services
58+
@inject ITelerikStringLocalizer TelerikLocalizer
59+
60+
<TelerikGrid @ref="@GridRef"
61+
Data="@GridData"
62+
Pageable="true"
63+
@bind-PageSize="@GridPageSize"
64+
Reorderable="true">
65+
<GridAggregates>
66+
<GridAggregate Field="@nameof(SampleModel.Name)" FieldType="@typeof(string)" Aggregate="@GridAggregateType.Count" />
67+
<GridAggregate Field="@nameof(SampleModel.Price)" FieldType="@typeof(decimal)" Aggregate="@GridAggregateType.Average" />
68+
<GridAggregate Field="@nameof(SampleModel.Quantity)" FieldType="@typeof(int)" Aggregate="@GridAggregateType.Sum" />
69+
</GridAggregates>
70+
<GridExport>
71+
<GridExcelExport AllPages="@GridExportAllPages" OnAfterExport="@OnGridAfterExport" />
72+
</GridExport>
73+
<GridToolBarTemplate>
74+
<GridCommandButton Command="ExcelExport">Export To Excel</GridCommandButton>
75+
<span class="k-separator"></span>
76+
<label><TelerikCheckBox @bind-Value="@GridExportAllPages" /> &nbsp; Export All Pages</label>
77+
<span class="k-separator"></span>
78+
<label><TelerikCheckBox @bind-Value="@GridRemoveAggregateLabelsInExcel" /> &nbsp; Remove Aggregate Labels in Excel File</label>
79+
</GridToolBarTemplate>
80+
<GridColumns>
81+
<GridColumn Field="@nameof(SampleModel.Name)">
82+
<FooterTemplate>
83+
Count: @context.Count?.ToString("N0")
84+
</FooterTemplate>
85+
</GridColumn>
86+
<GridColumn Field="@nameof(SampleModel.Price)">
87+
<FooterTemplate>
88+
Average: @context.Average?.ToString("N2")
89+
</FooterTemplate>
90+
</GridColumn>
91+
<GridColumn Field="@nameof(SampleModel.Quantity)">
92+
<FooterTemplate>
93+
Sum: @context.Sum?.ToString("N0")
94+
</FooterTemplate>
95+
</GridColumn>
96+
</GridColumns>
97+
</TelerikGrid>
98+
99+
@code {
100+
private TelerikGrid<SampleModel>? GridRef { get; set; }
101+
private List<SampleModel> GridData { get; set; } = new();
102+
private int GridPageSize { get; set; } = 7;
103+
private bool GridExportAllPages { get; set; }
104+
105+
private bool GridRemoveAggregateLabelsInExcel { get; set; } = true;
106+
107+
private void OnGridAfterExport(GridAfterExcelExportEventArgs args)
108+
{
109+
if (!GridRemoveAggregateLabelsInExcel)
110+
{
111+
return;
112+
}
113+
114+
// args.Stream is finalized, while XlsxFormatProvider.Import() requires a readable stream.
115+
// Copy the args.Stream bytes to a new MemoryStream for the import.
116+
byte[] originalBytes = args.Stream.ToArray();
117+
MemoryStream originalStream = new MemoryStream(originalBytes);
118+
119+
XlsxFormatProvider formatProvider = new XlsxFormatProvider();
120+
Workbook workbook = formatProvider.Import(originalStream, new TimeSpan(0, 0, 5));
121+
Worksheet worksheet = workbook.Worksheets[0];
122+
123+
// The footer row index depends on the number of data items and exported pages.
124+
int footerRowIndex = GridExportAllPages ? GridData.Count + 1 : GridPageSize + 1;
125+
126+
// Cell indexes may depend on column reordering.
127+
ICollection<GridColumnState> gridColumnStates = GridRef!.GetState().ColumnStates;
128+
int nameColumnIndex = gridColumnStates.First(x => x.Field == nameof(SampleModel.Name)).Index;
129+
int priceColumnIndex = gridColumnStates.First(x => x.Field == nameof(SampleModel.Price)).Index;
130+
int quantityColumnIndex = gridColumnStates.First(x => x.Field == nameof(SampleModel.Quantity)).Index;
131+
132+
CellSelection nameFooterCell = worksheet.Cells[footerRowIndex, nameColumnIndex];
133+
string nameFooterValue = nameFooterCell.GetValue().Value.RawValue;
134+
// Aggregate labels may depend on localization
135+
nameFooterCell.SetValue(nameFooterValue.Replace($"{TelerikLocalizer["Aggregate_Count"]}: ", ""));
136+
// Optional bold
137+
nameFooterCell.SetIsBold(true);
138+
139+
CellSelection priceFooterCell = worksheet.Cells[footerRowIndex, priceColumnIndex];
140+
string priceFooterValue = priceFooterCell.GetValue().Value.RawValue;
141+
priceFooterCell.SetValue(priceFooterValue.Replace($"{TelerikLocalizer["Aggregate_Average"]}: ", ""));
142+
priceFooterCell.SetIsBold(true);
143+
144+
CellSelection quantityFooterCell = worksheet.Cells[footerRowIndex, quantityColumnIndex];
145+
string quantityFooterValue = quantityFooterCell.GetValue().Value.RawValue;
146+
quantityFooterCell.SetValue(quantityFooterValue.Replace($"{TelerikLocalizer["Aggregate_Sum"]}: ", ""));
147+
quantityFooterCell.SetIsBold(true);
148+
149+
// Save modified workbook in a MemoryStream.
150+
MemoryStream modifiedStream = new MemoryStream();
151+
formatProvider.Export(workbook, modifiedStream, new TimeSpan(0, 0, 5));
152+
153+
args.Stream = modifiedStream;
154+
}
155+
156+
protected override void OnInitialized()
157+
{
158+
for (int i = 1; i <= 30; i++)
159+
{
160+
GridData.Add(new SampleModel()
161+
{
162+
Id = i,
163+
Name = $"Name {i}",
164+
Price = Random.Shared.Next(1, 100) * 1.23m,
165+
Quantity = Random.Shared.Next(0, 1000)
166+
});
167+
}
168+
}
169+
170+
public class SampleModel
171+
{
172+
public int Id { get; set; }
173+
public string Name { get; set; } = string.Empty;
174+
public decimal Price { get; set; }
175+
public int Quantity { get; set; }
176+
}
177+
}
178+
````
179+
180+
## See Also
181+
182+
* [Grid Export Events](slug://grid-export-events)
183+
* [Grid Excel Export](slug://grid-export-excel)
184+
* [Telerik Document Processing](slug://dpl-in-blazor)

0 commit comments

Comments
 (0)