New to Telerik UI for ASP.NET MVC? Start a free 30-day trial
Formatting Cell Height to scale dynamically when Exporting the Grid to Excel
Environment
Product Version | 2023.2.829 |
Product | Telerik UI for ASP.NET MVC Grid |
Description
How can I format the cell height to scale dynamically during the export of the Telerik UI for ASP.NET MVC Grid to Excel?
Solution
To achieve the desired scenario:
- Handle the
ExcelExport
event of the Grid. - Convert all the Grid items to a sanitized JSON format by using the
toJSON
client-side method. - Parse the model from the Excel Export's event data to a JSON object.
- Generate the column cells by using the previously obtained property names in a valid workbook format.
- Iterate through the JSON data and manually construct each of the row cells in a valid workbook format.
- Use the
rowHeight
formula to calculate the resizing. - The
rowHeight
formula checks if the length of thecontentToWrap
string is bigger than a given number (27 in this case), and if it is,rowHeight
is set to a number that we get from rounding up(contentToWrap.length / 27) * 20
in order to get a dynamic resizing value, otherwise set therowHeight
to 20. - Create a
Workbook
and add the already created data to its sheets. - Export.
Index.cshtml
@(Html.Kendo().Grid<wrap_text_in_Export_excel.Models.OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductID);
columns.Bound(p => p.ProductName);
})
.ToolBar(tb => tb.Excel())
.Events(ev => ev.ExcelExport("onExcelExport")) // Bind to the onExcelExport() function.
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Read", "Grid"))
)
)