Back to Devexpress

Grid Export: Task-Based Examples

aspnet-403940-components-grid-view-concepts-export-examples.md

latest24.5 KB
Original Source

Grid Export: Task-Based Examples

  • Jul 11, 2023
  • 10 minutes to read

This section contains code samples that demonstrate common export use cases.

Hide and Add Columns in an Exported Document

You can hide and show data columns and add custom columns to the exported file in the BeforeExport event handler.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    AutoGenerateColumns="False" OnBeforeExport="grid_BeforeExport">
    <Columns>
        <dx:GridViewDataColumn Caption="Product Name" FieldName="ProductName" />
        <dx:GridViewDataColumn Caption="Company Name" FieldName="CompanyName" />
        <dx:GridViewDataColumn Caption="Order Date" FieldName="OrderDate" Visible="false"/>
        <dx:GridViewDataTextColumn Caption="Product Amount" FieldName="ProductAmount" ReadOnly="True">
            <PropertiesTextEdit DisplayFormatString="c" />
        </dx:GridViewDataTextColumn>
    </Columns>
    <%--...--%>
</dx:ASPxGridView>
csharp
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    // Hides the ProductName column.
    grid.Columns["ProductName"].Visible = false;
    // Shows the hidden OrderDate column.
    grid.Columns["OrderDate"].Visible = true;
    // Adds a new Notes column.
    grid.Columns.Add(new DevExpress.Web.GridViewDataColumn() { Caption = "Notes", VisibleIndex = 0 });
}
vb
Protected Sub grid_BeforeExport(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridBeforeExportEventArgs)
    ' Hides the ProductName column.
    grid.Columns("ProductName").Visible = False
    ' Shows the hidden OrderDate column.
    grid.Columns("OrderDate").Visible = True
    ' Adds a new Notes column.
    grid.Columns.Add(New DevExpress.Web.GridViewDataColumn() With {
        .Caption = "Notes",
        .VisibleIndex = 0
    })
End Sub

Export All Data Columns

To export every grid data column, iterate through the grid’s DataColumns collection and set the Visible property of each column to true in the BeforeExport event handler.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    AutoGenerateColumns="False" OnBeforeExport="grid_BeforeExport">
    <%--...--%>
</dx:ASPxGridView>
csharp
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    foreach (DevExpress.Web.GridViewDataColumn DataColumn in grid.DataColumns) {
        DataColumn.Visible = true;
    }
}
vb
Protected Sub grid_BeforeExport(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridBeforeExportEventArgs)
    For Each DataColumn As DevExpress.Web.GridViewDataColumn In grid.DataColumns
        DataColumn.Visible = True
    Next
End Sub

Specify a Column Width

Use a column’s ExportWidth property to specify the width of the column in the exported file.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    AutoGenerateColumns="False" >
    <Columns>
        <dx:GridViewDataTextColumn FieldName="ProductName" ExportWidth="50" />
    <%--...--%>

Hide Column Headers

In the BeforeExport event handler, set the ShowColumnHeaders property to false to hide column headers in the exported document.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    OnBeforeExport="grid_BeforeExport"/>
csharp
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    grid.Settings.ShowColumnHeaders = false;
}
vb
Protected Sub grid_BeforeExport(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridBeforeExportEventArgs)
    grid.Settings.ShowColumnHeaders = False
End Sub

Export Display Text

When exporting data in XLS or XLSX format, the ASPxGridView control exports cell values.

If you need to export display text instead of values (for instance, when display text is specified in the CustomColumnDisplayText event handler), set the TextExportMode property of the XlsExportOptionsEx or XlsxExportOptionsEx object to Text.

Default Export Commands

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    OnCustomColumnDisplayText="grid_CustomColumnDisplayText">
    <SettingsExport EnableClientSideExportAPI="true"/>
    <SettingsContextMenu Enabled="true">
        <RowMenuItemVisibility ExportMenu-Visible="true" />
    </SettingsContextMenu>
    <!--...-->
csharp
using DevExpress.Web;

protected void grid_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e) {
    if (e.Column.FieldName == "ProductAmount" && Convert.ToDecimal(e.Value) == 0) {
        e.DisplayText = "none";
    }
}

protected void grid_BeforeExport(object sender, ASPxGridBeforeExportEventArgs e) {
    switch(e.ExportTarget) {
        case ExportTarget.Xls:
            XlsExportOptions optionsXls = e.ExportOptions as XlsExportOptions;
            optionsXls.TextExportMode = TextExportMode.Text;
            break;
        case ExportTarget.Xlsx:
            XlsxExportOptions optionsXlsx = e.ExportOptions as XlsxExportOptions;
            optionsXlsx.TextExportMode = TextExportMode.Text;
            break;
        default:
            break;
    }
}
vb
Imports DevExpress.Web

