Skip to main content

DataTableExporterExtensions.Export(DataTableExporter) Method

Exports a cell range to a DataTable.

You need a license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this method in production code.

Namespace: DevExpress.Spreadsheet.Export

Assembly: DevExpress.Docs.v24.1.dll

NuGet Package: DevExpress.Document.Processor

Declaration

public static void Export(
    this DataTableExporter exporter
)

Parameters

Name Type Description
exporter DataTableExporter

An object that performs export to a data table.

Remarks

Use the WorksheetExtensions.CreateDataTableExporter method to create a new DataTableExporter instance. Call its Export method to export the specified cell range to the DataTable.

You can implement a ICellValueToColumnTypeConverter interface to control the conversion process (analyze cell values and modify them as required). See the How to: Use a Custom Converter for Export to a DataTable topic for details.

Example

The example below shows how to export a cell range to a System.Data.DataTable object.

DataExport_Simple

View Example

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

Worksheet worksheet = spreadsheetControl1.Document.Worksheets.ActiveWorksheet;
CellRange range = worksheet.Selection;
bool rangeHasHeaders = this.barCheckItemHasHeaders1.Checked;

// Create a data table with column names obtained from the first row in a range if it has headers.
// 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, rangeHasHeaders);

//Validate cell value types. If cell value types in a column are different, the column values are exported as text.
int firstDataRowIndex = rangeHasHeaders ? 1 : 0;
int rowCount = range.RowCount;
if (firstDataRowIndex < rowCount) {
    for (int col = 0; col < range.ColumnCount; col++) {
        CellValueType cellType = range[firstDataRowIndex, col].Value.Type;
        for (int r = firstDataRowIndex + 1; r < rowCount; r++) {
            if (cellType != range[r, col].Value.Type) {
                dataTable.Columns[col].DataType = typeof(string);
                break;
            }
        }
    }
}

// Create the exporter that obtains data from the specified range, 
// skips the header row (if required) and populates the previously created data table. 
DataTableExporter exporter = worksheet.CreateDataTableExporter(range, dataTable, rangeHasHeaders);
// Handle value conversion errors.
exporter.CellValueConversionError += exporter_CellValueConversionError;

// Perform the export.
exporter.Export();
void exporter_CellValueConversionError(object sender, CellValueConversionErrorEventArgs e)
{
MessageBox.Show("Error in cell " + e.Cell.GetReferenceA1());
e.DataTableValue = null;
e.Action = DataTableExporterAction.Continue;
}
See Also