Working with Spreadsheet Management

Working with Spreadsheet Management

Working with Spreadsheet Management

Aspose.Cells for Java provides a complete API for creating and manipulating Excel spreadsheets programmatically. The Workbook class is the entry point for all spreadsheet operations from loading a file off disk to writing cell values and saving in a target format.


Creating a New Workbook

Use the no-argument constructor to create an empty workbook. A single blank worksheet named Sheet1 is added automatically.

import com.aspose.cells.foss.Workbook;
import com.aspose.cells.foss.WorksheetCollection;
import com.aspose.cells.foss.Worksheet;

Workbook workbook = new Workbook();
WorksheetCollection sheets = workbook.getWorksheets();
Worksheet sheet = sheets.get(0);
System.out.println("Sheet name: " + sheet.getName()); // Sheet1

Loading a Workbook from a File

Pass a file path to the Workbook(fileName) constructor to open an existing .xlsx or .ods file. Use Workbook(fileName, options) to supply LoadOptions when you need to control format detection or password handling.

import com.aspose.cells.foss.Workbook;
import com.aspose.cells.foss.LoadOptions;

// Simple load
Workbook workbook = new Workbook("data/report.xlsx");

// Load with explicit options
LoadOptions opts = new LoadOptions();
Workbook workbookWithOpts = new Workbook("data/report.xlsx", opts);

Loading a Workbook from a Stream

Workbook(stream) and Workbook(stream, options) accept any java.io.InputStream. This is useful when the file comes from a network resource, a database BLOB, or an in-memory byte array.

import com.aspose.cells.foss.Workbook;
import java.io.FileInputStream;
import java.io.InputStream;

try (InputStream is = new FileInputStream("data/template.xlsx")) {
    Workbook workbook = new Workbook(is);
    System.out.println("Worksheets: " + workbook.getWorksheets().getCount());
}

Accessing and Managing Worksheets

Workbook.getWorksheets() returns a WorksheetCollection. Retrieve sheets by index or by name, iterate over all sheets, and add or remove sheets as needed.

import com.aspose.cells.foss.Workbook;
import com.aspose.cells.foss.WorksheetCollection;
import com.aspose.cells.foss.Worksheet;

Workbook workbook = new Workbook();
WorksheetCollection sheets = workbook.getWorksheets();

// Access by index
Worksheet first = sheets.get(0);
System.out.println(first.getName()); // Sheet1

// Add a named sheet
int idx = sheets.add("Summary");
Worksheet summary = sheets.get(idx);
summary.setName("Summary");

// Iterate all sheets
for (Worksheet ws : sheets) {
    System.out.println("Sheet: " + ws.getName());
}

// Remove a sheet by name
sheets.removeAt("Sheet1");
System.out.println("Remaining sheets: " + sheets.getCount());

Reading and Writing Cell Values

Navigate to a cell using Worksheet.getCells(), which returns a Cells collection. Retrieve a Cell by name (e.g. "A1") or by zero-based row/column index. Use putValue() to write primitive values and getValue() / getStringValue() to read them back.

import com.aspose.cells.foss.Workbook;
import com.aspose.cells.foss.Worksheet;
import com.aspose.cells.foss.Cells;
import com.aspose.cells.foss.Cell;

Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
Cells cells = sheet.getCells();

// Write values
cells.get("A1").putValue("Product");
cells.get("B1").putValue("Units Sold");

// Write by row/column index (0-based)
Cell a2 = cells.get(1, 0);
a2.putValue("Widget A");

Cell b2 = cells.get(1, 1);
b2.putValue(1200);

// Read back
System.out.println(a2.getStringValue()); // Widget A
System.out.println(b2.getValue());       // 1200

Setting Cell Formulas

Assign a formula string to a cell via setFormula(). Aspose.Cells evaluates formulas when the workbook is saved or when calculation is triggered explicitly.

import com.aspose.cells.foss.Workbook;
import com.aspose.cells.foss.Cells;
import com.aspose.cells.foss.Cell;

Workbook workbook = new Workbook();
Cells cells = workbook.getWorksheets().get(0).getCells();

