# Blazor Grid Export to Excel and CSV

URL: https://flexcoreui.com/demo/grid/enterprise-suite  
Section: Data Grid  
Controls: GridControl, GridColumn  
Keywords: Excel export, xlsx export, CSV export, export to Excel, column template

Give users their data in Excel: export a Blazor grid's filtered, sorted rows to a real .xlsx workbook or CSV, and render any column from your own template.

## Documentation

### Export

| Name | Type | Description |
|---|---|---|
| ExportToCsvAsync(string? fileName = null) | Task | Comma-separated text: a header line, then the display values row by row; a value holding the delimiter, a quote or a line break is quoted, an empty value is written as two quotes. Encoded per DelimitedExportEncoding. ExportAsync with GridExportFormat.Csv; the CSV button on this page calls it. |
| ExportToTsvAsync(string? fileName = null) | Task | The same with a tab delimiter. |
| ExportToXlsxAsync(string? fileName = null) | Task | A real workbook from Fx.ControlKit.Excel.XlsxWriter in the FlexCore assembly: bold shaded header, thin borders, number formats resolved from each column's Format, column widths from the grid, native numbers and dates instead of display text, and a column Formula that references only exported fields written as a cell formula. The Excel button on this page calls it. |
| ExportToExcelAsync(string? fileName = null) | Task | Compatibility alias: it calls ExportToXlsAsync, so the file is an HTML table with an .xls name, not a workbook. |
| ExportToXlsAsync(string? fileName = null) | Task | The HTML table of ExportToHtmlAsync without the document wrapper, served as application/vnd.ms-excel with an .xls extension. |
| ExportToHtmlAsync(string? fileName = null) | Task | A standalone HTML document with one styled table; row and cell styles become a bold class and inline CSS. |
| ExportToJsonAsync(string? fileName = null) | Task | An indented JSON array, one object per row keyed by header text (ColumnN for a blank header), holding the display values. |
| ExportToPdfAsync(string title = "Export") | Task | PDF with a default GridPdfPrintOptions, named after the title. The toolbar pdf item calls this overload. Whatever title is passed, the grid's Title, Data or Id parameter replaces it when one is set (ResolveExportTitle, shared by every method here). |
| ExportToPdfAsync(string fileName, string title) | Task | The same with an explicit file name. |
| ExportToPdfAsync(string fileName, string title, GridPdfPrintOptions? pdfOptions, bool showCompletionStatus = true) | Task | Page size, orientation, column layout, margin and zoom from pdfOptions; false suppresses the status pill. The header-menu Print command calls this with the dialog's choices, the name grid-export.pdf and no pill. |
| ExportToPdfFileAsync(string fileName = "export.pdf", string title = "Export") | Task | The two-argument PDF overload with defaults for both. |
| ExportAsync(GridExportFormat format, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null, bool showCompletionStatus = true) | Task | What the methods above call. Builds the table (the pivot table in pivot mode; every provider page when ExportAllProviderItems is on; otherwise SortedData and VisibleColumns), runs GridExporter.ExportWithEncoding with DelimitedExportEncoding, then GridExporter.SaveAsync. A null or blank file name becomes the sanitized title; a missing extension is added. Afterward the pill shows N rows exported successfully. for about 2.5 seconds, or a warning when the save dialog could not open; a canceled dialog shows nothing. |
| CreateExport(GridExportFormat format, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null) | GridExportResult | The same bytes without the browser step: a GridExportResult record with Bytes, FileName and ContentType, for your own storage or mail. Synchronous, so a provider grid exports only the rows it has loaded. |
| ExportWithEncodingAsync(GridExportFormat format, GridDelimitedTextEncoding delimitedEncoding, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null, bool showCompletionStatus = true) | Task | ExportAsync with a one-off CSV/TSV encoding in place of DelimitedExportEncoding; the other formats ignore it. |
| CreateExportWithEncoding(GridExportFormat format, GridDelimitedTextEncoding delimitedEncoding, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null) | GridExportResult | CreateExport with a one-off encoding. |
| ExportToCsvWithEncodingAsync(GridDelimitedTextEncoding delimitedEncoding, string? fileName = null) | Task | CSV with an explicit encoding. |
| ExportToTsvWithEncodingAsync(GridDelimitedTextEncoding delimitedEncoding, string? fileName = null) | Task | TSV with an explicit encoding. |

### Provider