Protected Sub grid_CustomColumnDisplayText(ByVal sender As Object, ByVal e As ASPxGridViewColumnDisplayTextEventArgs)
    If e.Column.FieldName = "ProductAmount" AndAlso Convert.ToDecimal(e.Value) = 0 Then
        e.DisplayText = "none"
    End If
End Sub

Protected Sub grid_BeforeExport(ByVal sender As Object, ByVal e As ASPxGridBeforeExportEventArgs)
    Select Case e.ExportTarget
        Case ExportTarget.Xls
            Dim optionsXls As XlsExportOptions = TryCast(e.ExportOptions, XlsExportOptions)
            optionsXls.TextExportMode = TextExportMode.Text
        Case ExportTarget.Xlsx
            Dim optionsXlsx As XlsxExportOptions = TryCast(e.ExportOptions, XlsxExportOptions)
            optionsXlsx.TextExportMode = TextExportMode.Text
        Case Else
    End Select
End Sub

Export Methods

aspx
<dx:ASPxButton ID="ASPxButton1" runat="server" Text="Export to XLSX" OnClick="button_Click" />
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    OnCustomColumnDisplayText="grid_CustomColumnDisplayText" />
csharp
using DevExpress.Web;

protected void grid_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e) {
    if (e.Column.FieldName == "ProductAmount" && Convert.ToDecimal(e.Value) == 0) {
        e.DisplayText = "none";
    }
}

protected void button_Click(object sender, EventArgs e) {
    var exportOptions = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
    exportOptions.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Text;
    grid.ExportXlsxToResponse(exportOptions);
}
vb
Imports DevExpress.Web

Protected Sub grid_CustomColumnDisplayText(ByVal sender As Object, ByVal e As ASPxGridViewColumnDisplayTextEventArgs)
    If e.Column.FieldName = "ProductAmount" AndAlso Convert.ToDecimal(e.Value) = 0 Then
        e.DisplayText = "none"
    End If
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim exportOptions = New DevExpress.XtraPrinting.XlsxExportOptionsEx()
    exportOptions.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Text
    grid.ExportXlsxToResponse(exportOptions)
End Sub

Export Unbound Column Values as Formulas

When exporting an unbound (calculated) column in XLS or XLSX format, the ASPxGridView control exports cell values.

Set the UnboundExpressionExportMode property of the XlsExportOptionsEx or XlsxExportOptionsEx object to AsFormula to export the column values as formulas.

aspx
<dx:ASPxButton ID="ASPxButton1" runat="server" Text="Export to XLSX" OnClick="button_Click" />
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="ProductsDataSource" KeyFieldName="ProductID">
    <Columns>
        <dx:GridViewDataTextColumn FieldName="ProductName" />
        <dx:GridViewDataTextColumn FieldName="UnitPrice">
            <PropertiesTextEdit DisplayFormatString="c" />
        </dx:GridViewDataTextColumn>
        <dx:GridViewDataTextColumn FieldName="UnitsInStock" />
        <dx:GridViewDataTextColumn FieldName="Total" UnboundType="Decimal" 
            UnboundExpression="UnitPrice * UnitsInStock">
            <PropertiesTextEdit DisplayFormatString="c" />
        </dx:GridViewDataTextColumn>
    </Columns>
    <!--...-->
csharp
protected void button_Click(object sender, EventArgs e) {
    var exportOptions = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
    exportOptions.UnboundExpressionExportMode = DevExpress.Export.UnboundExpressionExportMode.AsFormula;
    grid.ExportXlsxToResponse(exportOptions);
}
vb
Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim exportOptions = New DevExpress.XtraPrinting.XlsxExportOptionsEx()
    exportOptions.UnboundExpressionExportMode = DevExpress.Export.UnboundExpressionExportMode.AsFormula
    grid.ExportXlsxToResponse(exportOptions)
End Sub

Export Master-Detail Grid

The Grid control supports master-detail grid export in WYSIWYG mode only. Set the SettingsDetail.ExportMode property to Expanded or All to export detail grid records.

