Back to Devexpress

Export Data

maui-404377-data-grid-export.md

latest19.1 KB
Original Source

Export Data

  • Jan 10, 2025
  • 6 minutes to read

The DataGridView control allows you to export its data to the following file formats:

File FormatDataGridExportExtensions Method
PDFExportToPDFAsync
XLSExportToXlsAsync
XLSXExportToXlsxAsync
MHTExportToMhtAsync
CSVExportToCsvAsync
HTMLExportToHtmlAsync
RTFExportToRtfAsync
DOCXExportToDocxAsync
TXTExportToTextAsync
Image file (the default is PNG)ExportToImageAsync

Follow the steps below to export DataGridView data:

  1. Install the DevExpress.Maui.DataGrid.Export NuGet package.

  2. Reference the DevExpress.Maui.DataGrid and DevExpress.Maui.DataGrid.Export namespaces.

  3. Call any of DataGridExportExtensions.Export methods.

The following code sample exports DataGridView data to the XLSX format:

csharp
using DevExpress.Maui.DataGrid.Export;
using DevExpress.Maui.DataGrid
// ...

public async void OnExportToXslxButtonClicked(object sender, EventArgs e) {
    string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "Document_Xslx.xlsx");
    await gridView.ExportToXlsxAsync(targetFile);
    await Share.Default.RequestAsync(new ShareFileRequest {
        Title = "Share XSLX file",
        File = new ShareFile(targetFile)
    });
}
xaml
<ContentPage ...
    xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
    xmlns:dx="clr-namespace:DevExpress.Maui.Core;assembly=DevExpress.Maui.Core">
    <ContentPage.Content>
        <Grid>
            <dx:DXButton Content="Export to XLSX" Clicked="OnExportToXslxButtonClicked"/>
            <dxg:DataGridView x:Name="gridView" ItemsSource="{Binding Employees}" AutoGenerateColumnsMode="None">
                <!-- ... -->
            </dxg:DataGridView>
        </Grid>
    </ContentPage.Content>
</ContentPage>

View Example: Export DataGridView Data

Customize Appearance

Select Elements for Export

Use the following properties to select DataGridView elements to be included in the exported file:

PropertyDescription
GridColumn.AllowExportGets or sets whether to display the column in the exported document. This is a bindable property.
DataGridView.ExportColumnHeaderModeGets or sets the location of DataGridView headers in an exported document. This is a bindable property.
DataGridView.ExportGroupSummaryGets or sets whether to print the group summary panel. This is a bindable property.
DataGridView.ExportTotalSummaryGets or sets whether to export the summary panel. This is a bindable property.

Example

The following code sample exports a hidden GridColumn:

xaml
<ContentPage ...
    xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
    xmlns:dx="clr-namespace:DevExpress.Maui.Core;assembly=DevExpress.Maui.Core">
    <ContentPage.Content>
        <Grid>
            <dx:DXButton Content="Export to XLSX" Clicked="OnExportToXslxButtonClicked"/>
            <dxg:DataGridView x:Name="gridView" ItemsSource="{Binding Employees}" AutoGenerateColumnsMode="None">
                <dxg:DataGridView.Columns>
                    <dxg:ImageColumn FieldName="Image" IsVisible="false" AllowExport="true/>
                    <dxg:TextColumn FieldName="FullName"/>
                    <!-- ... -->
                </dxg:DataGridView.Columns>
            </dxg:DataGridView>
        </Grid>
    </ContentPage.Content>
</ContentPage>
csharp
using DevExpress.Maui.DataGrid.Export;
using DevExpress.Maui.DataGrid
// ...

public async void OnExportToXslxButtonClicked(object sender, EventArgs e) {
    string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "Document_Xslx.xlsx");
    await gridView.ExportToXlsxAsync(targetFile);
    await Share.Default.RequestAsync(new ShareFileRequest {
        Title = "Share XSLX file",
        File = new ShareFile(targetFile)
    });
}

Appearance Properties

You can use the following properties to customize appearance settings in the exported document:

