Skip to main content

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

How to: Use a Custom Converter for Export to a DataTable

  • 5 minutes to read

The DataTableExportOptions.CustomConverters property enables you to specify a custom converter for a specific DataTable column. To do this, create a class that implements the ICellValueToColumnTypeConverter interface. The ICellValueToColumnTypeConverter.Convert method should perform the required conversion. Subsequently, add an instance of a custom converter to the collection of custom converters available via the DataTableExporter.Options.CustomConverters notation using the Add method.

The Convert method is called for each cell that is exported to the specified column.

The following code snippet illustrates the technique. The converter transforms DateTime values into strings in MMMM-yyyy format, and displays the “N/A” text if a cell contains an error.

View Example

using DevExpress.Spreadsheet;
using DevExpress.Spreadsheet.Export;
//...

Worksheet worksheet = spreadsheetControl1.Document.Worksheets[0];
CellRange range = worksheet.Tables[0].Range;

// Create a data table with column names obtained from the first row in a range.
// Column data types are obtained from cell value types of cells in the first data row of the worksheet range.
DataTable dataTable = worksheet.CreateDataTable(range, true);
// Change the data type of the "As Of" column to text.
dataTable.Columns["As Of"].DataType = System.Type.GetType("System.String");
// Create the exporter that obtains data from the specified range and populates the specified data table. 
DataTableExporter exporter = worksheet.CreateDataTableExporter(range, dataTable, true);
// Handle value conversion errors.
exporter.CellValueConversionError += exporter_CellValueConversionError;

// Specify a custom converter for the "As Of" column.
DateTimeToStringConverter toDateStringConverter = new DateTimeToStringConverter();
exporter.Options.CustomConverters.Add("As Of", toDateStringConverter);
// Set the export value for empty cell.
toDateStringConverter.EmptyCellValue = "N/A";
// Specify that empty cells and cells with errors should be processed.
exporter.Options.ConvertEmptyCells = true;
exporter.Options.DefaultCellValueToColumnTypeConverter.SkipErrorValues = false;

// Perform the export.
exporter.Export();

// A custom method that displays the resulting data table.
ShowResult(dataTable);


// A custom converter that converts DateTime values to "Month-Year" text strings.
class DateTimeToStringConverter : ICellValueToColumnTypeConverter
{
    public bool SkipErrorValues { get; set; }
    public CellValue EmptyCellValue { get; set; }

    public ConversionResult Convert(Cell readOnlyCell, CellValue cellValue, Type dataColumnType, out object result)
    {
        result = DBNull.Value; 
        ConversionResult converted = ConversionResult.Success;
        if (cellValue.IsEmpty) {
            result = EmptyCellValue;
            return converted;
        }
        if (cellValue.IsError) {
            // You can return an error, subsequently the exporter throws an exception if the CellValueConversionError event is unhandled.
            //return SkipErrorValues ? ConversionResult.Success : ConversionResult.Error;
            result = "N/A";
            return ConversionResult.Success;
        }
        result =  String.Format("{0:MMMM-yyyy}",cellValue.DateTimeValue);
        return converted;
    }
}

void exporter_CellValueConversionError(object sender, CellValueConversionErrorEventArgs e) {
    MessageBox.Show("Error in cell " + e.Cell.GetReferenceA1());
    e.DataTableValue = null;
    e.Action = DataTableExporterAction.Continue;
}

#Export In-Cell Images

You can also use ICellValueToColumnTypeConverter to export image values to a DataTable.

The following code snippet shows the ICellValueToColumnTypeConverter implementation that converts cell image data to images in PNG format:

using DevExpress.Spreadsheet;
using DevExpress.Spreadsheet.Export;

Worksheet worksheet = spreadsheetControl1.Document.Worksheets[0];
DataTable dataTable = worksheet.CreateDataTable(worksheet["A1:C4"], true);
dataTable.Columns["Image"].DataType = typeof(byte[]);
var exporter = worksheet.CreateDataTableExporter(worksheet["A1:C4"], dataTable, true);

MyConverter converter = new MyConverter();
converter.SkipErrorValues = true;
exporter.Options.CustomConverters.Add("Image", converter);
exporter.Export();

class MyConverter : ICellValueToColumnTypeConverter {
    public bool SkipErrorValues { get; set; }
    public CellValue EmptyCellValue { get; set; }

    public ConversionResult Convert(Cell readOnlyCell, CellValue cellValue, Type dataColumnType, out object result)
    {
        result = null;
        ConversionResult converted = ConversionResult.Success;
        if (readOnlyCell.Value.IsCellImage)
            result = readOnlyCell.Value.ImageValue.GetImageBytes(DevExpress.Office.Utils.OfficeImageFormat.Png);
        return converted;
    }
}