| Name | Type | Description |
|---|---|---|
| ExportProviderQueryAsync(GridExportFormat format, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null, bool showCompletionStatus = true, CancellationToken cancellationToken = default) | Task | With an ItemsProvider: pages through the whole current query (sort, filters, search) in ProviderExportPageSize batches, raising ProviderExportProgressChanged from before the first page, then saves like ExportAsync. Does not need ExportAllProviderItems; starting it cancels an export already in flight. Without a provider it is ExportAsync. |
| CreateProviderExportAsync(GridExportFormat format, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null, CancellationToken cancellationToken = default) | Task<GridExportResult> | The bytes of that complete query without the browser step; CreateExport when there is no provider. |
| ExportProviderQueryWithEncodingAsync(GridExportFormat format, GridDelimitedTextEncoding delimitedEncoding, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null, bool showCompletionStatus = true, CancellationToken cancellationToken = default) | Task | ExportProviderQueryAsync with a one-off CSV/TSV encoding. |
| CreateProviderExportWithEncodingAsync(GridExportFormat format, GridDelimitedTextEncoding delimitedEncoding, string? fileName = null, string title = "Export", GridPdfPrintOptions? pdfOptions = null, CancellationToken cancellationToken = default) | Task<GridExportResult> | CreateProviderExportAsync with a one-off encoding. |
| CancelProviderExport() | void | Cancels the provider export in flight, if any. |

### Exporter

| Name | Type | Description |
|---|---|---|
| Export(GridExportTable table, GridExportFormat format, string? fileName = null, GridPdfPrintOptions? pdfOptions = null) | GridExportResult | Bytes for a GridExportTable you assembled yourself; CSV and TSV as UTF-8 without a byte-order mark. |
| ExportWithEncoding(GridExportTable table, GridExportFormat format, GridDelimitedTextEncoding delimitedEncoding, string? fileName = null, GridPdfPrintOptions? pdfOptions = null) | GridExportResult | The dispatcher behind every grid export: one builder per GridExportFormat; the file name is the argument or the sanitized table Title, given the format's extension when it has none. |
| SaveAsync(IJSRuntime jsRuntime, GridExportResult export) | Task<string> | Imports the library's grid-control.js module and calls its saveFile with the file name, the bytes as base-64 and the content type, returning the module's result string; unavailable when the module could not be imported. The grid treats cancelled as no message and unavailable as a warning. This is the step the grid methods use. |
| DownloadAsync(IJSRuntime jsRuntime, GridExportResult export) | Task | Same module, downloadFile: a plain download without a dialog. TreeGridControl.DownloadAsync uses it; GridControl does not. |
| DefaultExtension(GridExportFormat format) | string | The extension for a format, as listed in the values table. |

### Formats

| Name | Description |
|---|---|
| Csv | BuildDelimited with a comma: header line, then the display values row by row; a value holding the delimiter, a quote or a line break is quoted, an empty value is written as two quotes. text/csv, .csv; a charset suffix is added for the BOM and ASCII encodings. |
| Tsv | The same with a tab. text/tab-separated-values, .tsv. |
| Html | A standalone HTML document with one styled table: bold rows get a bold class, highlight columns a highlight class; cell colors, alignment, italics and strikethrough become inline CSS. text/html, .html. |
| Xls | That table without the document wrapper, served as application/vnd.ms-excel with .xls so Excel opens it. HTML, not a workbook. |
| Xlsx | An OOXML workbook from XlsxWriter: the only format that uses XlsxValues, XlsxFormats and column Formula translation. application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, .xlsx. An unknown format value falls back to this. |
| Pdf | The library's own writer, NativePdfDocument.WriteLegacy: one content stream per page over the standard Helvetica and Helvetica-Bold fonts (bold for the header and for bold rows), gray header fill, optional grid lines, text widths from a built-in estimate, and extra page sets when the columns do not fit the width. application/pdf, .pdf. |
| Json | An indented array of objects keyed by header text. application/json, .json. |

### Params

