Category / Section
How to export the SfDataGrid to Excel with styles
1 min read
You can export the SfDataGrid with current style by getting the style using FindResource method and assign the style to CellStyle in ExportingHandler.
XAML: Apply the style to SfDataGrid
<Window.Resources> <Style TargetType="syncfusion:GridHeaderCellControl" > <Setter Property="Background" Value="LightBlue"/> <Setter Property="Foreground" Value="Black"/> </Style> <Style TargetType="syncfusion:GridCell"> <Setter Property="Background" Value="Cyan"/> </Style> </Window.Resources>
Note: It is not possible export the styles which are applied conditionally based on data.
C#: Getting the style properties values using FindResource method.
private static void GetDataGridStyles(SfDataGrid dataGrid) { var gridHeaderCellControl = dataGrid.FindResource(typeof(GridHeaderCellControl)) as Style; var gridCell = dataGrid.FindResource(typeof(GridCell)) as Style; if (gridHeaderCellControl == null || gridCell == null) return; foreach (Setter setter in gridHeaderCellControl.Setters) { if (setter.Property == GridHeaderCellControl.BackgroundProperty) gridHeaderBackgroundColor = (Color)ColorConverter.ConvertFromString(setter.Value.ToString()); else if (setter.Property == GridHeaderCellControl.ForegroundProperty) gridHeaderForeGroundColor = (Color)ColorConverter.ConvertFromString(setter.Value.ToString()); } foreach (Setter setter in gridCell.Setters) { if (setter.Property== GridCell.BackgroundProperty) gridCellBackgroundColor = (Color)ColorConverter.ConvertFromString(setter.Value.ToString()); } }
C#: Assign style property values from above code in ExportingHandler.
private static void ExportingHandler(object sender, GridExcelExportingEventArgs e) { if (e.CellType == ExportCellType.HeaderCell) { e.CellStyle.BackGroundBrush = new SolidColorBrush(gridHeaderBackgroundColor); e.CellStyle.ForeGroundBrush = new SolidColorBrush(gridHeaderForeGroundColor); } else if (e.CellType == ExportCellType.RecordCell) { e.CellStyle.BackGroundBrush = new SolidColorBrush(gridCellBackgroundColor); } e.Handled = true; }
Sample: