Skip to content
Dirk Fauth edited this page Jan 5, 2026 · 1 revision

Export

NatTable supports exporting the structure to an Excel spreadsheet. For this no additional layer is required. Everything is done via configuration and command execution.

Commands

ILayerCommand ILayerCommandHandler Description
ExportCommand ExportCommandHandler Executing this command will start the process for exporting the NatTable to an Excel file.

The ExportCommandHandler is registered to the GridLayer by default. If you don't use the GridLayer, you need to register it to your top-most layer (e.g. the ViewportLayer) yourself in order to make exporting work.

Configuration Attributes

The export feature can be configured via ConfigRegistry. The corresponding configuration attributes are defined in the class ExportConfigAttributes.

ConfigAttribute Type Description
ExportConfigAttributes.EXPORTER ILayerExporter Configure the ILayerExporter that should be used to export the NatTable.
ExportConfigAttributes.EXPORT_FORMATTER IExportFormatter Configure the formatter that should be used to format the value that should be exported. By default the values will be formatted as String representation of the value.
ExportConfigAttributes.DATE_FORMAT String Configure the format to use for exporting Date or Calendar objects. This configuration is only interpreted if an IExportFormatter returns an object of type Date or Calendar.
ExportConfigAttributes.NUMBER_FORMAT String Configure the format to use for exporting Number objects. This configuration is only interpreted if an IExportFormatter returns an object of type Number. The possible values are defined by BuiltinFormats.
ExportConfigAttributes.TABLE_EXPORTER ITableExporter Configure the ITableExporter that should be used to export the NatTable.

Default Configurations

You can find the default configurations for exporting in the DefaultExportBindings. These are aggregated by the DefaultGridLayerConfiguration which are added to the GridLayer as default configuration. If you don't use a GridLayer or not using the GridLayer with the default configuration, you need to add the necessary configurations yourself! Also note that the key binding for CTRL + E is registered to execute the ExportAction in the DefaultExportBindings.

There is also the DefaultImageExportBindings class to easily add the image export capability and bind it to CTRL + I.

Exporter

The ITableExporter is the exporter that is used to export the NatTable and gives the implementor full control on how the export should be done. The ILayerExporter is an exporter that is used to export a NatTable data driven by iterating over the content. Internally an anonymous implementation of ITableExporter is used that retrieves the configured ILayerExporter for exporting the data.

There are two default implementations of ITableExporter:

  • Anonymous internal implementation
    • Contained in NatTable Core package inside NatExporter
    • Iterates over the data and makes use of the configured ILayerExporter
  • ImageExporter
    • Contained in NatTable Core package
    • Exports a NatTable to an image

There are four default implementations of ILayerExporter:

  • CsvExporter
    • Contained in NatTable Core package
    • Exports to CSV format
  • ExcelExporter
    • Contained in NatTable Core package
    • Exports to an XML structure based format
  • HSSFExcelExporter
    • Contained in NatTable POI extension
    • Exports to Excel '97(-2007) file format by using Apache POI
  • XSSFExcelExporter
    • Contained in NatTable POI extension
    • Exports to Excel 2007 OOXML (.xlsx) file format by using Apache POI

You need to configure one of those implementations via the ExportConfigAttributes.EXPORTER ConfigAttribute to the ConfigRegistry in order to make exporting work.

configRegistry.registerConfigAttribute(
    ExportConfigAttributes.EXPORTER, 
    new HSSFExcelExporter());

Additionally it is possible to set the ILayerExporter to use with the ExportCommand, which makes it easier to provide different export functions in one NatTable instance.

The following snippet is part of a menu configuration that adds a menu to the corner region of a grid that contains a Export sub-menu, which provides the entries Export to CSV, Export to Excel and the export to an image by using PopupMenuBuilder#withExportToImageMenuItem().