Run Demo: Export Master-Detail Records

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CategoriesDataSource" KeyFieldName="CategoryID">
    <Toolbars>
        <dx:GridViewToolbar>
            <Items>
                <dx:GridViewToolbarItem Command="ExportToPdf" />
                <dx:GridViewToolbarItem Command="ExportToXls" />
                <dx:GridViewToolbarItem Command="ExportToXlsx" />
            </Items>
        </dx:GridViewToolbar>
    </Toolbars>
    <SettingsDetail ShowDetailRow="true" ExportMode="All" />
    <SettingsExport EnableClientSideExportAPI="true" ExcelExportMode="WYSIWYG" />
    <Templates>
        <DetailRow>
            <dx:ASPxGridView ID="detailGrid" runat="server" DataSourceID="ProductsDataSource"
                KeyFieldName="ProductID" OnBeforePerformDataSelect="detailGrid_BeforePerformDataSelect" />
        </DetailRow>
    </Templates>
</dx:ASPxGridView>

Export Images

The ASPxGridView control exports images contained in a column of the GridViewDataBinaryImageColumn type.

If your grid displays images in a column of the GridViewDataImageColumn type, handle the ExportRenderBrick event and assign the image to the ImageValue property. Note that the ExportRenderBrick event does not fire in DataAware export mode, so you should set the export mode to WYSIWIG.

Run Demo: Export with Data Cell Bands

aspx
<dx:ASPxGridView ID="grid" runat="server" AutoGenerateColumns="False" DataSourceID="XmlDataSource1" 
    OnExportRenderBrick="grid_ExportRenderBrick">
    <Columns>
        <dx:GridViewDataTextColumn FieldName="Common_Name" Caption="Common name" />
        <dx:GridViewDataTextColumn FieldName="Species_Name" Caption="Species name" />
        <dx:GridViewDataImageColumn FieldName="ImagePath" Caption="Image">
            <PropertiesImage>
                <ExportImageSettings Width="180" Height="120" />
            </PropertiesImage>
        </dx:GridViewDataImageColumn>
    </Columns>
    <%--...--%>
</dx:ASPxGridView>
csharp
byte[] GetImageBinaryData(string relativePath) {
    string path = Server.MapPath(relativePath);
    return File.Exists(path) ? File.ReadAllBytes(path) : null;
}

protected void grid_ExportRenderBrick(object sender, ASPxGridViewExportRenderingEventArgs e) {
    var dataColumn = e.Column as GridViewDataColumn;
    if (dataColumn != null && dataColumn.FieldName == "ImagePath" && e.RowType == GridViewRowType.Data)
        e.ImageValue = GetImageBinaryData(e.Value.ToString());
}
vb
Private Function GetImageBinaryData(ByVal relativePath As String) As Byte()
    Dim path As String = Server.MapPath(relativePath)
    Return If(File.Exists(path), File.ReadAllBytes(path), Nothing)
End Function

Protected Sub grid_ExportRenderBrick(ByVal sender As Object, ByVal e As ASPxGridViewExportRenderingEventArgs)
    Dim dataColumn = TryCast(e.Column, GridViewDataColumn)
    If dataColumn IsNot Nothing AndAlso dataColumn.FieldName = "ImagePath" AndAlso e.RowType = GridViewRowType.Data Then e.ImageValue = GetImageBinaryData(e.Value.ToString())
End Sub

Color Cells

The ASPxGridView control exports grid data with colors applied by conditional formatting. Colors applied to grid cells in other ways are not exported automatically. You can color grid cells in the exported document in the following ways (based on the export mode):

Color Cells in DataAware Mode

Handle the CustomizeCell event of the XlsExportOptionsEx or XlsxExportOptionsEx object to color grid cells.

aspx
<dx:ASPxButton ID="ASPxButton1" runat="server" Text="Export to XLSX" OnClick="button_Click" />
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" />
csharp
void exportOptions_CustomizeCell(DevExpress.Export.CustomizeCellEventArgs e) {
    if (e.AreaType == DevExpress.Export.SheetAreaType.Header) {
        e.Formatting.Font.Color = System.Drawing.Color.Red;
        e.Formatting.BackColor = System.Drawing.Color.LightYellow;
    }
    // Set the Handled property to true to apply the specified cell customization settings.
    e.Handled = true;
}

