Create Workbooks

How to Create Workbooks with Aspose.Cells FOSS for Java

Overview

This guide shows how to create an Excel workbook, populate cells with typed values, apply formatting, and save the result to .xlsx.

Step 1: Create a Workbook

Instantiate a Workbook and access the default worksheet via getWorksheets().get(0). Rename the sheet with setName() and call save() to write the output to an XLSX file:

import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    sheet.setName("Report");
    workbook.save("report.xlsx");
}

Step 2: Set Cell Values

Use getCells().get(ref).putValue() to write typed values into specific cells. The method accepts String, double, int, or boolean arguments. Use setFormula() to store a formula string:

import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    sheet.getCells().get("A1").putValue("Product");
    sheet.getCells().get("B1").putValue("Revenue");
    sheet.getCells().get("A2").putValue("Widget A");
    sheet.getCells().get("B2").putValue(42500.75);
    sheet.getCells().get("C2").setFormula("=B2*1.2");
    workbook.save("values.xlsx");
}

Step 3: Apply Formatting

Retrieve a cell style with getStyle(), modify font and number-format properties, then apply it back with setStyle(). You can also adjust row height and column width through the row and column objects:

import com.aspose.cells_foss.Cell;
import com.aspose.cells_foss.Style;
import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    Cell b2 = sheet.getCells().get("B2");
    b2.putValue(42500.75);
    Style style = b2.getStyle();
    style.getFont().setBold(true);
    style.setCustom("#,##0.00");
    b2.setStyle(style);
    sheet.getCells().getRows().get(0).setHeight(22.0);
    sheet.getCells().getColumns().get(1).setWidth(16.0);
    workbook.save("styled.xlsx");
}

Step 4: Add AutoFilter

Call getAutoFilter().setRange() on a worksheet to define header cells that display Excel filter dropdowns. This stores the AutoFilter range in the XLSX metadata:

import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    sheet.getCells().get("A1").putValue("Product");
    sheet.getCells().get("B1").putValue("Region");
    sheet.getAutoFilter().setRange("A1:B1");
    workbook.save("filtered.xlsx");
}

See Also

 English