return super.createCornerMenu(natTable) 
    .withSubMenu("Export") 
        .withMenuItemProvider((natTable1, popupMenu) -> { 
            MenuItem export = new MenuItem(popupMenu, SWT.PUSH); 
            export.setText(Messages.getLocalizedMessage("Export to CSV")); 
            export.setEnabled(true); 
            export.addSelectionListener(new SelectionAdapter() { 
                @Override 
                public void widgetSelected(SelectionEvent e) { 
                    natTable.doCommand( 
                        new ExportCommand( 
                            natTable.getConfigRegistry(), 
                            natTable.getShell(), 
                            true, 
                            true, 
                            new CsvExporter())); 
                } }); 
            }) 
        .withMenuItemProvider((natTable1, popupMenu) -> { 
            MenuItem export = new MenuItem(popupMenu, SWT.PUSH); 
            export.setText(Messages.getLocalizedMessage("Export to Excel")); 
            export.setEnabled(true); 
            export.addSelectionListener(new SelectionAdapter() { 
                @Override 
                public void widgetSelected(SelectionEvent e) { 
                    natTable.doCommand( 
                        new ExportCommand( 
                            natTable.getConfigRegistry(), 
                            natTable.getShell(), 
                            true, 
                            true)); 
                } 
            }); 
        }) 
        .withExportToImageMenuItem() 
        .buildSubMenu();

By default NatTable is configured to export every value as String, formatted by converting the value to String via the registered IDisplayConverter configured for the cell. This ensures that the values in the resulting Excel file are the same as shown in the NatTable instance in the application and is done by the DefaultExportFormatter. Changing this is quite easy by implementing and registering an IExportFormatter.

class ExampleExportFormatter implements IExportFormatter {
	@Override
	public Object formatForExport(ILayerCell cell, IConfigRegistry configRegistry) {
		Object data = cell.getDataValue();
		if (data != null) {
			try {
				if (data instanceof Boolean) {
					return ((Boole-an)data).booleanValue() ? "X" : ""; 
				}
				else if (data instanceof Date) {
					return data;
				}
				else {
					return data.toString();
				}
			}
			catch (Exception e) {
					return data.toString();
			}
		}
		return ""; 
	}
}
...
configRegistry.registerConfigAttribute(
	ExportConfigAttributes.EXPORT_FORMATTER, 
	new ExampleExportFormatter(),
	DisplayMode.NORMAL,
	GridRegion.BODY);
...

Note:
For exporting the registered IExportFormatter is used and not an IDisplayConverter. This adds the possibility to change the export from the visualization in the application. A possible configured IDisplayConverter is only evaluated in case the DefaultExportFormatter is used, which converts every value in the resulting Excel sheet to String. If you want to have Boolean, Calendar, Date or Number values in the Excel sheet, you need to return the object of the corresponding type in your IExportFormatter instead of a converted value.

Multi-table Export

The export functionality is only working on the NatTable instance the exporter is connected to. But you are also able to export multiple NatTable instances into one spreadsheet by using framework capabilities. For this you need to use NatExporter.exportMultipleNatTables() which needs the ILayerExporter to use and the collection of NatTable instances to export as method parameters. The NatTable instances to export need to be provided as Map<String, NatTable> where the key will be used as spreadsheet title.

Map<String, NatTable> export = 
    new HashMap<String, NatTable>();
export.put("Persons", natTable);
export.put("Numbers", numberNatTable);
new NatExporter(Display.getCurrent().getActiveShell())
	.exportMultipleNatTables(new HSSFExcelExporter(), export);

Note:
There is no default ILayerCommandHandler implementation that provides support for multi-table export. You need to implement and register such an implementation yourself, as the framework can not know which tables should be exported at once.

Exporter Configurations

By default the CsvExporter, ExcelExporter, HSSFExcelExporter and the XSSFExcelExporter are using the FileOutputStreamProvider which opens a file dialog, so a user is able to specify where to save the resulting export file. It is also possible to create an instance of the exporter implementations by using a FilePathOutputStreamProvider, which can be used to specify a fixed target location to avoid the user interaction.

The ExcelExporter comes with additional internal configuration settings:

  • setCharset(String)
    configure the charset that should be used as replacement for the charset value in the export header
  • setSheetname(String)
    configure the sheet name of the Excel sheet

The HSSFExcelExporter and the XSSFExcelExporter come with some additional internal configuration settings to modify the export format:

  • setApplyBackgroundColor(boolean)
    turn off/on exporting the background color
  • setApplyCellBorders(boolean)
    configure whether this exporter should render cell borders on all cells
  • setApplyCellDimensions(boolean)
    configure whether this exporter should apply the cell dimensions to the same size configuration the NatTable shows
  • setApplyColumnWidths(boolean)
    configure whether this exporter should apply the column widths to the same size configuration the NatTable shows
  • setApplyRowHeights(boolean)
    configure whether this exporter should apply the row heights to the same size configuration the NatTable shows
  • setExportOnSameSheet(boolean)
    if multiple NatTable instances are exported at once, this setting can be used to configure if all instances should be exported on the same Excel sheet, or if every instance should be exported on its own sheet
  • setSheetname(String)
    configure the sheet name of the Excel sheet
  • setApplyTextWrapping(boolean)
    configure whether the export should check for text wrapping configuration in NatTable and apply the corresponding style attribute in the export
  • setApplyVerticalTextConfiguration(boolean)
    configure whether vertical rendered text in NatTable should be rendered vertical in the export too