| Name | Type | Default | Description |
|---|---|---|---|
| RowExportStyleSelector | Func<TValue, int, GridExportCellStyle?>? | null | Called once per exported row with the item and its row index. A non-null result copies ForeColorHex and BackColorHex to the row and sets the row's bold, italic and strikethrough flags where the matching property is non-null. Honored by Xlsx, Html and Xls; the PDF uses the bold flag only; CSV, TSV and JSON carry no styling. Not called for the appended total rows. |
| CellExportStyleSelector | Func<TValue, string, int, GridExportCellStyle?>? | null | Called per row and visible column with the item, the column Field and the row index. In Xlsx, Html and Xls each non-null property overrides the row's value for that cell, so a cell with Bold = false inside a bold row exports in normal weight. Not read by the PDF, CSV, TSV or JSON builders. |
| DelimitedExportEncoding | GridDelimitedTextEncoding | GridDelimitedTextEncoding.Utf8NoBom | Byte encoding of CSV and TSV: Utf8NoBom, Utf8WithBom, Utf16LittleEndian or Ascii (characters outside ASCII become a question mark). The other formats ignore it. |
| IncludeTotalsInExport | bool | true | Appends the footer AggregateRows (those with ShowInFooter) as bold rows after the data, formatted as on screen; in Xlsx they keep native values and formats and skip column formulas. Nothing is added when this is false, there are no footer rows, or there is no data. |
| ShowPrintOptionsDialog | bool | true | The header-menu Print command opens the print-options dialog first; false makes it export the PDF at once with the defaults below. |
| DefaultPrintOrientation | GridPdfOrientation | GridPdfOrientation.Portrait | Starting value of that dialog, and the value Print uses without it. The six DefaultPrint… parameters are read only on that menu path: ExportToPdfAsync takes its layout from the GridPdfPrintOptions you pass. |
| DefaultPrintPageSize | GridPdfPageSize | GridPdfPageSize.Letter | Letter, Legal or A4; same path. |
| DefaultPrintColumnLayout | GridPdfColumnLayout | GridPdfColumnLayout.WrapText | WrapText, ClipText or FitColumnsToPage; same path. Ignored while the zoom mode is FitToPage, which always fits the columns. |
| DefaultPrintGridLines | bool | true | Cell borders in the printed PDF; same path. |
| DefaultPrintZoomMode | GridPdfZoomMode | GridPdfZoomMode.FitToPage | FitToPage scales the table down until its natural width fits the page; Percent uses the percentage below. Same path. |
| DefaultPrintZoomPercent | int | 100 | Clamped to 25 to 200; same path. |
| ExportAllProviderItems | bool | false | With an ItemsProvider, makes ExportAsync and every ExportTo…Async page through the whole query like ExportProviderQueryAsync. Off, they export the rows the provider has loaded. |
| ProviderExportPageSize | int | 1_000 | Rows requested per provider call while paging an export; clamped to 1 to 100000. |
| ProviderExportProgressChanged | EventCallback<GridProviderExportProgress> | default | Raised from before the first page as a provider export progresses, with ExportedRows, TotalRows, IsCompleted and IsCanceled; the latest record is also kept in ProviderExportProgress. |

### Cell style

| Name | Type | Default | Description |
|---|---|---|---|
| ForeColorHex | string? | null | Text color as three- or six-digit hex, with or without a leading #. Black is dropped (it is the default color) and anything unparseable is ignored. |
| BackColorHex | string? | null | Fill color in the same forms; white is dropped. When null, a highlighted column fills ffffc1 in Xlsx and takes the highlight class in HTML. |
| Bold | bool? | null | Null inherits the row flag; true or false overrides it for this cell. From the row selector, null leaves the row flag alone. |
| Italic | bool? | null | Same rule for italics. |
| Strikethrough | bool? | null | Same rule for strikethrough. |

### Pdf options

