Devexpress wpf gridcontrol export to excel

The GridControl provides a fast and flexible way to export its data to a file or stream in various formats. This topic consists of the following sections:

  • Overview
  • Export to XLS, XLSX, and CSV Formats

    • Data-aware Export
    • WYSIWYG Export

Overview

A View provides multiple methods to export its contents.

Method Description
DataViewBase.ExportToHtml Exports a grid to the specified file path in HTML format.
DataViewBase.ExportToImage Exports a grid to the specified file path in image format.
DataViewBase.ExportToMht Exports a grid to the specified file path in MHT format
DataViewBase.ExportToPdf Exports a grid to the specified file path in PDF format.
DataViewBase.ExportToRtf Exports a grid to the specified stream in RTF format.
DataViewBase.ExportToText Exports a grid to the specified stream in text format.
DataViewBase.ExportToXps Exports a grid to the specified file path in XPS format.
TableView.ExportToCsv, TreeListView.ExportToCsv, CardView.ExportToCsv Exports a grid to the specified stream in CSV format.
TableView.ExportToXls, TreeListView.ExportToXls, CardView.ExportToXls Exports a grid to the specified file path in XLS format.
TableView.ExportToXlsx, TreeListView.ExportToXlsx, CardView.ExportToXlsx Exports a grid to the specified stream in XLSX format.

The Print Preview window allows you to customize the printed document, print or export it to a file in the required format. The image below illustrates the Print Preview window for a sample grid.

PrintPreviewWindowExport

See the Printing Options section of the Printing topic to learn how to specify the View elements to be printed.

Export to XLS, XLSX, and CSV Formats

The GridControl supports two export modes when exporting data to XLS, XLSX, and CSV formats:

  • Data-aware Export
  • WYSIWYG Export

Data-aware Export

This is the default export mode, optimized for subsequent analysis of grid data within Microsoft Excel. Output documents retain various data shaping options that are applied within the grid. The data-aware export functionality provides improved performance and memory usage.

Note

Currently CardView does not support the data-aware export.

The GridControl supports the following features for all Excel export operations:

  • Data Grouping — allows end-users to collapse/expand groups within a worksheet.
  • Data Sorting and Filtering — allows end-users to display relevant data in the desired order.
  • Totals and Group Summaries — allows end-users to modify/change formulas.
  • Excel Style Conditional Formatting.
  • Data Validation for lookup and combobox columns.
  • Fixed Columns.
  • Band Columns.

The data-aware export has the following limitations:

  • Only master rows are shown when exporting master-detail data.
  • Printing styles and templates are not supported.
  • Custom summary export is not supported.
  • Icon Sets that are used for conditional formatting are not supported.

WYSIWYG Export

In this export mode, resulting documents retain the layout of grid cells. Specific data shaping options are not retained, in comparison to the data-aware export.

Set the ExportSettings.DefaultExportType property to ExportType.WYSIWYG to enable the WYSIWYG export mode in an application.

The following code illustrates the WYSIWYG export to XLSX:

  • C#
TableView.ExportToXlsx([Path], new XlsxExportOptionsEx { ExportType = ExportType.WYSIWYG })

See Also

Содержание

  1. Data-Aware Export
  2. Supported Data Shaping Features
  3. Export Data
  4. Customize Appearance
  5. Limitations
  6. Exporting
  7. Overview
  8. Export to XLS, XLSX, and CSV Formats
  9. Export to XLS, XLSX, CSV Formats
  10. Data-Aware Export
  11. WYSIWYG Export
  12. Choose Export Mode
  13. Data-aware Export
  14. Data-aware Export Specifics and Limitations
  15. Grid Features that are not Exported
  16. Export Specifics
  17. Data-aware Export Settings
  18. Data-aware Export Events

Data-Aware Export

The data-aware export is the default export mode for the XLS, XLSX, and CSV formats. This mode allows you to transfer data shaping operations (filters, groups, conditional formatting, etc.) into a document. The data-aware mode provides improved performance and memory usage compared to WYSIWYG mode.

The CardView does not support the data-aware export.

Supported Data Shaping Features

The data-aware export mode retains the following grid data shaping features in the exported documents:

Data Grouping — allows end users to collapse/expand groups within a worksheet.

Data Sorting and Filtering — allows end users to display relevant data in the desired order.

Total and Group Summaries — allows end users to modify/change formulas.

Fixed Columns (except columns fixed to the right edge).

Export Data

The following code sample exports the GridControl to the Xls file:

The following methods export GridControl data in the data-aware mode:

