Skip to main content
All docs
V24.2

Grid Export: Task-Based Examples

  • 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.

<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>
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 });
}

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.

<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    AutoGenerateColumns="False" OnBeforeExport="grid_BeforeExport">
    <%--...--%>
</dx:ASPxGridView>
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    foreach (DevExpress.Web.GridViewDataColumn DataColumn in grid.DataColumns) {
        DataColumn.Visible = true;
    }
}

Specify a Column Width

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

<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.

<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    OnBeforeExport="grid_BeforeExport"/>
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    grid.Settings.ShowColumnHeaders = false;
}

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

<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    OnCustomColumnDisplayText="grid_CustomColumnDisplayText">
    <SettingsExport EnableClientSideExportAPI="true"/>
    <SettingsContextMenu Enabled="true">
        <RowMenuItemVisibility ExportMenu-Visible="true" />
    </SettingsContextMenu>
    <!--...-->
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;
    }
}

Export Methods

<dx:ASPxButton ID="ASPxButton1" runat="server" Text="Export to XLSX" OnClick="button_Click" />
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    OnCustomColumnDisplayText="grid_CustomColumnDisplayText" />
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);
}

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.

<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>
    <!--...-->
protected void button_Click(object sender, EventArgs e) {
    var exportOptions = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
    exportOptions.UnboundExpressionExportMode = DevExpress.Export.UnboundExpressionExportMode.AsFormula;
    grid.ExportXlsxToResponse(exportOptions);
}

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

<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

<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>
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());
}

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.

<dx:ASPxButton ID="ASPxButton1" runat="server" Text="Export to XLSX" OnClick="button_Click" />
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" />
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);
}

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.

DevExpress ASP.NET Web Forms Components

<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource"
    OnExportRenderBrick="grid_ExportRenderBrick">
    <SettingsExport ExcelExportMode="WYSIWYG" />
    <%--...--%>
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;
    }
}

Export Selected Rows

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

Run Demo: Export Selected Records

<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 ReportHeader property to specify the grid header in WYSIWYG mode.

    <dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource">
        <SettingsExport ExcelExportMode="WYSIWYG" ReportHeader="Custom Header" />
        <%--...--%>
    </dx:ASPxGridView>
    
  • Show the title panel and specify the Title property in the BeforeExport event handler.

    protected void grid_BeforeExport(object sender, ASPxGridBeforeExportEventArgs e) {
        grid.Settings.ShowTitlePanel = true;
        grid.SettingsText.Title = "Custom Header"; 
    }
    

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 Field Description
[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
<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.

<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.

<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    OnBeforeExport="grid_BeforeExport"/>
protected void grid_BeforeExport(object sender, DevExpress.Web.ASPxGridBeforeExportEventArgs e) {
    grid.SettingsExport.FileName = "My File " + DateTime.Now;
}

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.

<dx:ASPxGridView ID="grid" runat="server" DataSourceID="CustomerReportsDataSource" 
    OnBeforeExport="grid_BeforeExport"/>
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());
}

GitHub Examples