| Name | Type | Default | Description |
|---|---|---|---|
| Orientation | GridPdfOrientation | GridPdfOrientation.Portrait | Landscape swaps the page width and height. |
| PageSize | GridPdfPageSize | GridPdfPageSize.Letter | Letter 612 by 792 points, Legal 612 by 1008, A4 595 by 842. |
| ColumnLayout | GridPdfColumnLayout | GridPdfColumnLayout.WrapText | WrapText wraps cell text up to MaxWrappedLines; ClipText keeps one line; FitColumnsToPage scales the column widths to the content width. Forced to FitColumnsToPage while ZoomMode is FitToPage. |
| Margin | double | 24 | Points on all four sides, clamped to 12 to 72. |
| MaxWrappedLines | int | 4 | Lines per cell in WrapText, clamped to 1 to 12. |
| IncludeColumnHeaders | bool | true | Repeats the header row at the top of every page (the table's IncludeHeaderRow must also be true). |
| ShowGridLines | bool | true | Thin gray borders around every cell. |
| ZoomMode | GridPdfZoomMode | GridPdfZoomMode.FitToPage | FitToPage scales fonts, padding and widths down (never up, floor 12 percent) until the natural column widths fit the content width; Percent uses ZoomPercent. |
| ZoomPercent | int | 100 | Used with Percent; clamped to 25 to 200. |

### Templates

| Name | Type | Default | Description |
|---|---|---|---|
| Template | RenderFragment<object>? | null | Replaces the cell content. The grid invokes it as EffectiveTemplate((object)item), so context is the row item typed as object; cast it to your row class as the Status column does. Exports never see the markup: a templated column writes its Field value formatted like a plain cell (Format, DisplayFormatter, DisplayField), which is why the badge exports as text. |
| ChildContent | RenderFragment<object>? | null | Shorthand for Template: markup placed directly inside <GridColumn> without a <Template> tag. EffectiveTemplate is Template ?? ChildContent. |
| HeaderTemplate | RenderFragment? | null | Replaces the caption span in the header cell; the sort arrow and filter badge still render after it. No context. |
| HeaderSuffixTemplate | RenderFragment? | null | Rendered in the header cell after the caption, sort arrow and filter badge. No context. |
| EditTemplate | RenderFragment<object>? | null | Replaces the editor for this column in the inline edit row and in the edit dialog; the grid passes the item being edited, cast to object, and nothing else, so the template does its own binding. A column with one is excluded from keyboard-started batch edits. |
| FilterTemplate | RenderFragment<GridColumn>? | null | Older filter-row cell template; context is the GridColumn. Used only when the column allows filtering and FilterCellTemplate is null. |
| FilterCellTemplate | RenderFragment<GridFilterCellTemplateContext>? | null | Filter-row cell. context carries Column, the current Value, Operator and Operators, and the ValueChanged, OperatorChanged, ApplyAsync and ClearAsync callbacks that drive the grid's own filter state. |
| FilterMenuTemplate | RenderFragment<GridFilterMenuTemplateContext>? | null | Body of the header filter menu. context carries the column, the draft value and operator of both conditions with their LogicalOperator, the distinct values and checklist state, and the matching change, apply, clear and close callbacks. |
| FilterMenuButtonsTemplate | RenderFragment<GridFilterMenuButtonsTemplateContext>? | null | Button area of that menu. context: Column, AutoApply, ApplyAsync (applies and closes), ClearAsync, CloseAsync. |
| PrintCellIcon | GridPrintCellIcon | GridPrintCellIcon.None | A small icon drawn before the text of this column's cells in the PDF only (IdentityCard is the one icon), for a templated column whose visual cue would otherwise be lost. Copied to the export column; the other formats ignore it. |

## Examples

### Export

```razor
@using Fx.ControlKit
@using Fx.ControlKit.Grid

<GridControl @ref="_grid"
             TValue="RateCardRow"
             DataSource="@_displayRows"
             ShowRowCountInFooter="true"
             AllowSorting="true"
             AllowSelection="true"
             AllowResizing="true"
             AllowFiltering="true"
             ShowSearchBar="true"
             Height="420px"
             CssClass="fx-grid-compact">
    <GridColumnsBase>
        <GridColumn Field="@nameof(RateCardRow.Code)" HeaderText="Code" Width="100px" />
        <GridColumn Field="@nameof(RateCardRow.Description)" HeaderText="Service" Width="220px" />
        <GridColumn Field="@nameof(RateCardRow.Supplier)" HeaderText="Supplier" Width="180px" />
        <GridColumn Field="@nameof(RateCardRow.Category)" HeaderText="Category" Width="130px" />
        <GridColumn Field="@nameof(RateCardRow.Season)" HeaderText="Season" Width="90px" />
        <GridColumn Field="@nameof(RateCardRow.Status)" HeaderText="Status" Width="110px" TextAlign="TextAlign.Center">
            <Template>
                @{
                    var row = (RateCardRow)context;
                    var variant = row.Bookable ? BadgeVariant.Success : BadgeVariant.Secondary;
                }
                <BadgeControl Text="@row.Status" Variant="@variant" Size="BadgeSize.Small" />
            </Template>
        </GridColumn>
        <GridColumn Field="@nameof(RateCardRow.Qty)" HeaderText="Qty" Width="80px" Type="ColumnType.Number" TextAlign="TextAlign.Right" />
        <GridColumn Field="@nameof(RateCardRow.Rate)" HeaderText="Net Rate" Width="110px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="$#,##0.00" />
        <GridColumn Field="@nameof(RateCardRow.Total)" HeaderText="Total" Width="120px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="$#,##0.00" />
    </GridColumnsBase>
</GridControl>
```

```csharp
public class RateCardRow
{
    public string Code { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public string Supplier { get; set; } = string.Empty;
    public string Category { get; set; } = string.Empty;
    public string Season { get; set; } = string.Empty;
    public bool Bookable { get; set; } = true;
    public string Status { get; set; } = string.Empty;
    public decimal Qty { get; set; }
    public decimal Rate { get; set; }
    public decimal Total => Qty * Rate;
}

private GridControl<RateCardRow>? _grid;
private List<RateCardRow> _displayRows = [];

protected override void OnInitialized()
{
    _displayRows = BenchData.RateCard.Take(250).Select((item, idx) => new RateCardRow
    {
        Code = item.Code,
        Description = item.Description,
        Supplier = item.Supplier,
        Category = item.Category,
        Season = item.Season,
        Bookable = item.Bookable,
        Status = item.Bookable ? "Bookable" : "Suspended",
        Qty = (idx % 8) + 1,
        Rate = item.Rate
    }).ToList();
}

private Task ExportCsv() => _grid?.ExportToCsvAsync("rate-card.csv") ?? Task.CompletedTask;

private Task ExportExcel() => _grid?.ExportToXlsxAsync("rate-card.xlsx") ?? Task.CompletedTask;
```