Method Description
TableView.ExportToCsv, TreeListView.ExportToCsv Exports a grid to the specified stream in CSV format.
TableView.ExportToXls, TreeListView.ExportToXls Exports a grid to the specified file path in XLS format.
TableView.ExportToXlsx, TreeListView.ExportToXlsx Exports a grid to the specified stream in XLSX format.

Customize Appearance

The exported GridControl ignores the DataViewBase.CellTemplate and regular Template/Style properties. Refer to the Format Cell Values topic for information on what properties affect the data-aware export mode.

The following code sample changes the Birthday column’s width and the background color of odd rows in the exported document:

To customize the resulting document in the data-aware export mode, use members of the XlsxExportOptionsEx, XlsExportOptionsEx, or CsvExportOptionsEx classes.

Event Description
XlsxExportOptionsEx.CustomizeCell, XlsExportOptionsEx.CustomizeCell, CsvExportOptionsEx.CustomizeCell Allows you to customize a cell in the output document.
XlsxExportOptionsEx.CustomizeDocumentColumn, XlsExportOptionsEx.CustomizeDocumentColumn Allows you to customize an individual column in the output document (for example, change its width, formatting, collapse the group containing the column or hide the column).
XlsxExportOptionsEx.CustomizeSheetFooter, XlsExportOptionsEx.CustomizeSheetFooter Allows you to add a footer to the output document.
XlsxExportOptionsEx.CustomizeSheetHeader, XlsExportOptionsEx.CustomizeSheetHeader Allows you to add a header to the output document.
XlsxExportOptionsEx.CustomizeSheetSettings, XlsExportOptionsEx.CustomizeSheetSettings Allows you to customize the output document’s settings.

Limitations

  • If the GridControl works in the master-detail mode, only master rows are exported.
  • Printing styles and templates are not supported.
  • If you set the DataViewBase.TotalSummaryPosition property to Top , the GridControl exports summaries from this Summary Panel as text strings instead of formulas.
  • Custom summary export is not supported.
  • Icon Sets that are used for conditional formatting are not supported.
  • If you applied a conditional formatting filter, the Data-aware Export discards all the conditional formats applied to the GridControl except the FormatCondition conditional formats.
  • In-place ImageEditSettings are not exported.
  • Custom masks are not exported.

Refer to the following help topic for more information: Excel Export Specifications and Limits.

Источник

Exporting

The GridControl provides a fast and flexible way to export its data to a file or stream in various formats. This topic consists of the following sections:

Overview

A View provides multiple methods to export its contents.

Method Description
DataViewBase.ExportToHtml Exports a grid to the specified file path in HTML format.
DataViewBase.ExportToImage Exports a grid to the specified file path in image format.
DataViewBase.ExportToMht Exports a grid to the specified file path in MHT format
DataViewBase.ExportToPdf Exports a grid to the specified file path in PDF format.
DataViewBase.ExportToRtf Exports a grid to the specified stream in RTF format.
DataViewBase.ExportToText Exports a grid to the specified stream in text format.
DataViewBase.ExportToXps Exports a grid to the specified file path in XPS format.
TableView.ExportToCsv, TreeListView.ExportToCsv, CardView.ExportToCsv Exports a grid to the specified stream in CSV format.
TableView.ExportToXls, TreeListView.ExportToXls, CardView.ExportToXls Exports a grid to the specified file path in XLS format.
TableView.ExportToXlsx, TreeListView.ExportToXlsx, CardView.ExportToXlsx Exports a grid to the specified stream in XLSX format.

The Print Preview window allows you to customize the printed document, print or export it to a file in the required format. The image below illustrates the Print Preview window for a sample grid.

See the Printing Options section of the Printing topic to learn how to specify the View elements to be printed.

Export to XLS, XLSX, and CSV Formats

The GridControl supports two export modes when exporting data to XLS, XLSX, and CSV formats:

Data-aware Export

This is the default export mode, optimized for subsequent analysis of grid data within Microsoft Excel. Output documents retain various data shaping options that are applied within the grid. The data-aware export functionality provides improved performance and memory usage.

Currently CardView does not support the data-aware export.

The GridControl supports the following features for all Excel export operations:

  • Data Grouping — allows end-users to collapse/expand groups within a worksheet.
  • Data Sorting and Filtering — allows end-users to display relevant data in the desired order.
  • Totals and Group Summaries — allows end-users to modify/change formulas.
  • Excel Style Conditional Formatting.
  • Data Validation for lookup and combobox columns.
  • Fixed Columns.
  • Band Columns.

