Telerik RadGrid: Formatting Footer cell in OnExpor

2019-08-15 00:36发布

问题:

Posted 1 day ago Hi, I have a currency value column in a radgrid, and exporting to excel using this function for formatting the currency cells

protected void RadGrid_OnExportCellFormatting(object sender, ExportCellFormattingEventArgs e)
{
    if (e.FormattedColumn.DataType == typeof (long))
    {
        e.Cell.Style["mso-number-format"] = "Currency";
    }
}

Works very well, but it doesn't format the footer item which is an aggregated sum value. How do I format the footer to be currency as well?

回答1:

In the markup (if you are using the AJAX controls) you can define the (footer) aggregate format as follows:

<telerik:GridBoundColumn DataField="columnName" HeaderText="Money" UniqueName="uniqueColumnName"  
    DataFormatString="{0:C}" Aggregate="Sum" FooterAggregateFormatString="{0:C}" />

This will be implemented on the displayed and exported grid. It is however possible that you do not want to display this on the screen; in these instances you could update the attribute from within an export event handler. You should also note that from the above markup there is a DataFormatString attribute which can format the data displayed in the cell.

protected void RadGrid_OnExportCellFormatting(object sender, ExportCellFormattingEventArgs e)
{
    if ((e.FormattedColumn.DataType == typeof(long))) {
        e.Cell.Style("mso-number-format") = "Currency";
        if (((e.FormattedColumn) is GridBoundColumn)) {
            GridBoundColumn col = e.FormattedColumn;
            col.FooterAggregateFormatString = "{0:C}";
        }
    }
} 

You could otherwise do this with a GridExporting event handler:

protected void RadGrid_GridExporting(object sender, GridExportingArgs e)
{
    GridColumn gridCol = grdCustomers.MasterTableView.GetColumnSafe("uniqueColumnName");
    if (((gridCol) is GridBoundColumn)) {
        GridBoundColumn boundCol = (GridBoundColumn)gridCol;
        boundCol.FooterAggregateFormatString = "{0:C}";
    }
}

I'm sure the casting etc. done above could be implemented more efficiently/properly, but the above code should be a reasonable place to start from.