protected void button_Click(object sender, EventArgs e) {
    var exportOptions = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
    exportOptions.CustomizeCell += exportOptions_CustomizeCell;
    grid.ExportXlsxToResponse(exportOptions);
}
vb
Private Sub exportOptions_CustomizeCell(ByVal e As DevExpress.Export.CustomizeCellEventArgs)
    If e.AreaType = DevExpress.Export.SheetAreaType.Header Then
        e.Formatting.Font.Color = System.Drawing.Color.Red
        e.Formatting.BackColor = System.Drawing.Color.LightYellow
    End If
    ' Set the Handled property to true to apply the specified cell customization settings.
    e.Handled = True
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim exportOptions = New DevExpress.XtraPrinting.XlsxExportOptionsEx()
    exportOptions.CustomizeCell += AddressOf exportOptions_CustomizeCell
    grid.ExportXlsxToResponse(exportOptions)
End Sub

View Example: How to export a colored grid in Data Aware export mode

Color Cells in WYSIWIG Mode

Handle the ExportRenderBrick event to color grid cells.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    OnExportRenderBrick="grid_ExportRenderBrick">
    <SettingsExport ExcelExportMode="WYSIWYG" />
    <%--...--%>
csharp
protected void grid_ExportRenderBrick(object sender, DevExpress.Web.ASPxGridViewExportRenderingEventArgs e) {
    if (e.RowType == DevExpress.Web.GridViewRowType.Header) {
        e.BrickStyle.ForeColor = System.Drawing.Color.Red;
        e.BrickStyle.BackColor = System.Drawing.Color.LightYellow;
    }
}
vb
Protected Sub grid_ExportRenderBrick(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridViewExportRenderingEventArgs)
    If e.RowType = DevExpress.Web.GridViewRowType.Header Then
        e.BrickStyle.ForeColor = System.Drawing.Color.Red
        e.BrickStyle.BackColor = System.Drawing.Color.LightYellow
    End If
End Sub

Export Selected Rows

Set the ASPxGridView.SettingsExport.ExportSelectedRowsOnly property to true to export selected rows only.

Run Demo: Export Selected Records

aspx
<dx:ASPxGridView ID="grid" Crunat="server" DataSourceID="ProductsDataSource"
    AutoGenerateColumns="false" KeyFieldName="ProductID" >
    <SettingsExport ExportSelectedRowsOnly="true" />
    <Columns>
        <dx:GridViewCommandColumn ShowSelectCheckbox="true" />
        <dx:GridViewDataTextColumn FieldName="ProductName" />
        <dx:GridViewDataTextColumn FieldName="QuantityPerUnit" />
        <dx:GridViewDataTextColumn FieldName="UnitPrice">
    </Columns>
    <%--...--%>
</dx:ASPxGridView>

Add a Grid Header

You can add a grid header to an exported document in the following ways:

Use the PageHeader and PageFooter properties to specify custom text content for an exported document page’s header and footer. You can use the following service fields in the header and footer content:

Service FieldDescription
[Page #]Page number
[Pages #]Total number of pages
[Page # of Pages #]Page number and total number of pages
[Date Printed]Current date
[Time Printed]Current time
aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource">
    <SettingsExport ExcelExportMode="WYSIWYG">
        <PageFooter Center="[Page #]" />
        <PageHeader Right="[Date Printed]" Left="Developer Express Inc."/>
    </SettingsExport>
    <%--...--%>
</dx:ASPxGridView>

Specify Exported File Name

Use the FileName property to specify the name of the exported file.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource">
    <SettingsExport FileName="exported-grid" />
    <%--...--%>
</dx:ASPxGridView>

To specify the name dynamically at runtime, handle the BeforeExport event and assign the desired file name to the FileName property.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    OnBeforeExport="grid_BeforeExport"/>
csharp
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    grid.SettingsExport.FileName = "My File " + DateTime.Now;
}
vb
Protected Sub grid_BeforeExport(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridBeforeExportEventArgs)
    grid.SettingsExport.FileName = "My File " & DateTime.Now
End Sub

Change the Grid Layout in Exported Document

To apply a custom layout to an exported document, call the LoadClientLayout(String) method in the BeforeExport event handler. In this case, the layout settings affect the exported document content only and do not affect the current grid UI.

aspx
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    OnBeforeExport="grid_BeforeExport"/>
csharp
protected void Page_Init(object sender, EventArgs e) {
    // Save the default grid layout.
    Session["layout"] = grid.SaveClientLayout();
}
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    // Load the default layout.
    grid.LoadClientLayout(Session["layout"].ToString());
}
vb
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    ' Save the default grid layout.
    Session("layout") = grid.SaveClientLayout()
End Sub

Protected Sub grid_BeforeExport(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridBeforeExportEventArgs)
    ' Load the default layout.
    grid.LoadClientLayout(Session("layout").ToString())
End Sub

GitHub Examples