The data-aware export has the following limitations:

  • Only master rows are shown when exporting master-detail data.
  • Printing styles and templates are not supported.
  • Custom summary export is not supported.
  • Icon Sets that are used for conditional formatting are not supported.

WYSIWYG Export

In this export mode, resulting documents retain the layout of grid cells. Specific data shaping options are not retained, in comparison to the data-aware export.

Set the ExportSettings.DefaultExportType property to ExportType.WYSIWYG to enable the WYSIWYG export mode in an application.

The following code illustrates the WYSIWYG export to XLSX:

Источник

Export to XLS, XLSX, CSV Formats

The Grid Control supports two modes (engines) to export data from Grid Views and Banded Grid Views in XLS, XLSX, and CSV formats:

Data-Aware Export

The new export engine features improved performance and memory usage. Choose this mode if you need to process and analyze exported data in Microsoft Excel.

Data shaping options in an exported control (for example, data collapsing/expanding, summary formulas, and format rules) are persisted in the output XLS/XLSX document. The layout of grid elements may not match the original layout in the exported document.

When exporting to CSV format, the grid’s data shaping options are not included in the export document, which simplifies subsequent analysis and processing of text data.

You can export a detail View if you maximize this View.

WYSIWYG Export

This export engine retains the layout of grid elements in the output document. However, the data shaping options are not retained. For instance, the grid control exports summary values as text strings instead of formulas.

In WYSIWYG export mode, the export of detail Views is supported (see GridOptionsPrint.PrintDetails).

The Grid Control’s Card, Layout, Tile, and WinExplorer Views always export their data in WYSIWYG mode.

You can also use the PrintableComponentLink and XtraReports library‘s methods to export a Grid Control to Microsoft Excel format. These techniques always use the WYSIWYG export engine.

Use the following methods to export the grid control’s data:

Method Description
GridControl.ExportToXls Exports a View’s data to a file/stream in XLS format.
GridControl.ExportToXlsx Exports a View’s data to a file/stream in XLSX format.
GridControl.ExportToCsv Exports a View’s data to a file/stream in CSV format.

Choose Export Mode

The static ExportSettings.DefaultExportType property allows you to choose the default export mode when you use the Grid Control’s ExportToXls , ExportToXlsx , and ExportToCsv methods.

You can also specify the required export mode with each ExportToXls (or ExportToXlsx ) method call when you use these method overloads with an options parameter. Create an XlsExportOptionsEx object (or XlsxExportOptionsEx object), set its ExportType property to ExportType.DataAware or ExportType.WYSIWYG , and pass this object to the ExportToXls (or ExportToXlsx ) method.

Data-aware Export

The data-aware export engine retains the following grid data shaping features in the resulting XLS/XLSX documents:

  • Data grouping (collapse/expand groups within a worksheet).
  • Column sorting and filtering.
  • Total and group summary formulas.
  • Conditional cell formatting (format rules).
  • Lookup values (Lookup and Combo-box columns).
  • Fixed columns.
  • Expressions (expression-based unbound columns).

The following image illustrates an MS Excel worksheet that contains data from a sample Grid control with group and summary features:

Data-aware Export Specifics and Limitations

Grid Features that are not Exported

Images, charts, gauges, and RTF text in grid cells.

If a Grid Control contains a column with this type of data, the resulting worksheet contains an empty column with only a header.

Appearance settings applied to rows and individual cells.