DataGridView PropertyGridColumn PropertyDescription
DataGridView.ExportColumnHeaderAppearanceGridColumn.ExportColumnHeaderAppearanceGets or sets the appearance object applied to column header items in the exported document. This is a bindable property.
DataGridView.ExportCellAppearanceGridColumn.ExportCellAppearanceGets or sets the appearance object applied to cells in the exported document. This is a bindable property.
DataGridView.ExportGroupRowAppearance-Gets or sets the appearance object applied to group row items (including Group Summary) in the exported document. This is a bindable property.
DataGridView.ExportGroupSummaryAppearance-Gets or sets the appearance object applied to the group summary items in the exported document. This is a bindable property.
DataGridView.ExportTotalSummaryAppearanceGridColumn.ExportTotalSummaryAppearanceGets or sets the appearance object applied to the total summary items when they are exported. This is a bindable property.
-GridColumn.ExportMaxWidthGets or sets the column’s maximum width in an exported document. This is a bindable property.
-GridColumn.ExportMinWidthGets or sets the column’s minimum width in an exported document. This is a bindable property.
-GridColumn.ExportWidthGets or sets the column’s width in an exported document. This is a bindable property.

Example

The following code sample specifies appearances of column headers and group rows in the exported document:

xaml
<ContentPage ...
    xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
    xmlns:dx="clr-namespace:DevExpress.Maui.Core;assembly=DevExpress.Maui.Core">
    <ContentPage.Content>
        <StackLayout>
            <dx:DXButton Content="Export to XLSX" Clicked="OnExportToXslxButtonClicked" />
            <dxg:DataGridView x:Name="gridView" ItemsSource="{Binding Employees}" 
                              AutoGenerateColumnsMode="None">
                <dxg:DataGridView.ExportColumnHeaderAppearance>
                    <dxg:ExportBrickAppearance Background="LightGreen" BorderColor="Black" BorderThickness="1" FontSize="14"/>
                </dxg:DataGridView.ExportColumnHeaderAppearance>
                <dxg:DataGridView.ExportGroupRowAppearance>
                    <dxg:ExportBrickAppearance Background="#FCE9B2" BorderColor="Black" BorderThickness="1" FontSize="14"/>
                </dxg:DataGridView.ExportGroupRowAppearance>
                <dxg:DataGridView.Columns>
                <!-- ... -->
            </dxg:DataGridView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Events

You can use the following events to customize the appearance of exported elements:

PropertyDescription
DataGridView.CustomCellExportAllows you to customize an exported cell.
DataGridView.CustomColumnHeaderExportAllows you to customize an exported column header.
DataGridView.CustomGroupRowExportAllows you to customize an exported group row.
DataGridView.CustomGroupSummaryExportAllows you to customize an exported group summary.
DataGridView.CustomTotalSummaryExportAllows you to customize an exported total summary.

Example

The following code sample specifies the background color of even rows in the exported document:

xaml
<ContentPage ...
    xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
    xmlns:dx="clr-namespace:DevExpress.Maui.Core;assembly=DevExpress.Maui.Core">
    <ContentPage.Content>
        <StackLayout>
            <dx:DXButton Content="Export to XLSX" Clicked="OnExportToXslxButtonClicked" />
            <dxg:DataGridView x:Name="gridView" ItemsSource="{Binding Employees}" 
                              AutoGenerateColumnsMode="None" CustomCellExport="CustomCellExport">
                <!-- ... -->
            </dxg:DataGridView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
csharp
using DevExpress.Maui.DataGrid.Export;
using DevExpress.Maui.DataGrid;
// ...

public void CustomCellExport(object sender, CustomCellExportEventArgs e) {
    var rowHandle = gridView.GetRowHandle(e.SourceIndex);
    if (rowHandle % 2 == 0) {
        e.Appearance.Background = Colors.Red;
    }
}

public async void OnExportToXslxButtonClicked(object sender, EventArgs e) {
    string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "Document_Xslx.xlsx");
    await gridView.ExportToXlsxAsync(targetFile);
    await Share.Default.RequestAsync(new ShareFileRequest {
        Title = "Share XSLX file",
        File = new ShareFile(targetFile)
    });
}

Customize Document Settings

You can use the following properties to customize the exported document:

PropertyDescription
DataGridExportLink.LandscapeGets or sets a value indicating whether the page orientation is landscape.
DataGridExportLink.MarginsGets or sets the margins of a report page (measured in hundredths of an inch).
DataGridExportLink.MinMarginsSpecifies the minimum printer margin values.
DataGridExportLink.PageHeaderFooterGets or sets the object used to fill the document’s area that is occupied by the page header and page footer.
DataGridExportLink.PaperKindGets or sets the type of paper for the document.
DataGridExportLink.RightToLeftLayoutSpecifies the orientation of the document’s content.
DataGridExportLink.RtfReportFooterGets or sets the RTF text, which will be printed as a Report Footer.
DataGridExportLink.RtfReportHeaderGets or sets the RTF text, which will be printed as a Report Header.