Exporting formulas

Using the Apache POI based exporters, it is possible to also export formulas.

If formulas are supported in the NatTable and those formulas should be also exported instead of the values, you need to set the FormulaParser via setFormulaParser(FormulaParser). You can influence the appearance of Number values by setting a NumberFormat via setNumberFormat(NumberFormat). Note that this only influences Number values returned by the FormulaParser.

Exporting images

Using the Apache POI based exporters, it is possible to also export images.

To export images to the resulting Excel sheet an IExportFormatter needs to be registered that returns an InputStream. The following snippet shows a simple IExportFormatter that exports the checkbox images for boolean values.

class ExampleExportFormatter implements IExportFormatter { 
    @Override public Object formatForExport( ILayerCell cell, IConfigRegistry configRegistry) { 
        Object data = cell.getDataValue(); 
        if (data != null) { 
            try { 
                if (data instanceof Boolean) { 
                    if ((Boolean) data) { 
                        return GUIHelper 
                        .getInternalImageUrl("checked") 
                        .openStream(); 
                    } 
                    return GUIHelper 
                        .getInternalImageUrl("unchecked") 
                        .openStream(); 
                } else { 
                    return data.toString(); 
                } 
            } catch (Exception e) { 
                return data.toString(); 
            } 
        } 
        return ""; 
    } 
}

Note:
The InputStream is closed internally on processing the export. So it is not necessary to deal with that in the outside.

NatExporter Configurations

The NatExporter is the central class for exporting a NatTable. It orchestrates the export operation and is created and used by the ExportCommandHandler. It has several configuration options, which can also be set via constructor or corresponding setter methods. It is also possible to specify those settings via the ExportCommand if the default ExportCommandHandler is used.

Configuration Description NatExporter ExportCommand
Synchronous execution
Configure if the export operation should be done sychronously or asynchronously. Default is asynchronous execution.
Only via constructors available
Progress Reporting
Configure if the export progress should be visualized by using a ProgressMonitorDialog or a custom shell with a ProgressBar.
Constructors and NatExporter#setUseProgressDialog(boolean) available
Open result
Configure if the created export result should be opened after the export is finished.
Constructors and NatExporter#setOpenResult(boolean) available
Success Reporting
Configure the Runnable that should be executed after the export finished successfully. Useful in case openResult is set to false so an alternative for reporting the export success can be configured.
Constructors and NatExporter#setSuccessRunnable(Runnable) available
Pre-Rendering
Configure in-memory pre-rendering. It is used to ensure that cell dimensions that are calculated on rendering are applied before the export. This feature is enabled by default.
NatExporter#enablePreRendering()
NatExporter#disablePreRendering()
-

Error Reporting

Errors that occur on exporting a NatTable are propagated wrapped in a RuntimeException to the calling NatExporter. For handling the exceptions NatExporter#handleExportException(Exception) is called, that by default logs the exception and opens an ExceptionDialog. To customize the behavior you can extend NatExporter and override handleExportException(Exception).

Related Examples

  • Tutorial Examples - Additional Functions - ExcelExportExample
    This example shows how to trigger an export for a NatTable. It produces a XLS Excel Export in HTML format.
  • Tutorial Examples - Additional Functions - GridExcelExportExample
    This example shows how to trigger an export for a NatTable grid. This example does not add any further export configuration and produces a XLS Excel Export in HTML format
  • Tutorial Examples - Additional Functions - GridExcelExportFormatterExample
  • This example shows how to trigger an export for a NatTable grid. This example adds additional export configuration and supports exporting to CSV, XLS (Excel '97(-2007)) and XLSX (Excel 2007 OOXML (.xlsx)).
  • Tutorial Examples - Additional Functions - MultiExportExample
    This example shows how to trigger an export for multiple NatTable instances into one Excel with multiple sheets.

Clone this wiki locally