Export To Excel in WPF DataGrid (SfDataGrid)
6 Sep 202324 minutes to read
WPF DataGrid provides support to export data to excel. It also provides support for grouping, filtering, sorting, paging, unbound rows, merged cells, stacked headers and Details View while exporting.
The following assemblies needs to be added for exporting to excel.
- Syncfusion.SfGridConverter.WPF
- Syncfusion.XlsIO.Base
For NuGet package, have to install Syncfusion.DataGridExcelExport.WPF package. For more details refer this UG link.
You can export SfDataGrid to excel by using the ExportToExcel extension method present in the Syncfusion.UI.Xaml.Grid.Converter namespace.
using Syncfusion.UI.Xaml.Grid.Converter;
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
NOTE
SfDataGrid exports data to excel by using XlsIO. You can refer XlsIO documentation for manipulating exported work sheets.
Excel exporting options
Exporting operation can be customized by passing ExcelExportingOptions instance as argument to ExportToExcel
method.
Export mode
By default, actual value only will be exported to excel. If you want to export the display text, you need to set ExportMode property as Text
.
var options = new ExcelExportingOptions();
options.ExportMode = ExportMode.Text;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Export groups with outlines
By default, all the groups in dataGrid will be exported in expanded state. You can enable outlines in excel based on groups by setting the AllowOutlining property as true
in ExcelExportingOptions.
var options = new ExcelExportingOptions();
options.AllowOutlining = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Exclude columns while exporting
By default, all the columns (including hidden columns) in SfDataGrid will be exported to Excel. If you want to exclude some columns while exporting to Excel, you can use ExcludeColumns field in ExcelExportingOptions.
var options = new ExcelExportingOptions();
options.ExcludeColumns.Add("CustomerName");
options.ExcludeColumns.Add("Country");
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Here, the columns having CustomerName
and Country
as MappingName are excluded while exporting.
Excel version
While exporting to Excel, you can specify the excel version by using ExcelVersion property.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Exporting stacked headers
You can export stacked headers to excel by setting ExportStackedHeaders property to true
.
var options = new ExcelExportingOptions();
options.ExportStackedHeaders = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Exporting merged cells
You can export merged cells to excel by setting ExportMergedCells property as true
.
var options = new ExcelExportingOptions();
options.ExportMergedCells = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Exporting unbound rows
You can export unbound rows to excel by setting ExportUnBoundRows property as true
.
var options = new ExcelExportingOptions();
options.ExportUnBoundRows = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Changing start row and column index while exporting
You can export the data to specified row index and column index in worksheet, by setting StartRowIndex and StartColumnIndex properties.
var options = new ExcelExportingOptions();
options.StartColumnIndex = 3;
options.StartRowIndex = 3;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Saving options
Save directly to file
After exporting to excel, you can save exported workbook directly to file system by using SaveAs method.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Save as stream
After exporting to excel, you can save exported workbook to stream by using SaveAs method.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
FileStream fileStream = new FileStream("Output.xlsx", FileMode.Create);
workBook.SaveAs(fileStream);
You can refer XlsIO documentation.
Save using File dialog
After exporting to excel, you can save exported workbook by opening FileDialog.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
SaveFileDialog sfd = new SaveFileDialog
{
FilterIndex = 2,
Filter = "Excel 97 to 2003 Files(*.xls)|*.xls|Excel 2007 to 2010 Files(*.xlsx)|*.xlsx|Excel 2013 File(*.xlsx)|*.xlsx"
};
if (sfd.ShowDialog() == true)
{
using (Stream stream = sfd.OpenFile())
{
if (sfd.FilterIndex == 1)
workBook.Version = ExcelVersion.Excel97to2003;
else if (sfd.FilterIndex == 2)
workBook.Version = ExcelVersion.Excel2010;
else
workBook.Version = ExcelVersion.Excel2013;
workBook.SaveAs(stream);
}
//Message box confirmation to view the created workbook.
if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
{
//Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
System.Diagnostics.Process.Start(sfd.FileName);
}
}
Opening exported excel without saving
You can open the exported workbook without saving by using SfSpreadsheet control.
var options = new ExcelExportingOptions();
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
Window window1 = new Window();
SfSpreadsheet spreadsheet = new SfSpreadsheet();
spreadsheet.Open(workBook);
window1.Content = spreadsheet;
window1.Show();
Export DataGrid pages to Excel
While exporting data to excel, if paging is used, current page only will be exported, by default. If you want to export all pages, you need to set ExportAllPages property as true
.
var options = new ExcelExportingOptions();
options.ExportAllPages = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
By default, all data will be exported to single sheet. If you want to export each page to different sheets, you need to use ExportPageOptions property.
var options = new ExcelExportingOptions();
options.ExportAllPages = true;
options.ExportPageOptions = ExportPageOptions.ExportToDifferentSheets;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Export DataGrid SelectedItems to Excel
By default, entire grid will be exported to Excel. You can export selected items only by passing SelectedItems
to
ExportToExcel method.
var options = new ExcelExportingOptions();
ExcelEngine excelEngine = new ExcelEngine();
IWorkbook workBook = excelEngine.Excel.Workbooks.Create();
workBook.Worksheets.Create();
dataGrid.ExportToExcel(dataGrid.SelectedItems, options, workBook.Worksheets[0]);
workBook.Version = ExcelVersion.Excel2013;
workBook.SaveAs("Sample.xlsx");
Export DataGrid to HTML
You can save exported workbook as HTML by using SaveAsHtml method.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAsHtml("Sample.html", HtmlSaveOptions.Default);
It is also possible to save worksheet as HTML by using SaveAsHtml method. You can refer XlsIO documentation for this.
Export DataGrid to Mail
You can export SfDataGrid to mail by converting it into Excel and save exported worksheet as HTML. Then exported HTML contents is embedded in mail body.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2010;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.Worksheets[0].UsedRange.BorderInside(ExcelLineStyle.Thick, ExcelKnownColors.Black);
workBook.Worksheets[0].UsedRange.BorderAround(ExcelLineStyle.Thick, ExcelKnownColors.Black);
workBook.Worksheets[0].SaveAsHtml("test.htm", Syncfusion.XlsIO.Implementation.HtmlSaveOptions.Default);
System.Net.Mail.MailMessage myMessage = new System.Net.Mail.MailMessage();
myMessage.To.Add("Support@syncfusion.com");
myMessage.From = new MailAddress("Support@syncfusion.com");
myMessage.Priority = MailPriority.High;
myMessage.Subject = "Order Details";
myMessage.IsBodyHtml = true;
myMessage.Body = new StreamReader("test.htm").ReadToEnd();
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("Support@syncfusion.com", "test");
int count = 0;
while (count < 3)
{
try
{
client.Send(myMessage);
count = 3;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(String.Format("Sending Mail Attemp - {0}", count.ToString()));
Thread.Sleep(60000);
count++;
}
}
Console.WriteLine("Mail has been sent...");
Export DataGrid to XML
You can save exported workbook as Xml
file also by using SaveAsXml methods.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAsXml("Sample.xml", ExcelXmlSaveType.MSExcel);
Export DataGrid to CSV
You can save exported workbook as CSV by using SaveAs
method.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.csv", ",");
Similarly, you can save exported worksheet also to CSV. You can refer XlsIO documentation.
Row Height and Column Width customization
After exporting data to excel, you can set different row height and column width for the columns based on your requirement. You can refer here for more information.
var options = new ExcelExportingOptions();
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.Worksheets[0].SetRowHeight(2, 50);
workBook.Worksheets[0].SetColumnWidth(2, 50);
workBook.SaveAs("Sample.xlsx");
Styling cells based on CellType in Excel
You can customize the cell styles based on CellType
by using ExportingEventHandler.
var options = new ExcelExportingOptions();
options.ExportingEventHandler = ExportingHandler;
options.AllowOutlining = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void ExportingHandler(object sender, GridExcelExportingEventArgs e)
{
if (e.CellType == ExportCellType.HeaderCell)
{
e.CellStyle.BackGroundBrush = new SolidColorBrush(Colors.LightPink);
e.CellStyle.ForeGroundBrush = new SolidColorBrush(Colors.White);
e.Handled = true;
}
else if (e.CellType == ExportCellType.RecordCell)
{
e.CellStyle.BackGroundBrush = new SolidColorBrush(Colors.LightSkyBlue);
e.Handled = true;
}
else if (e.CellType == ExportCellType.GroupCaptionCell)
{
e.CellStyle.BackGroundBrush = new SolidColorBrush(Colors.Wheat);
e.Handled = true;
}
}
Cell customization in Excel while exporting
You can customize the cells by setting CellsExportingEventHandler in ExcelExportingOptions
.
Customize cell value while exporting
You can customize the call values while exporting to excel by using CellsExportingEventHandler and ExcelExportingOptions
.
var options = new ExcelExportingOptions();
options.CellsExportingEventHandler = CellExportingHandler;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void CellExportingHandler(object sender, GridCellExcelExportingEventArgs e)
{
// Based on the column mapping name and the cell type, we can change the cell
//values while exporting to excel.
if (e.CellType == ExportCellType.RecordCell && e.ColumnName == "IsClosed")
{
//if the cell value is True, "Y" will be displayed else "N" will be displayed.
if (e.CellValue.Equals(true))
e.Range.Cells[0].Value = "Y";
else
e.Range.Cells[0].Value = "N";
e.Handled = true;
}
}
Here, cell values are changed for IsClosed
column based on custom condition.
Changing row style in excel based on data
You can customize the rows based on the record values by using CellsExportingEventHandler.
var options = new ExcelExportingOptions();
options.CellsExportingEventHandler = CellExportingHandler;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void CellExportingHandler(object sender, GridCellExcelExportingEventArgs e)
{
if (!(e.NodeEntry is RecordEntry))
return;
var record = e.NodeEntry as RecordEntry;
if ((record.Data as OrderInfo).Country == "Mexico")
{
e.Range.CellStyle.ColorIndex = ExcelKnownColors.Green;
e.Range.CellStyle.Font.Color = ExcelKnownColors.White;
}
}
Here, records having the Country
name as Mexico
are customized.
Customize the cells based on Column Name
You can customize the cells based on GridCellExcelExportingEventArgs.ColumnName property in the CellsExportingEventHandler.
var options = new ExcelExportingOptions();
options.CellsExportingEventHandler = CellExportingHandler;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void CellExportingHandler(object sender, GridCellExcelExportingEventArgs e)
{
if (e.ColumnName != "OrderID")
return;
e.Range.CellStyle.Font.Size = 12;
e.Range.CellStyle.Font.Color = ExcelKnownColors.Pink;
e.Range.CellStyle.Font.FontName = "Segoe UI";
}
Here, OrderID
column cells are customized while exporting.
Customize exported workbook and worksheet
SfDataGrid exports to excel by using XlsIO. You can refer XlsIO documentation for manipulating workbook and sheet after exporting.
Workbook
SfDataGrid provides option to return ExcelEngine from that you can get exported workbook. This allows you to protect, encrypt and add worksheet before saving.
var options = new ExcelExportingOptions();
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
Worksheet customization
SfDataGrid provides support to export to already existing file or worksheet.
In the below code snippet, worksheet is created and passed to ExportToExcel
method. In the same way, you can open already existing excel also using XlsIO
.
var options = new ExcelExportingOptions();
ExcelEngine excelEngine = new ExcelEngine();
IWorkbook workBook = excelEngine.Excel.Workbooks.Create();
dataGrid.ExportToExcel(dataGrid.View, options, workBook.Worksheets[0]);
workBook.Version = ExcelVersion.Excel2013;
workBook.SaveAs("Sample.xlsx");
Before saving workbook, you need to set the specific excel version by using IWorkbook.Version property. Here, you can directly manipulate the data in the worksheet. You can refer here for more information.
Setting borders
You can set borders to excel cells by directly accessing worksheet after exporting data.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.Worksheets[0].UsedRange.BorderInside(ExcelLineStyle.Dash_dot, ExcelKnownColors.Black);
workBook.Worksheets[0].UsedRange.BorderAround(ExcelLineStyle.Dash_dot, ExcelKnownColors.Black);
workBook.SaveAs("Sample.xlsx");
Enabling Filters
You can show filters in exported worksheet by enabling filter for the exported range in the worksheet.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.Worksheets[0].AutoFilters.FilterRange = workBook.Worksheets[0].UsedRange;
workBook.SaveAs("Sample.xlsx");
While using stacked headers
, you can specify the range
based on Stacked headers count.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
options.ExportStackedHeaders = true;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
var range = "A" + (dataGrid.StackedHeaderRows.Count + 1).ToString() + ":" + workBook.Worksheets[0].UsedRange.End.AddressLocal;
excelEngine.Excel.Workbooks[0].Worksheets[0].AutoFilters.FilterRange = workBook.Worksheets[0].Range[range];
workBook.SaveAs("Sample.xlsx");
You can refer XlsIO documentation.
Customize the range of cells
You can customize the range of cells after exporting to excel by directly manipulating worksheet.
var options = new ExcelExportingOptions();
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.Worksheets[0].Range["A2:A6"].CellStyle.Color = System.Drawing.Color.LightSlateGray;
workBook.Worksheets[0].Range["A2:A6"].CellStyle.Font.Color = ExcelKnownColors.White;
workBook.SaveAs("Sample.xlsx");
Exporting DetailsView
By default, DetailsViewDataGrid will be exported to Excel. You can customize its exporting operation by using ChildExportingEventHandler.
Excluding DetailsViewDataGrid while exporting
You can exclude particular DetailsViewDataGrid
while exporting, by using the ChildExportingEventHandler and GridChildExportingEventArgs.Cancel .
var options = new ExcelExportingOptions();
options.ChildExportingEventHandler = ChildExportingHandler;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void ChildExportingHandler(object sender, GridChildExportingEventArgs e)
{
var recordEntry = e.NodeEntry as RecordEntry;
if ((recordEntry.Data as OrderInfo).OrderID == 1002)
e.Cancel = true;
}
Here, DetailsViewDataGrid
is not exported for the parent record having OrderID
as 1002.
Excluding DetailsViewDataGrid columns from exporting
You can exclude DetailsViewDataGrid columns while exporting, by using ChildExportingEventHandler and GridChildExportingEventArgs.ExcludeColumns.
var options = new ExcelExportingOptions();
options.ChildExportingEventHandler = ChildExportingHandler;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void ChildExportingHandler(object sender, GridChildExportingEventArgs e)
{
e.ExcludeColumns.Add("OrderID");
}
Here, OrderID
column is displayed in DetailsViewDataGrid
and it is excluded while exporting to excel.
Customizing DetailsViewDataGrid cells
Like parent DataGrid, You can customize the DetailsViewDataGrid
cells also by using CellsExportingEventHandler. Based on GridCellExcelExportingEventArgs.GridViewDefinition property, you can identify the particular DetailsViewDataGrid
and customize it.
var options = new ExcelExportingOptions();
options.CellsExportingEventHandler = CellExportingHandler;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
var workBook = excelEngine.Excel.Workbooks[0];
workBook.SaveAs("Sample.xlsx");
private static void CellExportingHandler(object sender, GridCellExcelExportingEventArgs e)
{
if (e.GridViewDefinition == null || e.GridViewDefinition.RelationalColumn != "ProductDetails")
return;
if (e.ColumnName == "OrderID")
{
e.Range.CellStyle.Font.Size = 12;
e.Range.CellStyle.Font.Color = ExcelKnownColors.Blue;
e.Range.CellStyle.Font.FontName = "Segoe UI";
}
}
Performance
Using ExcelExportingOptions.CellsExportingEventHandler and changing settings for each cell will consume more memory and time consumption. So, avoid using CellsExportingEventHandler
and instead of you can do the required settings in the exported sheet.
Formatting column without using CellsExportingEventHandler
You can perform cell level customization such as row-level styling, formatting particular column in the exported worksheet.
In the below code snippet, NumberFormat for Unit Price
column is changed in the exported sheet after exporting without using CellsExportingEventHandler
.
Reference:
https://help.syncfusion.com/file-formats/xlsio/working-with-cell-or-range-formatting
var options = new ExcelExportingOptions();
options.ExportMode = ExportMode.Value;
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
IWorkbook workBook = excelEngine.Excel.Workbooks[0];
workBook.ActiveSheet.Columns[4].NumberFormat = "0.0";
Alternate row styling without using CellsExportingEventHandler
In the below code snippet, the background color of rows in excel is changed based on row index using conditional formatting for better performance.
Reference:
https://help.syncfusion.com/file-formats/xlsio/working-with-conditional-formatting
var options = new ExcelExportingOptions();
options.ExportMode = ExportMode.Value;
options.ExcelVersion = ExcelVersion.Excel2013;
var excelEngine = dataGrid.ExportToExcel(dataGrid.View, options);
IWorkbook workBook = excelEngine.Excel.Workbooks[0];
IConditionalFormats condition = workBook.ActiveSheet.Range[2,1,this.dataGrid.View.Records.Count+1,this.dataGrid.Columns.Count].ConditionalFormats;
IConditionalFormat condition1 = condition.AddCondition();
condition1.FormatType = ExcelCFType.Formula;
condition1.FirstFormula = "MOD(ROW(),2)=0";
condition1.BackColorRGB = System.Drawing.Color.Pink;
IConditionalFormat condition2 = condition.AddCondition();
condition2.FormatType = ExcelCFType.Formula;
condition2.FirstFormula = "MOD(ROW(),2)=1";
condition2.BackColorRGB = System.Drawing.Color.LightGray;