cells.get("A1").putValue(100);
cells.get("A2").putValue(200);

Cell a3 = cells.get("A3");
a3.setFormula("=SUM(A1:A2)");
System.out.println("Formula: " + a3.getFormula()); // =SUM(A1:A2)

Saving a Workbook

Use Workbook.save(fileName) to write the workbook to disk. The output format is determined by the file extension; use .xlsx for Excel workbooks.

import com.aspose.cells.foss.Workbook;

Workbook workbook = new Workbook();
workbook.getWorksheets().get(0).getCells().get("A1").putValue("Hello");

// Save to file -- format inferred from .xlsx extension
workbook.save("output/result.xlsx");

Releasing Resources

Workbook implements AutoCloseable. Use a try-with-resources block to ensure the workbook’s internal resources are released promptly after use.

import com.aspose.cells.foss.Workbook;

try (Workbook workbook = new Workbook("data/large.xlsx")) {
    workbook.save("output/large_modified.xlsx");
}
// workbook.close() called automatically

Tips and Best Practices

  • Always use try-with-resources (try (Workbook wb = new Workbook(...))) for large files to avoid holding file handles open.
  • Prefer cells.get(row, column) over cells.get(cellName) in hot loops; the integer overload avoids repeated cell-name parsing.
  • Call workbook.getWorksheets().getCount() before accessing sheets by index to avoid IndexOutOfBoundsException.
  • Name your sheets explicitly with setName() after add() so downstream code can look them up by name rather than by fragile index.
  • Do not rely on formula results immediately after setFormula(); save first or reload if you need computed values in the same session.

Common Issues

IssueCauseFix
WorkbookLoadException on new Workbook(fileName)File path incorrect or file lockedVerify the path exists and is readable; close other applications holding the file
get(index) throws IndexOutOfBoundsExceptionSheet index beyond getCount() - 1Check sheets.getCount() before accessing; use add() to create a new sheet
Formula cell returns empty getValue()Formulas not auto-calculated in-memorySave the workbook and reload it to obtain formula results
Output file is corrupt after save()Wrong file extensionEnsure the file name ends with .xlsx; format is inferred from the extension

FAQ

How do I rename a worksheet?

Retrieve the Worksheet object and call setName(name):

workbook.getWorksheets().get(0).setName("Sales Data");

How do I check how many sheets a workbook has?

int count = workbook.getWorksheets().getCount();

Can I add multiple sheets in one call?

No. Call worksheets.add(sheetName) once per sheet. Each call returns the index of the newly created sheet.

How do I check the type of a cell value?

Cell cell = cells.get("A1");
System.out.println(cell.getType()); // CellValueType enum value

API Reference Summary

Class / MethodDescription
Workbook()Creates an empty workbook with one blank sheet
Workbook(fileName)Loads a workbook from a file path
Workbook(stream)Loads a workbook from an InputStream
Workbook(fileName, options)Loads a workbook with LoadOptions
Workbook.getWorksheets()Returns the WorksheetCollection
Workbook.save(fileName)Saves to a file (format inferred from extension)
Workbook.save(stream, format)Saves to a stream with explicit SaveFormat
WorksheetCollection.get(index)Returns sheet by zero-based index
WorksheetCollection.get(name)Returns sheet by name
WorksheetCollection.add(sheetName)Adds a named sheet; returns its index
WorksheetCollection.getCount()Number of sheets in the workbook
WorksheetCollection.removeAt(sheetName)Removes a sheet by name
Worksheet.getCells()Returns the Cells collection for this sheet
Worksheet.getName() / setName()Gets or sets the sheet tab name
Cells.get(cellName)Returns a Cell by name (e.g. “A1”)
Cells.get(row, column)Returns a Cell by zero-based row/column
Cell.putValue(value)Writes a value to the cell
Cell.getValue()Reads the cell value as Object
Cell.getStringValue()Reads the cell value as a String
Cell.setFormula(formula)Sets a formula string (e.g. “=SUM(A1:A2)”)
LoadOptionsConfiguration for workbook loading
SaveFormatEnum of format constants (format is inferred from file extension; not passed to save())

See Also