The resulting document contains appearance settings applied to column cells (GridColumn.AppearanceCell).

  • Custom painting, alpha blending, and color gradient customizations. Refer to the following KB article for available workarounds: Is custom drawing ignored when printing or exporting?.
  • Export Specifics

      Some functions used in expression-based Excel Style Format Rules and expression-based unbound columns can only be exported to XLS (or XLSX) format in data-aware export mode. Refer to the following topic for details on which functions can be exported to XLS (or XLSX) format: Criteria Language Syntax.

    Use one of the following techniques to export custom text supplied by the ColumnView.CustomColumnDisplayText event:

    To export the specified custom text without affecting other columns, assign an in-place editor to the target column (GridColumn.ColumnEdit), and set the in-place editor’s RepositoryItem.ExportMode property to DisplayText.

    To export the specified custom text from all columns, set the XlExportOptionsBase.TextExportMode setting to Text.

  • Columns anchored to the grid control’s right edge are not fixed in the resulting document.
  • Custom summaries implemented with grid events are exported as plain text.
  • The GridColumn.Width property specifies the width of columns in XLS (or XLSX) documents. The GridColumn.Width property value may not match the actual column width in column auto-width mode (see GridOptionsView.ColumnAutoWidth).
  • Lookup and image-combo box columns: the default behavior is to export display values. Use the RepositoryItem.ExportMode property of GridColumn.ColumnEdit objects to export edit values instead of display values. Images are not exported.
  • The sort and filter functionality is disabled in the resulting document when data is exported from Advanced Banded Grid Views. These Views arrange columns one under another. The export engine ignores the XlsExportOptionsEx.AllowSortingAndFiltering and XlsxExportOptionsEx.AllowSortingAndFiltering settings for Advanced Banded Grid Views.
  • The GridView.RowHeight and AdvBandedGridOptionsView.RowAutoHeight settings do not affect row height in the resulting worksheets.
  • Column values are exported using the “[h]:mm:ss” format string for TimeSpan columns with no explicit formatting.
  • Values of numeric columns with a “P” display format string are exported with the “0.00%“ format string.
  • The ColumnApplyTo setting is not supported for FormatConditionRuleIconSet. The FormatConditionRuleIconSet rule should be applied to a column specified by the GridFormatRule.Column property.
  • Read the following article for more information about Microsoft Excel limitations (for example, row count and column count): Excel specifications and limits.

    Data-aware Export Settings

    You can use the following settings to customize the resulting document’s data:

    Base settings — accessible with the GridView.OptionsPrint and BandedGridView.OptionsPrint properties.

    These properties specify which grid elements should be included in the resulting document.

    Advanced settings — Call the ExportToXls (or ExportToXlsx) method overloads and pass an options parameter to access these settings.

    Set the options parameter to an XlsExportOptionsEx (when using the ExportToXls method) or XlsxExportOptionsEx object (when using the ExportToXlsx method).

    The following table lists these options, grouped by categories:

    Gets or sets a name of the sheet in the created XLS file to which a document is exported.

    Gets or sets whether a title is displayed for each print preview page of the exported document.

    Gets or sets the export document’s culture, which defines numeric and date-time data format settings.

    Gets or sets whether to suppress the warning that appears if the resulting XLSX file has more than 16,384 columns.

    Gets or sets whether to suppress the warning that appears if the resulting XLSX file has more than 1,048,576 rows.

    Gets or sets whether data is exported in regular mode or as a native Excel table.

    Gets or sets whether cell merge is enabled for band headers in the exported document.

    Gets or sets whether cell merge is enabled in the exported document.

    The cell merge feature is enabled in the resulting worksheet if the Xls(x)ExportOptionsEx.AllowCellMerge property is set to Default, and the Grid View allows cell merge (see GridOptionsView.AllowCellMerge).

    If cell merge is disabled in the Grid View, the Xls(x)ExportOptionsEx.AllowCellMerge property is not in effect, and cell merge is disabled in the resulting worksheet.

    Gets or sets whether columns anchored to the grid control’s left edge are fixed in the exported document.

    Gets or sets whether the column header panel is anchored to the top of the export document and not scrolled vertically.

    Gets or sets how bands and columns are arranged in the output worksheet when data is exported from Banded Views.

    Gets or sets whether band headers are visible in the exported document. This option is in effect when data is exported from Banded Grid Views if the XlsExportOptionsEx.BandedLayoutMode option is set to Default.

    Gets or sets whether column headers are visible in the exported document.

    Gets or sets whether to display the view footer in the printed/exported output.

    Gets or sets whether to display column headers in the printed/exported output.

    Gets or sets whether to display horizontal grid lines in the printed/exported output.

    Gets or sets whether to display vertical grid lines in the printed/exported output.

    Data Grouping, Sorting, and Filtering

    Gets or sets whether data groups are exported from the source control to the output document.

    Gets or sets whether column sort and filter functionality is enabled in the exported document.

    Gets or sets the expanded state of data groups in the exported document.

    Gets or sets whether group summaries are enabled in the exported document.

    Gets or sets whether total summaries are enabled in the exported document.

    Gets or sets whether group summaries are enabled in the exported document.

    Gets or sets whether the Count summary function takes all cells into account or only non-blank cells when data is exported to Excel format.

    Cell Values/Custom Text

    Gets or sets whether hyperlinks are exported.

    Gets or sets whether sparklines are exported.

    Gets or sets whether the lookup values of combo-box and lookup columns are exported.

    Gets or sets whether the source control cells with Empty Strings are exported as Blank cells in Excel format.

    Gets or sets whether column values or column expressions are exported for unbound (calculated) columns.

    Set this property to Text to export a cell’s display text (not the cell’s values) from all columns. In this mode, the export engine takes into account the custom text you specify for any column using the Data Grid’s ColumnView.CustomColumnDisplayText event.

    To export a single column‘s display text (not the column’s values), assign an in-place editor to the column and set the editor’s RepositoryItem.ExportMode property to DisplayText. In this mode, the custom text specified in the target column by the ColumnView.CustomColumnDisplayText event is exported.

    Appearance and Styles

    Gets or sets whether conditional format rules applied to columns are preserved in the exported document.

    Gets or sets whether cell formatting (cell appearance and borders) is applied to entire sheet columns or individual sheet cells. Formatting algorithms applied to sheet columns are faster than those applied to individual cells.

    Gets or sets whether horizontal grid lines are printed/exported.

    Gets or sets whether vertical grid lines are displayed in the printed/exported output.

    Data-aware Export Events

    You can use the following events to customize the resulting document while it is being generated:

    Fires immediately after a row is added to the output document.

    Allows you to customize a native Excel table’s settings before export.

    Allows you to customize a cell in the output document.

    Allows you to customize an individual column in the exported document — change its width, formatting, collapse the group containing the column, or hide the column.

    Allows you to customize the header in the output document.

    Allows you to customize the footer in the output document.

    Allows you to customize the output document’s settings.

    Allows you to apply filters to the exported document’s columns.

    Fires repeatedly while the data is being exported.

    Allows you to hide certain summary footers (or certain lines of multi-line summary footers) from the exported document.

    Источник

    I really need help with this.. I can’t find any example on the internet
    I am using DevExpress GridView I need to send it to excel and I’m getting problems to loop to every cell and column because DevExpress contains different methods then the DataGridView

    that’s the code that i’m trying to write.. I really Appreciate your help

        public class Form1 : System.Windows.Forms.Form
        {
        Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
    
        string FirstName = "First Name";
        string FatherName = "Father Name";
        string LastName = "Last Name";
        }
        public Form1()
        {
            ExcelApp.Application.Workbooks.Add(Type.Missing);
            ExcelApp.Columns.ColumnWidth = 20;
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
    
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        private void simpleButton1_Click(object sender, System.EventArgs e)
        {
            try
            {
                OleDbConnection con = new OleDbConnection();
                con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=C:\Users\pc\Documents\Emp.xlsx;Extended Properties="Excel 12.0;HDR=Yes"";
    
                con.Open();
                DataTable dtSchema;
                dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                OleDbCommand Command = new OleDbCommand ("select * FROM [" + dtSchema.Rows[0]["TABLE_NAME"].ToString() + "]", con);
                OleDbDataAdapter da = new OleDbDataAdapter(Command);
                DataSet ds = new DataSet ();
                da.Fill(ds);
                dataGrid1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
    
        private void ExportBtn_Click(object sender, System.EventArgs e)
        {
            for (int i = 1; i < gridView3.Columns.Count + 1; i++)
            {
                //ExcelApp.Cells[1, i] = gridView3.Columns[i].HeaderStyleName;
    
            }
            for (int i = 0; i< gridView3.RowCount - 1; i++)
            {
                for (int j = 0; j < gridView3.Columns.Count; j++)
                {
                    ExcelApp.Cells[i + 2, j + 1] = gridView3.Columns[j].ToString();
                }
            }
            ExcelApp.ActiveWorkbook.SaveCopyAs("C:\Users\pc\Emp.xlsx");
            ExcelApp.ActiveWorkbook.Saved = true;
            ExcelApp.Quit();
        }
    

    My problem is in the Export button the click event.. There’s no such thing as Row()

    asked Jan 29, 2013 at 12:36

    Nejthe's user avatar

    3

    To know various export methods of XtraGrid, go through Export Methods and Settings

    Use GridControl.ExportToXls(String) Method

    Example code snippet:

    private void mnuExportTable_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        using (SaveFileDialog saveDialog = new SaveFileDialog())
        {
            saveDialog.Filter = "Excel (2003)(.xls)|*.xls|Excel (2010) (.xlsx)|*.xlsx |RichText File (.rtf)|*.rtf |Pdf File (.pdf)|*.pdf |Html File (.html)|*.html";
            if (saveDialog.ShowDialog() != DialogResult.Cancel)
            {
                string exportFilePath = saveDialog.FileName;
                string fileExtenstion = new FileInfo(exportFilePath).Extension;
                
                switch (fileExtenstion)
                {
                    case ".xls":
                        gridControl.ExportToXls(exportFilePath);
                        break;
                    case ".xlsx":
                        gridControl.ExportToXlsx(exportFilePath);
                        break;
                    case ".rtf":
                        gridControl.ExportToRtf(exportFilePath);
                        break;
                    case ".pdf":
                        gridControl.ExportToPdf(exportFilePath);
                        break;
                    case ".html":
                        gridControl.ExportToHtml(exportFilePath);
                        break;
                    case ".mht":
                        gridControl.ExportToMht(exportFilePath);
                        break;
                    default:
                        break;
                }
    
                if (File.Exists(exportFilePath))
                {
                   try
                   {
                       //Try to open the file and let windows decide how to open it.
                       System.Diagnostics.Process.Start(exportFilePath);
                    }
                    catch
                    {
                        String msg = "The file could not be opened." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
                        MessageBox.Show(msg, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                 }
                 else
                 {
                     String msg = "The file could not be saved." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
                     MessageBox.Show(msg, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 }
            }
        }
    }
    

    Reference:
    Exporting Several XtraGrid Controls to a Single Excel File

    Community's user avatar

    answered Jan 29, 2013 at 14:33

    Niranjan Singh's user avatar

    Niranjan SinghNiranjan Singh

    18k2 gold badges41 silver badges75 bronze badges

    try below code. SaveFileDialog1 is tool
    also add required references —

     Try
    
            Dim sv As New SaveFileDialog1
            SaveFileDialog1.Filter = "Excel Workbook|*.xlsx"
            If SaveFileDialog1.ShowDialog() = DialogResult.OK And SaveFileDialog1.FileName <> Nothing Then
                If SaveFileDialog1.FileName.EndsWith(".xlsx") Then
                    Dim path = SaveFileDialog1.FileName.ToString()
                    GridControlAFP.ExportToXlsx(path)
                    Dim xlApp As New Excel.Application
                    Dim xlWorkBook As Excel.Workbook
                    Dim xlWorkSheet As Excel.Worksheet
                    xlWorkBook = xlApp.Workbooks.Open(path)
                    xlWorkSheet = xlWorkBook.Sheets("Sheet")
                    xlWorkSheet.Range("A1:XFD1").EntireColumn.AutoFit()
    
                    xlWorkBook.Save()
                    xlWorkBook.Close()
                    xlApp.Quit()
                End If
    
    
                MessageBox.Show("Data Exported to :" + vbCrLf + SaveFileDialog1.FileName, "Business Intelligence Portal", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
                SaveFileDialog1.FileName = Nothing
    
            End If
        Catch ex As Exception
        End Try
    

    answered Oct 24, 2017 at 7:09

    Nilesh Sarkale's user avatar

    The selectgridvalues function returns the values in the Database in Datatable format.
    Calling this function in the show button sets these values in the gridcontrol.
    Export button exports the values into an Excel sheet in .xlsx format

        //function to get values from DataTable to gridControl Devexpress
        public DataTable selectgridvalues()
        {
          SqlConnection con;
          con = new SqlConnection();
          con.ConnectionString = "server='SERVER';uid='sa';pwd='1234';database='DBName'";
          con.Open();
    
          SqlDataAdapter adp = new SqlDataAdapter("select * from Tablename order by id ", con);
          DataTable dt = new DataTable();
          adp.Fill(dt);
          gridControl1.DataSource =dt;
        }
    
    
        //code on showdatagridview values button
        public void buttonShow_Click(object sender, EventArgs e)
        {         
            gridControl1.DataSource = selectgridvalues();
        }
    
    
         //code on export to excel button
         private void buttonExportExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialogExcel = new SaveFileDialog();
            saveFileDialogExcel.Filter = "Excel files (*.xlsx)|*.xlsx";
            if (saveFileDialogExcel.ShowDialog() == DialogResult.OK)
            {
                string exportFilePath = saveFileDialogExcel.FileName;
                gridControl1.DataSource = selectgridvalues();
                gridControl1.ExportToXlsx(exportFilePath);
            }
    
        }
    

    answered Jul 20, 2019 at 5:56

    Adithya Vijay's user avatar

    DEV Express WPF provides a public export method for controls:

    • Export to PDF
    • Export to HTML
    • Export to MHT
    • Export to Text
    • Export to CSV
    • Export to XLS
    • Export to XLSX
    • Export to RTF
    • Export to DOCX
    • Export to Image

    Take the export data to the Excel form:

    The export mode is divided into two types:Data-Aware Export and WYSIWYG Export

    in WYSIWYG Export Mode supports export results to keep the printstyle set by GridControl, but display a write problem in Excel, while performance is slightly somewhat, maybe this is part of the DEV upgrade export engine.

    Data-Aware Export The model exported data does not support PrintStyle, and if you need to set the display style of the table data, you can implement the Customizecell event;

    Test code:


    <Window x:Class="GridExample.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"       
            xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
            xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
            xmlns:local="clr-namespace:GridExample" 
            Width="600" Height="350"
            >
        
        <Window.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="/GridExample;component/Themes/PrintCellStylesWPF.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>        
        </Window.Resources>
    
        <Grid VerticalAlignment="Top">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            
            <dxg:GridControl Name="grid" AutoGenerateColumns="AddNew">
                <dxg:GridControl.Columns>
                    
                    <dxg:GridColumn FieldName="PlainText"/>
                    
                    <dxg:GridColumn FieldName="MemoText" 
                                    PrintCellStyle="{StaticResource MemoColumnPrintingStyle}"
                                    >
                        <dxg:GridColumn.EditSettings>
                            <dxe:MemoEditSettings/>
                        </dxg:GridColumn.EditSettings>
                    </dxg:GridColumn>
    
                    <dxg:GridColumn FieldName="BooleanMember"
                                    PrintCellStyle="{StaticResource CheckEditColumnPrintingStyle}"
                                    > 
                        <dxg:GridColumn.EditSettings>
                            <dxe:CheckEditSettings/>
                        </dxg:GridColumn.EditSettings>
                    </dxg:GridColumn>
    
                    <dxg:GridColumn FieldName="Image"
                                    PrintCellStyle="{StaticResource ImageColumnPrintingStyle}"
                                    >
                        <dxg:GridColumn.EditSettings>
                            <dxe:PopupImageEditSettings/>
                        </dxg:GridColumn.EditSettings>
                    </dxg:GridColumn>
    
                </dxg:GridControl.Columns>
                
                <dxg:GridControl.View>
                    <dxg:TableView Name="view" PrintColumnHeaderStyle="{StaticResource HeaderStyle}"/>
                </dxg:GridControl.View>         
            </dxg:GridControl>
            
            <Button Grid.Row="1" Width="150" Name="PrintButton" Click="PrintButton_Click" Content="Show print preview"/>
        </Grid>
    </Window>

    View Code


    // Developer Express Code Central Example:
    // How to use the PrintCellStyle property to customize cell's printing appearance
    // 
    // This example shows how to create custom PrintCellStyle for grid columns to bring
    // a custom printing appearance for PopupImageEdit, CheckBoxEdit and MemoEdit.
    // 
    // You can find sample updates and versions for different programming languages here:
    // http://www.devexpress.com/example=E3227
    
    using System;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Collections.Generic;
    using System.Windows.Resources;
    using System.IO;
    using System.Drawing;
    using System.Windows.Data;
    using DevExpress.XtraPrinting;
    using DevExpress.Export;
    
    namespace GridExample {
        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();
    
                Loaded += new RoutedEventHandler(MainWindow_Loaded);
            }
    
            void MainWindow_Loaded(object sender, RoutedEventArgs e) {
                grid.ItemsSource = new List<TestData>() {
                    new TestData() { PlainText = "LMA AG", MemoText = "Mercedes-Benz SLK n 2004 n Silver", BooleanMember = true, Image = GetImage("/Images/1.png") },
                    new TestData() { PlainText = "Western Motors", MemoText ="Rolls-Royce Corniche n 1975 n Snowy whight", BooleanMember = false, Image = GetImage("/Images/2.png") },
                    new TestData() { PlainText = "Sun car rent", MemoText = "Ford Ranger FX-4n 1999 n Red rock", BooleanMember = true, Image = GetImage("/Images/3.png") }
                };
            }
    
            ImageSource GetImage(string path) {
                return new BitmapImage(new Uri(path, UriKind.Relative));
            }
    
            private void PrintButton_Click(object sender, RoutedEventArgs e) {
                //view.ExportToCsv(@"C:UserslenovoDesktoptestExportaa.csv");
                view.ExportToXlsx(@"C:UserslenovoDesktoptestExportaa.xlsx", new XlsxExportOptionsEx 
                { ExportType = ExportType.WYSIWYG
                });
                XlsxExportOptionsEx options = new XlsxExportOptionsEx();
                options.CustomizeCell += Options_CustomizeCell;
                view.ExportToXlsx(@"C:UserslenovoDesktoptestExportaa11.xlsx", options);
                view.ShowPrintPreview(this);
            }
    
            private void Options_CustomizeCell(CustomizeCellEventArgs e)
            {
                if(e.AreaType == SheetAreaType.Header)
                {
                    e.Formatting.Font = new DevExpress.Export.XlCellFont { Name= "Microsoft", Bold = true, Size = 20 };
                    e.Formatting.BackColor = System.Drawing.Color.Pink;
                    e.Handled = true;
                }
            }
        }
    }

    View Code

    PrintStyle Settings


    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
                        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
                        xmlns:dxp="http://schemas.devexpress.com/winfx/2008/xaml/printing"
                        xmlns:dxgt="clr-namespace:DevExpress.Xpf.Grid.Themes;assembly=DevExpress.Xpf.Grid.v20.1"
                        >
        <Style x:Key="HeaderStyle"  
           TargetType="{x:Type dxe:TextEdit}"  
           BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
            <Setter Property="dxp:ExportSettings.TargetType" Value="Text" />
            <Setter Property="FontSize" Value="11pt" />
            <Setter Property="FontFamily" Value="Calibri" />
            <Setter Property="Background" Value="#177477" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="FontWeight" Value="Bold" />
        </Style>
        
        <Style x:Key="ImageColumnPrintingStyle" 
               TargetType="{x:Type dxe:PopupImageEdit}"
               BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
            <Setter Property="dxp:ExportSettings.TargetType" Value="Panel" />
            <Setter Property="DisplayTemplate">
                <Setter.Value>
                    <ControlTemplate TargetType="dxe:PopupImageEdit">
    
                        <dxe:ImageEdit Source="{Binding Path=Value}"
                                        IsPrintingMode="True" 
                                        Margin="4" 
                                        HorizontalAlignment="Center" 
                                        VerticalAlignment="Center"       
                                        />
    
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    
        <dx:BoolToObjectConverter x:Key="BoolToTextConverter" TrueValue="Avaliable" FalseValue="NotAvaliable" />
    
        <Style x:Key="CheckEditColumnPrintingStyle" 
               TargetType="dxe:CheckEdit"
               BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
            <Style.Setters>
                <Setter Property="dxp:ExportSettings.TargetType" Value="Panel" />
                <Setter Property="DisplayTemplate">
                    <Setter.Value>
                        <ControlTemplate TargetType="dxe:CheckEdit">
                            <dxe:TextEdit Text="{Binding Path=Value, Converter={StaticResource BoolToTextConverter}}" HorizontalAlignment="Center" Margin="4"
                                              />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style.Setters>
        </Style>
    
        <Style x:Key="MemoColumnPrintingStyle" 
               TargetType="dxe:MemoEdit"
               BasedOn="{StaticResource {dxgt:TableViewThemeKey ResourceKey=DefaultPrintCellStyle}}">
            <Style.Setters>
                <Setter Property="dxp:ExportSettings.TargetType" Value="Panel" />
                <Setter Property="DisplayTemplate">
                    <Setter.Value>
                        <ControlTemplate TargetType="dxe:MemoEdit">
                            <dxe:TextEdit Text="{Binding Value}"
                                              TextWrapping="Wrap"
                                              IsPrintingMode="True"
                                              Margin="4"
                                              VerticalContentAlignment="Center"
                                              HorizontalContentAlignment="Left"
                                              />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style.Setters>
        </Style>
    </ResourceDictionary>

    View Code


        public class TestData {
            public string PlainText { get; set; }
            public string MemoText { get; set; }
            public bool BooleanMember { get; set; }
            public ImageSource Image { get; set; }
        }

    View Code

    Demo

    Помогаю со студенческими работами здесь

    Экспорт в Excel из GridView
    как експортировать в ексель я написал, но возникает проблема.. когда в гриде много записей и есть…

    Экспорт из SQL или со странци ASP.NET (GridView) в Excel, на стороне клиента
    Здравствуйте.

    Как реализовать выгрузку данных в Excel на строне клента. То есть чтобы вся…

    DevExpress, gridview
    Здравствуйте! Есть таблица (gridview, DevExpress) с данными (id, name и т.д.). Как достать id из…

    Компонент Devexpress GridView
    Начал работать с Devexpress. Не подскажете как работает переключение страниц? Таблица заполняется…

    Искать еще темы с ответами

    Или воспользуйтесь поиском по форуму:

    Like this post? Please share to your friends:
  • Describe what word processing can do
  • Describe tiger in one word
  • Describe this picture in one word
  • Describe this in one word перевод
  • Describe the world in one word