Vaadin Spreadsheet - Basic Use
 Edit This Page

Basic Use

Spreadsheet is a Vaadin component, which you can use as you would any component. You can create it, or load from an Excel file, create cells and new sheets, define formulas, and so forth. In the following, we go through these basic steps.

Creating a Spreadsheet

The default constructor for Spreadsheet creates an empty spreadsheet with a default sheet. The spreadsheet component has full size by default, so the containing layout must have defined size in both dimensions; a spreadsheet may not have undefined size.

In the following example, we create an empty spreadsheet with a fixed size and add it to a layout.

import com.vaadin.addon.spreadsheet.Spreadsheet;
...
private Spreadsheet spreadsheet = null;

@Override
protected void init(VaadinRequest request) {
   VerticalLayout layout = new VerticalLayout();
   layout.setSizeFull();
   setContent(layout);

   spreadsheet = new Spreadsheet();
   layout.addComponent(spreadsheet);
}

An empty spreadsheet automatically gets an initial worksheet with some default size and settings.

Loading an Excel Spreadsheet

To open an existing Excel file in Spreadsheet, you need to pass an Excel file to the Spreadsheet constructor.

import com.vaadin.addon.spreadsheet.Spreadsheet;
...
private Spreadsheet spreadsheet;

@Override
protected void init(VaadinRequest request) {
   final VerticalLayout layout = new VerticalLayout();
   layout.setSizeFull();
   setContent(layout);

   File sampleFile = new File("C:/Users/John/Calculator.xlsx");
   try {
       spreadsheet = new Spreadsheet(sampleFile);
   } catch (IOException e) {
       e.printStackTrace();
       return;
   }
   layout.addComponent(spreadsheet);
}

You can load an Excel file from the local filesystem with a File reference or from memory or other source with an InputStream.

Working with an Apache POI Workbook

If you have an Apache POI workbook created otherwise, you can wrap it to Spreadsheet with the respective constructor.

You can access the underlying workbook with getWorkbook(). However, if you make modifications to the workbook, you must allow the spreadsheet update itself by calling appropriate update methods for the modified element or elements.

Working with Sheets

A "spreadsheet" in reality works on a workbook, which contains one or more worksheets. You can create new sheets and delete existing ones with createNewSheet() and deleteSheet(), respectively.

// Recreate the initial sheet to configure it
Spreadsheet sheet = new Spreadsheet();
sheet.createNewSheet("New Sheet", 10, 5);
sheet.deleteSheet(0);

When a sheet is deleted, the index of the sheets with a higher index is decremented by one. When the active worksheet is deleted, the next one by index is set as active, or if there are none, the previous one.

All operations on the spreadsheet content are done through the currently active worksheet. You can set an existing sheet as active with setActiveSheetIndex().