Example

The following example specifies the exported document margins, paper type, and orientation:

csharp
// ...
public partial class MainPage : ContentPage {
    // ...
    public async void OnExportToPdfButtonClicked(object sender, EventArgs e) {
        var link = this.gridView.GetExportLink();
        link.PaperKind = DevExpress.Drawing.Printing.DXPaperKind.A5;
        link.Landscape = true;
        link.Margins = new DevExpress.Drawing.DXMargins(100, 100, 5, 5);

        await Task.Run(link.CreateDocument);
        string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "Document_PDF1.pdf");
        using (FileStream outputStream = System.IO.File.OpenWrite(targetFile)) {
            await Task.Run(() => link.ExportToPdf(outputStream));
        }
        await Share.Default.RequestAsync(new ShareFileRequest {
            Title = "Share PDF file",
            File = new ShareFile(targetFile)
        });
    }
}
xaml
<ContentPage ...
    xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
    xmlns:dx="clr-namespace:DevExpress.Maui.Core;assembly=DevExpress.Maui.Core">
    <ContentPage.Content>
        <StackLayout>
            <dx:DXButton x:Name="exportButton" Content="Export to PDF" Clicked="OnExportToPdfButtonClicked"/>
            <dxg:DataGridView x:Name="gridView" ItemsSource="{Binding Employees}" AutoGenerateColumnsMode="None" >
                <dxg:DataGridView.Columns>
                    <!-- ... -->
                </dxg:DataGridView.Columns>
            </dxg:DataGridView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Performance Enhancements

When you export the DataGridView, the DataGridExportLink class instance is created. This class is a bridge between the DataGridView and the exported document.

The DataGridView export APIs allow you to generate a DataGridExportLink in the background thread while a user interacts with the UI.

Example

The following code sample generates DataGridExportLink in the background thread while a user interacts with the UI:

csharp
// ...
public partial class MainPage : ContentPage {
    // ...
    public async void OnExportButtonClicked(object sender, EventArgs e) {
        DataGridExportLink link = this.grid.GetExportLink();

        Task modelCreating = Task.Factory.StartNew(() => link.CreateDocument());

        string action = await DisplayActionSheet("Select export format:", "Cancel", null, "Excel", "Word", "PDF");

        MemoryStream outputStream = new();
        Task exporting = modelCreating.ContinueWith((task) => {
            switch (action) {
                case "Excel":
                    link.ExportToXlsx(outputStream);
                    break;
                case "Word":
                    link.ExportToDocx(outputStream);
                    break;
                case "PDF":
                    link.ExportToPdf(outputStream);
                    break;
            }
        });

        string fileName = await DisplayPromptAsync("Enter file name:", "Document");
        if (string.IsNullOrEmpty(fileName))
            return;

        switch (action) {
            case "Excel":
                if (!fileName.EndsWith(".xlsx"))
                    fileName += ".xlsx";
                break;
            case "Word":
                if (!fileName.EndsWith(".docx"))
                    fileName += ".docx";
                break;
            case "PDF":
                if (!fileName.EndsWith(".pdf"))
                    fileName += ".pdf";
                break;
        }

        string targetFile = Path.Combine(FileSystem.Current.AppDataDirectory, fileName);

        await exporting;

        using (FileStream fileStream = new(targetFile, FileMode.Create, FileAccess.Write)) {
            outputStream.Seek(0, SeekOrigin.Begin);
            outputStream.CopyTo(fileStream);
        }
        await Share.RequestAsync(new ShareFileRequest {
            Title = fileName,
            File = new ShareFile(targetFile)
        });
    }
}
xaml
<ContentPage ...
    xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
    xmlns:dx="clr-namespace:DevExpress.Maui.Core;assembly=DevExpress.Maui.Core">
    <ContentPage.Content>
        <Grid>
            <Button Text="Export" Clicked="OnExportButtonClicked"/>
            <dxg:DataGridView ItemsSource="{Binding Employees}" x:Name="grid">
                <dxg:DataGridView.Columns>
                    <!-- ... -->
                </dxg:DataGridView.Columns>
            </dxg:DataGridView>
        </Grid>
    </ContentPage.Content>
</ContentPage>

See Also

Use Office File API to Import Data from Excel