[]
IWorksheet provides access to worksheet content, ranges, views, events, and protection features, which can be used to read and modify cell data, manage worksheet state, and perform worksheet-related operations. This interface is typically obtained through Workbook.getActiveSheet() or Workbook.getWorksheets().
IWorksheet sheet = workbook.getActiveSheet();
IRange range = sheet.getRange("A1:B2");
range.setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
voidactivate()voidvoidautoMerge(IRange range,
AutoMergeDirection direction) voidautoMerge(IRange range,
AutoMergeDirection direction,
AutoMergeMode mode) voidautoMerge(IRange range,
AutoMergeDirection direction,
AutoMergeMode mode,
AutoMergeSelectionMode selectionMode) copy()copyAfter(IWorksheet targetSheet) copyBefore(IWorksheet targetSheet) voiddelete()evaluate(String formula,
IFormulaResolver resolver) voidfreezePanes(int row,
int column) voidfreezeTrailingPanes(int row,
int column) voidfromJson(InputStream stream) voidfromJson(InputStream stream,
DeserializationOptions deserializationOptions) voidvoidfromJson(String json,
DeserializationOptions deserializationOptions) IAutoFilter object for the worksheet.booleanbooleanIAutoMergeRangeInfo objects that represent all auto merge range information in the current worksheet.byte[]getCells()IRange object that represents all cells in the worksheet.intIRange object that represents all the columns on the worksheet.IComments collection that represents all the comments in the worksheet.ICommentsThreaded collection that represents all threaded comments in the worksheet.booleanbooleanintintintintintgetIndex()getName()getNames()INames collection that represents all the worksheet-specific names (names defined with the "WorksheetName!" prefix).IOutline object that represents the outline for the worksheet.IPageSetup object for this worksheet.getPanes()booleangetRange(int row,
int column) IRange object for the cell at the specified row and column.getRange(int row,
int column,
int rowCount,
int columnCount) IRange object for the specified row, column, row count, and column count.IRange object with the specified reference.intgetRows()IRange object that represents all rows in the worksheet.IScenarios object that represents the collection of What-If analysis scenarios in the worksheet.IShapes collection that contains all shapes on the worksheet or chart sheet.booleanbooleangetSort()intintdoubledoubledoubledoubleITable objects in the worksheet.getTag()getType()getUsedRange(EnumSet<UsedRangeType> type) Workbook that contains this worksheet.move()moveAfter(IWorksheet targetSheet) moveBefore(IWorksheet targetSheet) voidprotect()voidvoidsave(OutputStream fileStream,
SaveFileFormat fileFormat) voidsave(OutputStream fileStream,
SaveOptionsBase options) voidvoidsave(String fileName,
SaveFileFormat fileFormat) voidsave(String fileName,
SaveOptionsBase options) voidselect()voidselect(boolean replace) voidsetAutoFilterMode(boolean value) voidsetAutoGenerateColumns(boolean value) voidsetBackgroundPicture(byte[] picture) voidsetCellType(BaseCellType cellType) voidsetColumnCount(int value) voidsetDataSource(Object value) voidsetFixedPageBreaks(boolean value) voidsetFrozenLineColor(Color value) voidsetIndex(int value) voidvoidsetProtection(boolean value) voidsetRowCount(int value) voidsetShowColumnOutline(boolean value) voidsetShowRowOutline(boolean value) voidsetStandardHeight(double value) voidsetStandardHeightInPixel(double value) voidsetStandardWidth(double value) voidsetStandardWidthInPixel(double value) voidsetTabColor(Color value) voidvoidsetVisible(Visibility value) voidvoidsplitPanes(int row,
int column) voidtoImage(OutputStream stream,
ImageType imageType) voidtoImage(OutputStream stream,
ImageType imageType,
ImageSaveOptions options) voidvoidtoImage(String imageFile,
ImageSaveOptions options) toJson()toJson(SerializationOptions serializationOptions) voidtoJson(OutputStream stream) voidtoJson(OutputStream stream,
SerializationOptions serializationOptions) voidvoidvoidvoidvoid
IWorksheet detailSheet = workbook.getWorksheets().add();
final String[] activatedSheetName = {null};
detailSheet.getActivatedEvent().addListener(new EventHandler<EventArgs>() {
public void invoke(Object sender, EventArgs e) {
activatedSheetName[0] = ((IWorksheet)sender).getName();
}
});
detailSheet.activate();
IWorksheet detailSheet = workbook.getWorksheets().add();
final String[] deletedSheetName = {null};
detailSheet.getBeforeDeleteEvent().addListener(new EventHandler<EventArgs>() {
public void invoke(Object sender, EventArgs e) {
deletedSheetName[0] = ((IWorksheet)sender).getName();
}
});
detailSheet.delete();
final String[] changedAddress = {null};
worksheet.getChangedEvent().addListener(new EventHandler<RangeEventArgs>() {
public void invoke(Object sender, RangeEventArgs e) {
changedAddress[0] = e.getRange().getAddress();
}
});
worksheet.getRange("B2").setValue("Updated");
IWorksheet detailSheet = workbook.getWorksheets().add();
final String[] deactivatedSheetName = {null};
worksheet.getDeactivatedEvent().addListener(new EventHandler<EventArgs>() {
public void invoke(Object sender, EventArgs e) {
deactivatedSheetName[0] = ((IWorksheet)sender).getName();
}
});
detailSheet.activate();
final String[] selectionAddress = {null};
worksheet.getSelectionChangeEvent().addListener(new EventHandler<RangeEventArgs>() {
public void invoke(Object sender, RangeEventArgs e) {
selectionAddress[0] = e.getRange().getAddress();
}
});
worksheet.getRange("C3:D4").select();
The returned IControlCollection provides access to the form controls contained in the worksheet, such as buttons, check boxes, and drop-down lists.
worksheet.getControls().addButton(20, 20, 100, 24);
IControlCollection controls = worksheet.getControls();
IControl control = controls.get(0);
Use the returned IWorksheetView object to access worksheet display settings such as gridline visibility, reading direction, scroll position, zoom, and view type.
worksheet.getRange("A1").setValue("Name");
IWorksheetView sheetView = worksheet.getSheetView();
sheetView.setDisplayGridlines(false);
sheetView.setZoom(150);
IWorksheetView object that represents the view settings of this worksheet.The returned value indicates whether the worksheet is currently shown, hidden, or very hidden.
IWorksheet detailSheet = workbook.getWorksheets().add();
detailSheet.setName("Detail");
detailSheet.setVisible(Visibility.Hidden);
Visibility visibility = detailSheet.getVisible();
Visibility.Visible, Visibility.Hidden, or Visibility.VeryHidden.Use this method to display the worksheet, hide it so that users can show it again, or make it very hidden so that it cannot be shown directly through the user interface.
IWorksheet detailSheet = workbook.getWorksheets().add();
detailSheet.setName("Detail");
detailSheet.setVisible(Visibility.Hidden);
Visibility currentVisibility = detailSheet.getVisible();
value - The worksheet visibility state, such as Visibility.Visible, Visibility.Hidden, or Visibility.VeryHidden.The active cell is returned as a single-cell IRange. Returns null if the worksheet does not have a current selection.
worksheet.getRange("C3").activate();
IRange cell = worksheet.getActiveCell();
cell.setValue("Active");
IRange that represents the active cell, or null if the worksheet does not have a current selection.IAutoFilter object for the worksheet.The returned object provides access to the filter range, filters, and sort settings for the worksheet's AutoFilter. Returns null if AutoFilter is not enabled on the worksheet.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200}
});
worksheet.getRange("A1:B3").autoFilter();
IAutoFilter autoFilter = worksheet.getAutoFilter();
IRange filterRange = autoFilter.getRange();
IAutoFilter object for the worksheet, or null if AutoFilter is not enabled.This property indicates whether the worksheet is showing the AutoFilter drop-down buttons for filtered ranges.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200}
});
worksheet.getRange("A1:B3").autoFilter();
worksheet.setAutoFilterMode(true);
boolean autoFilterMode = worksheet.getAutoFilterMode();
true if the AutoFilter drop-down arrows are currently displayed on the sheet; otherwise, false.This property indicates whether the worksheet is showing the AutoFilter drop-down buttons for filtered ranges.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200}
});
worksheet.getRange("A1:B3").autoFilter();
worksheet.setAutoFilterMode(false);
value - true if the AutoFilter drop-down arrows are currently displayed on the sheet; otherwise, false.IRange object that represents all the columns on the worksheet.The returned range can be used to access or manipulate columns by index.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B1").setValue("Value");
IRange columns = worksheet.getColumns();
IRange firstColumn = columns.get(0);
IRange object that represents all the columns on the worksheet.IRange object that represents all cells in the worksheet.The returned range covers the entire worksheet, including cells that are not currently in use.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B2").setValue(100);
IRange cells = worksheet.getCells();
IRange firstCell = cells.get(0, 0);
IRange object that represents all cells in the worksheet.IComments collection that represents all the comments in the worksheet.Use this method to access and enumerate cell comments in the current worksheet.
worksheet.getRange("B2").addComment("Review this value");
IComments comments = worksheet.getComments();
IComment comment = comments.get(0);
IComments collection that represents all the comments in the worksheet.ICommentsThreaded collection that represents all threaded comments in the worksheet.Each item in the returned collection is an ICommentThreaded object. Threaded comments are stored in the collection in row-major order.
worksheet.getRange("C3").addCommentThreaded("Review this value", "Alex");
ICommentsThreaded commentsThreaded = worksheet.getCommentsThreaded();
ICommentThreaded comment = commentsThreaded.get(0);
ICommentsThreaded collection that contains all threaded comments in the worksheet.This value represents the worksheet's default column width setting.
worksheet.getRange("A:A").setUseStandardWidth(true);
worksheet.setStandardWidth(72.0);
double standardWidth = worksheet.getStandardWidth();
double firstColumnWidth = worksheet.getRange("A:A").getColumnWidth();
This value represents the worksheet's default column width setting in pixel units.
worksheet.getRange("A:A").setUseStandardWidth(true);
worksheet.setStandardWidthInPixel(80);
double standardWidthInPixel = worksheet.getStandardWidthInPixel();
double firstColumnWidthInPixel = worksheet.getRange("A:A").getColumnWidthInPixel();
This value represents the worksheet's default column width setting.
worksheet.getRange("A:A").setUseStandardWidth(true);
worksheet.setStandardWidth(72.0);
double firstColumnWidth = worksheet.getRange("A:A").getColumnWidth();
value - The standard column width, in points.This value represents the worksheet's default column width setting in pixel units.
worksheet.getRange("A:A").setUseStandardWidth(true);
worksheet.setStandardWidthInPixel(80);
double firstColumnWidthInPixel = worksheet.getRange("A:A").getColumnWidthInPixel();
value - The standard column width, in pixels.To get the corresponding pixel value, use getStandardHeightInPixel().
worksheet.setStandardHeight(18.0);
double standardHeight = worksheet.getStandardHeight();
To get the corresponding value in points, use getStandardHeight().
worksheet.setStandardHeightInPixel(24.0);
double standardHeightInPixel = worksheet.getStandardHeightInPixel();
worksheet.setStandardHeight(18.0);
value - The default row height, in points.
worksheet.setStandardHeightInPixel(24.0);
value - The default row height, in pixels.Filter mode indicates that a filter has been applied and the worksheet is actively filtering data. This differs from getAutoFilterMode(), which indicates whether AutoFilter is enabled on the worksheet.
worksheet.getRange("A1:B4").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200},
{"C", 100}
});
worksheet.getRange("A1:B4").autoFilter(1, 100);
boolean filterMode = worksheet.getFilterMode();
true if the worksheet is actively filtering data; otherwise, false.Use this method to access, add, and manage worksheet-level hyperlinks through the returned IHyperlinks collection.
worksheet.getRange("A1").setValue("Example App");
worksheet.getHyperlinks().add(worksheet.getRange("A1"), "https://www.example.com");
IHyperlinks hyperlinks = worksheet.getHyperlinks();
IHyperlink hyperlink = hyperlinks.get(0);
IHyperlinks collection that contains the hyperlinks in the worksheet.The returned value reflects the current worksheet order in the collection.
workbook.getWorksheets().add();
IWorksheet secondSheet = workbook.getWorksheets().get(1);
int index = secondSheet.getIndex();
workbook.getWorksheets().add();
IWorksheet secondSheet = workbook.getWorksheets().get(1);
secondSheet.setIndex(0);
value - The zero-based position of the worksheet in the workbook's worksheet collection.This value represents the current number of rows available in the worksheet.
worksheet.setRowCount(20);
int rowCount = worksheet.getRowCount();
This value represents the current number of rows available in the worksheet.
worksheet.setRowCount(20);
value - The row count of the worksheet.This value represents the number of columns currently defined on the worksheet. It reflects the value set through setColumnCount(int).
worksheet.setColumnCount(12);
int columnCount = worksheet.getColumnCount();
worksheet.setColumnCount(12);
value - The current number of columns in the worksheet.
byte[] picture = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("background.png"));
worksheet.setBackgroundPicture(picture);
byte[] backgroundPicture = worksheet.getBackgroundPicture();
byte[] picture = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("background.png"));
worksheet.setBackgroundPicture(picture);
picture - A byte array that contains the background image data, or null to remove the background image.This property returns the display name used to identify the worksheet in the workbook.
worksheet.setName("Summary");
String name = worksheet.getName();
This property Sets the display name used to identify the worksheet in the workbook.
worksheet.setName("Summary");
value - The name of the worksheet.INames collection that represents all the worksheet-specific names (names defined with the "WorksheetName!" prefix).
worksheet.getNames().add("LocalTotal", "=Sheet1!$A$1");
INames names = worksheet.getNames();
INames collection that represents all worksheet-specific names (names defined with the "WorksheetName!" prefix).IOutline object that represents the outline for the worksheet.Use the returned outline object to access and configure worksheet outline settings for grouped rows and columns.
IOutline outline = worksheet.getOutline();
outline.showLevels(1, 0);
IOutline object for the worksheet.This setting applies to SpreadJS (SJS) serialization and viewing scenarios.
worksheet.setShowRowOutline(false);
boolean showRowOutline = worksheet.getShowRowOutline();
true if outline symbols for grouped rows are displayed; otherwise, false.This setting applies to SpreadJS (SJS) serialization and viewing scenarios.
worksheet.setShowRowOutline(false);
value - true if outline symbols for grouped rows are displayed; otherwise, false.This setting applies to SpreadJS (SJS) serialization and viewing scenarios.
worksheet.setShowColumnOutline(false);
boolean showColumnOutline = worksheet.getShowColumnOutline();
true if outline symbols for grouped columns are displayed; otherwise, false.This setting applies to SpreadJS (SJS) serialization and viewing scenarios.
worksheet.setShowColumnOutline(false);
value - true if outline symbols for grouped columns are displayed; otherwise, false.Use this method to access existing PivotTable reports on the worksheet or to add new ones through the returned IPivotTables collection.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Category", "Amount"},
{"Beverages", 100},
{"Snacks", 200}
});
IPivotCache pivotCache = workbook.getPivotCaches().create(worksheet.getRange("A1:B3"));
worksheet.getPivotTables().add(pivotCache, worksheet.getRange("D1"), "SalesPivot");
IPivotTables pivotTables = worksheet.getPivotTables();
IPivotTables collection that contains all PivotTable reports on the worksheet.IRange object with the specified reference.Use this method to access a single cell, a contiguous cell range, or a non-contiguous range by using an A1-style reference string.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B1").setValue(100);
IRange range = worksheet.getRange("A1:B1");
range.getInterior().setColor(Color.GetLightYellow());
reference - The A1-style reference string that identifies the target cell or range.IRange object that represents the specified reference.IRange object for the cell at the specified row and column.Use this method to access a single cell by its zero-based row and column indexes. For example, (0, 0) refers to cell A1.
worksheet.getRange("A1").setValue("Name");
IRange cell = worksheet.getRange(0, 1);
cell.setValue(100);
row - The zero-based row index of the cell.column - The zero-based column index of the cell.IRange object that represents the cell at the specified row and column.IRange object for the specified row, column, row count, and column count.Use this method to access a rectangular range by its top-left cell and size.
IRange range = worksheet.getRange(0, 0, 2, 2);
range.setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
row - The starting row of the range.column - The starting column of the range.rowCount - The number of rows in the range.columnCount - The number of columns in the range.IRange object that starts at the specified row and column and spans the specified number of rows and columns.Returns an IRange that represents the currently selected cells. If the selection contains multiple areas, the returned range represents all selected areas. Returns null if the worksheet has no selection.
worksheet.getRange("A1:B2").select();
IRange selection = worksheet.getSelection();
selection.setValue("Selected");
null if the worksheet has no selection.IShapes collection that contains all shapes on the worksheet or chart sheet.Use this method to access and manage drawing objects such as shapes, pictures, and charts associated with the current sheet.
worksheet.getShapes().addShape(AutoShapeType.Rectangle, 20, 20, 100, 60);
IShapes shapes = worksheet.getShapes();
IShape shape = shapes.get(0);
IShapes collection for the current worksheet or chart sheet.The returned IBackgroundPictures object provides access to all IBackgroundPicture objects associated with the sheet.
IBackgroundPictures backgroundPictures = worksheet.getBackgroundPictures();
try (InputStream stream = createSampleImageStream()) {
IBackgroundPicture createdPicture = backgroundPictures.addPicture(stream, ImageType.PNG, 12, 18, 120, 80);
createdPicture.setName("Watermark");
}
int count = backgroundPictures.getCount();
IBackgroundPicture picture = backgroundPictures.get(0);
IBackgroundPicture namedPicture = backgroundPictures.get("Watermark");
Returns an ISort object that you can use to configure the sort range, sort fields, and sort orientation before calling ISort.apply().
worksheet.getRange("A1:A4").setValue(new Object[][] {{5}, {3}, {4}, {2}});
ISort sort = worksheet.getSort();
sort.setRange(worksheet.getRange("A1:A4"));
sort.getSortFields().add(new ValueSortField(worksheet.getRange("A1:A4")));
sort.apply();
Use this method to retrieve the color currently applied to the tab. To change the tab color, use setTabColor(Color).
worksheet.setTabColor(Color.GetBlue());
Color tabColor = worksheet.getTabColor();
worksheet.getRange("A1").setValue(tabColor.toString());
worksheet.setTabColor(Color.GetBlue());
value - The primary color of the worksheet tab.ITable objects in the worksheet.Use the returned ITables collection to create, access, and manage tables defined on the current worksheet. The collection can be empty if the worksheet does not contain any tables.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"Tea", 100},
{"Coffee", 200}
});
ITables tables = worksheet.getTables();
ITable salesTable = tables.add(worksheet.getRange("A1:B3"), true);
ITable firstTable = tables.get(0);
Workbook that contains this worksheet.Use this method to access workbook-level settings, collections, and operations from the current worksheet.
worksheet.getRange("A1").setValue("Name");
IWorkbook workbook = worksheet.getWorkbook();
workbook.getWorksheets().add();
Returns an IProtectionSettings object that provides access to the worksheet protection options. Changes to the returned settings take effect only when the worksheet is protected.
worksheet.setProtection(true);
IProtectionSettings protectionSettings = worksheet.getProtectionSettings();
protectionSettings.setAllowFiltering(true);
IProtectionSettings object that represents the protection options of the worksheet.This property indicates whether worksheet protection is enabled.
worksheet.setProtection(true);
boolean protection = worksheet.getProtection();
true if the worksheet is protected; otherwise, false.This property indicates whether worksheet protection is enabled.
worksheet.setProtection(true);
value - true if the worksheet is protected; otherwise, false.IRange object that represents all rows in the worksheet.You can use the returned range to access individual rows by index and perform row-level operations.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B1").setValue("Value");
IRange rows = worksheet.getRows();
IRange firstRow = rows.get(0);
IRange object that represents all rows in the worksheet.This method returns the row position specified by freezePanes(int,int). Returns 0 if the worksheet does not have frozen panes.
worksheet.freezePanes(2, 1);
int frozenRow = worksheet.getFreezeRow();
0 if the worksheet does not have frozen panes.This method returns the column position specified by freezePanes(int,int). Returns 0 if the worksheet does not have frozen panes.
worksheet.freezePanes(1, 2);
int frozenColumn = worksheet.getFreezeColumn();
0 if the worksheet does not have frozen panes.This property returns the color used to display the divider between frozen and unfrozen panes. If no frozen line color has been set, this method returns null.
worksheet.freezePanes(2, 1);
worksheet.setFrozenLineColor(Color.GetRed());
Color frozenLineColor = worksheet.getFrozenLineColor();
null if no frozen line color has been set.This method returns the trailing frozen row position specified by freezeTrailingPanes(int,int). Returns 0 if the worksheet does not have trailing frozen panes.
worksheet.freezeTrailingPanes(2, 1);
int trailingFrozenRow = worksheet.getFreezeTrailingRow();
0 if the worksheet does not have trailing frozen panes.This method returns the trailing frozen column position specified by freezeTrailingPanes(int,int). Returns 0 if the worksheet does not have trailing frozen panes.
worksheet.freezeTrailingPanes(1, 2);
int trailingFrozenColumn = worksheet.getFreezeTrailingColumn();
0 if the worksheet does not have trailing frozen panes.Use this method to set the color used to display the divider between frozen and unfrozen panes. Pass null to clear the frozen line color setting.
worksheet.freezePanes(2, 1);
worksheet.setFrozenLineColor(Color.GetRed());
value - The color of the frozen line, or null to clear the frozen line color setting.This method returns the row position specified by splitPanes(int,int). Returns 0 if the worksheet does not have split panes.
worksheet.splitPanes(2, 1);
int splitRow = worksheet.getSplitRow();
0 if the worksheet does not have split panes.This method returns the column position specified by splitPanes(int,int). Returns 0 if the worksheet does not have split panes.
worksheet.splitPanes(2, 3);
int splitColumn = worksheet.getSplitColumn();
0 if the worksheet does not have split panes.IPageSetup object for this worksheet.The returned object provides access to page setup settings such as print area, margins, orientation, scaling, and headers and footers.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
IPageSetup pageSetup = worksheet.getPageSetup();
pageSetup.setPrintArea("A1:B3");
IPageSetup object that contains the page setup settings for this worksheet.Use the returned IHPageBreaks collection to access existing horizontal page breaks or add new ones within the worksheet print area.
worksheet.getRange("A1").setValue("Name");
worksheet.getHPageBreaks().add(worksheet.getRange("A10"));
IHPageBreaks pageBreaks = worksheet.getHPageBreaks();
IHPageBreak pageBreak = pageBreaks.get(0);
Use the returned IVPageBreaks collection to add, access, and manage vertical page breaks on the worksheet.
worksheet.getRange("A1:F10").setValue("Data");
IVPageBreaks pageBreaks = worksheet.getVPageBreaks();
pageBreaks.add(worksheet.getRange("D1"));
IVPageBreak pageBreak = pageBreaks.get(0);
IRange location = pageBreak.getLocation();
Use activate() to make this worksheet the active sheet.
worksheet.setName("Data");
IWorksheet summarySheet = workbook.getWorksheets().add();
summarySheet.setName("Summary");
worksheet.select();
If replace is true, the current selection is replaced with this worksheet. If replace is false, this worksheet is added to the current selection.
workbook.getWorksheets().add();
IWorksheet sheet2 = workbook.getWorksheets().get(1);
worksheet.select(true);
sheet2.select(false);
replace - true to replace the current selection with this worksheet; false to extend the current selection to include this worksheet.This method is equivalent to clicking the worksheet tab in the workbook UI.
IWorksheet summarySheet = workbook.getWorksheets().add();
summarySheet.setName("Summary");
summarySheet.activate();
If this worksheet is the active worksheet, another worksheet may become active after the deletion.
IWorksheet summarySheet = workbook.getWorksheets().add();
summarySheet.setName("Summary");
worksheet.delete();
The formula is evaluated by using non-dynamic array semantics.
worksheet.getRange("A1").setValue(100);
worksheet.getRange("A2").setValue(200);
Object result = worksheet.evaluate("=SUM(A1:A2)");
Object nameResult = worksheet.evaluate("=ROW(A1)");
formula - A string containing an Excel formula, named range, or defined name to evaluate.IRange object when the formula result is a reference, such as "=A1".evaluate2(String) if the formula should be evaluated by using dynamic array semantics.The formula is evaluated by using dynamic array semantics.
worksheet.getRange("A1").setValue(1);
worksheet.getRange("A2").setValue(2);
worksheet.getRange("A3").setValue(2);
Object result = worksheet.evaluate2("=UNIQUE(A1:A3)");
formula - A string containing an Excel formula, named range, or defined name to evaluate.Object[][] for a dynamic array formula, or an IRange object when the formula returns a reference such as "=A1:A5".Use the resolver to supply values for custom names referenced by the formula. The calculation behavior is consistent with Excel 2019 and earlier versions.
class CustomFormulaResolver implements IFormulaResolver {
public Object evaluate(String text) {
return "TaxRate".equals(text) ? 0.08 : null;
}
public boolean isCustomName(String text) {
return "TaxRate".equals(text);
}
}
IFormulaResolver resolver = new CustomFormulaResolver();
Object result = worksheet.evaluate("=100*TaxRate", resolver);
formula - A string containing an Excel formula, named range, or defined name to evaluate. A leading = is allowed. Must not be null or empty.resolver - The custom resolver used to resolve names referenced by the formula. If null, the formula is evaluated without a custom resolver.IRange object when the formula result is a reference, such as "=A1".InvalidFormulaException - if formula is null, empty, or not a valid formula expression.If getAutoFilter() is in use on the worksheet, this method clears the applied filter criteria and changes the filter drop-down arrows to show All.
worksheet.getRange("A1:B4").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200},
{"C", 120}
});
worksheet.getRange("A1:B4").autoFilter(1, "<150");
worksheet.showAllData();
worksheet.getRange("B2").setValue("Used cell");
IRange usedRange = worksheet.getUsedRange();
worksheet.getRange("B2").setValue("Used cell");
IRange usedRange = worksheet.getUsedRange(EnumSet.of(UsedRangeType.Data));
type - The feature type.IRange object that represents the used range on the specified worksheet.Use this method to keep the rows above the specified row position and the columns to the left of the specified column position visible while scrolling the worksheet.
worksheet.getRange("A1:B4").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200},
{"C", 300}
});
worksheet.freezePanes(1, 1);
row - The frozen row position.column - The frozen column position.This method clears the pane freeze state that was applied by freezePanes(int,int).
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200}
});
worksheet.freezePanes(1, 1);
worksheet.unfreezePanes();
This method sets the number of trailing rows and trailing columns that remain visible when the worksheet is scrolled.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200}
});
worksheet.freezeTrailingPanes(1, 1);
row - The trailing frozen row position.column - The trailing frozen column position.This method clears the trailing frozen pane state that was applied by freezeTrailingPanes(int,int).
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"A", 100},
{"B", 200}
});
worksheet.freezeTrailingPanes(1, 1);
worksheet.unfreezeTrailingPanes();
Use this method to divide the worksheet view into multiple panes so that different areas of the worksheet can be viewed independently.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B1").setValue("Value");
worksheet.splitPanes(2, 2);
IPanes panes = worksheet.getPanes();
row - The row position where the worksheet is split.column - The column position where the worksheet is split.This method clears the current split pane layout and restores the worksheet to a single-pane view. The implementation forwards to splitPanes(int,int) with both arguments set to 0.
worksheet.splitPanes(2, 2);
worksheet.unsplitPanes();
IPanes panes = worksheet.getPanes();
Returns the IPanes collection for the current worksheet view. Use this method to access the IPane objects in the worksheet, such as after calling splitPanes(int,int).
worksheet.splitPanes(2, 2);
IPanes panes = worksheet.getPanes();
IPane pane = panes.get(0);
IPanes collection that contains the worksheet panes.Returns the IPane object that represents the pane currently active in the worksheet view. Use this method to access or modify the scroll position of the active pane after the worksheet has been split into multiple panes.
worksheet.splitPanes(2, 2);
IPane pane = worksheet.getActivePane();
pane.setScrollRow(3);
pane.setScrollColumn(2);
IPane object that represents the active pane of the worksheet.The file format is determined from the extension in fileName and the call is forwarded to save(String,SaveFileFormat) with the resolved format.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
worksheet.save("InvoiceSheet.xlsx");
fileName - The file name to save to. Must be a valid file path and include the target file name; null is not supported.IllegalArgumentException - if fileName is not a valid file path.Use this method to export a single worksheet when the target file path and file format are known explicitly.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
worksheet.save("InvoiceSheet.pdf", SaveFileFormat.Pdf);
fileName - The path and name of the file to create. Must be a valid file path; null is not supported.fileFormat - The file format to use when saving the worksheet.Use this method to export a single worksheet to a stream when the output format is known explicitly.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
worksheet.save(stream, SaveFileFormat.Pdf);
fileStream - The output stream to receive the saved worksheet. Must not be null.fileFormat - The format used to save the worksheet to the stream.The save behavior depends on the concrete SaveOptionsBase instance that is provided. This overload writes the worksheet to the file path specified by fileName.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Score"},
{"Alice", 100}
});
SaveOptionsBase options = new PdfSaveOptions();
worksheet.save("report.pdf", options);
fileName - The path and name of the file to create. Must be a valid file path and must not be null.options - The save options that control how the worksheet is written. This value must not be null.IllegalArgumentException - if fileName is invalid, or if saving the worksheet fails.UnsupportedOperationException - if the specified save options use an unsupported file format.The output format and save behavior are determined by the concrete SaveOptionsBase instance that is provided.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Score"},
{"Alice", 100}
});
SaveOptionsBase options = new PdfSaveOptions();
java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
worksheet.save(stream, options);
fileStream - The output stream that receives the saved worksheet. This value must not be null.options - The save options that control how the worksheet is written to the stream. This value must not be null.UnsupportedOperationException - if the specified save options use a file format that is not supported by worksheet stream saving.IllegalArgumentException - if the specified save options use an invalid or unsupported file format.When this property is true, existing page break positions remain fixed during row or column insertion and deletion operations.
worksheet.getRange("A1:T32").setValue(1);
IHPageBreak pageBreak = worksheet.getHPageBreaks().add(worksheet.getRows().get(7));
worksheet.setFixedPageBreaks(true);
boolean fixedPageBreaks = worksheet.getFixedPageBreaks();
worksheet.getRows().get(6).insert();
IRange location = pageBreak.getLocation();
true if the horizontal and vertical page breaks are fixed when rows or columns are inserted or deleted; otherwise, false.When this property is true, existing page break positions remain fixed during row or column insertion and deletion operations.
worksheet.getRange("A1:T32").setValue(1);
IHPageBreak pageBreak = worksheet.getHPageBreaks().add(worksheet.getRows().get(7));
worksheet.setFixedPageBreaks(true);
worksheet.getRows().get(6).insert();
IRange location = pageBreak.getLocation();
value - true if the horizontal and vertical page breaks are fixed when rows or columns are inserted or deleted; otherwise, false.Use this method to determine whether the current sheet is a regular worksheet or another supported sheet type, such as a chart sheet.
IWorksheet chartSheet = workbook.getWorksheets().add(SheetType.Chart);
SheetType type = chartSheet.getType();
Use this method to retrieve application-defined metadata stored with the worksheet. To assign a tag, use setTag(Object).
worksheet.setTag("Quarterly summary");
Object tag = worksheet.getTag();
String text = (String) tag;
null if no tag has been assigned.
worksheet.setTag("Quarterly summary");
tag - The custom tag stored on the worksheet. Sets null if no tag has been assigned.Use this method to retrieve the BaseCellType applied at the worksheet level. The returned cell type affects cells that inherit the worksheet's default cell type setting.
worksheet.setCellType(new ButtonCellType());
BaseCellType cellType = worksheet.getCellType();
null if no cell type is set for the worksheet.The specified BaseCellType is used as the default cell type for cells that inherit the worksheet's cell type setting. Use null to clear the worksheet-level cell type.
ButtonCellType cellType = new ButtonCellType();
cellType.setText("Details");
worksheet.getRange("A1").setValue("Details");
worksheet.setCellType(cellType);
cellType - The cell type to apply to the worksheet. Use null to remove the worksheet-level cell type.This method returns the object previously assigned through setDataSource(Object).
JsonDataSource dataSource = new JsonDataSource("[{\"name\":\"Jack\",\"age\":12},{\"name\":\"Alice\",\"age\":25}]");
worksheet.setAutoGenerateColumns(true);
worksheet.setDataSource(dataSource);
Object source = worksheet.getDataSource();
Object firstName = worksheet.getRange("A1").getValue();
null if no data source has been set.
JsonDataSource dataSource = new JsonDataSource("[{\"name\":\"Jack\",\"age\":12},{\"name\":\"Alice\",\"age\":25}]");
worksheet.setAutoGenerateColumns(true);
worksheet.setDataSource(dataSource);
Object firstName = worksheet.getRange("A1").getValue();
value - The data source object for the current worksheet, or null if no data source has been set.When this property is true, columns can be created automatically during data binding. Use setAutoGenerateColumns(boolean) to change this setting before assigning or refreshing bound data.
JsonDataSource dataSource = new JsonDataSource("[{\"name\":\"Jack\",\"age\":12},{\"name\":\"Alice\",\"age\":25}]");
worksheet.setAutoGenerateColumns(true);
worksheet.setDataSource(dataSource);
boolean autoGenerateColumns = worksheet.getAutoGenerateColumns();
int columnCount = worksheet.getColumnCount();
Object firstName = worksheet.getRange("A1").getValue();
Object secondAge = worksheet.getRange("B2").getValue();
true if columns are generated automatically during data binding; otherwise, false.
JsonDataSource dataSource = new JsonDataSource("[{\"name\":\"Jack\",\"age\":12},{\"name\":\"Alice\",\"age\":25}]");
worksheet.setAutoGenerateColumns(true);
worksheet.setDataSource(dataSource);
int columnCount = worksheet.getColumnCount();
Object firstName = worksheet.getRange("A1").getValue();
Object secondAge = worksheet.getRange("B2").getValue();
value - true if columns are generated automatically during data binding; otherwise, false.The outline column displays hierarchical row data in a tree view. Use the returned IOutlineColumn object to configure the column index and display options for the row hierarchy.
worksheet.getRange("A1:A3").setValue(new Object[][] {{"Name"}, {"Node 1"}, {"Node 1.1"}});
worksheet.getRange("A2").setIndentLevel(1);
IOutlineColumn outlineColumn = worksheet.getOutlineColumn();
outlineColumn.setColumnIndex(0);
IOutlineColumn object for the current worksheet.IScenarios object that represents the collection of What-If analysis scenarios in the worksheet.Use the returned collection to add, retrieve, and iterate worksheet scenarios.
worksheet.getRange("C4").setValue(0.8);
IScenarios scenarios = worksheet.getScenarios();
scenarios.add("80% highest", worksheet.getRange("C4"));
IScenario scenario = scenarios.get("80% highest");
IScenarios object for the worksheet's scenarios.IAutoMergeRangeInfo objects that represent all auto merge range information in the current worksheet.Each item describes an auto-merge range that was added by autoMerge(IRange), autoMerge(IRange,AutoMergeDirection), autoMerge(IRange,AutoMergeDirection,AutoMergeMode), or autoMerge(IRange,AutoMergeDirection,AutoMergeMode,AutoMergeSelectionMode).
IRange range = worksheet.getRange("A1:A4");
range.setValue(new Object[][] {
{"North"},
{"North"},
{"South"},
{"South"}
});
worksheet.autoMerge(range, AutoMergeDirection.Column, AutoMergeMode.Free);
List<IAutoMergeRangeInfo> autoMergeInfos = worksheet.getAutoMergeRangesInfo();
IAutoMergeRangeInfo objects for the current worksheet. Returns an empty list if no auto merge range information exists.The returned worksheet represents the newly created copy.
worksheet.setName("Template");
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
IWorksheet copiedSheet = worksheet.copy();
copiedSheet.setName("Template Copy");
The copied sheet is appended to the destination workbook and returned as a new worksheet instance. If workbook is null, the sheet is copied to the end of the current workbook.
worksheet.setName("Report");
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
IWorkbook targetWorkbook = new Workbook();
IWorksheet copiedSheet = worksheet.copy(targetWorkbook);
copiedSheet.setName("Report Copy");
workbook - The workbook to which the sheet will be copied, or null to copy the sheet to the end of the current workbook.The copied sheet is inserted immediately before targetSheet. The target sheet can belong to the current workbook or another workbook.
worksheet.setName("Data");
worksheet.getRange("A1").setValue("Name");
IWorksheet summarySheet = workbook.getWorksheets().add();
summarySheet.setName("Summary");
IWorksheet copiedSheet = worksheet.copyBefore(summarySheet);
copiedSheet.setName("Data Copy");
targetSheet - The sheet before which the copied sheet will be placed. It can be a sheet in the same workbook or another workbook.The copied sheet is inserted immediately after targetSheet. The target sheet can belong to the current workbook or another workbook.
worksheet.setName("Data");
worksheet.getRange("A1").setValue("Name");
IWorksheet summarySheet = workbook.getWorksheets().add();
summarySheet.setName("Summary");
IWorksheet copiedSheet = worksheet.copyAfter(summarySheet);
copiedSheet.setName("Data Copy");
targetSheet - The sheet after which the copied sheet will be placed. It can be a sheet in the same workbook or another workbook.
worksheet.setName("Summary");
workbook.getWorksheets().add().setName("Details");
IWorksheet movedSheet = worksheet.move();
If workbook is null or is the current workbook, the sheet is moved to the end of the current workbook.
worksheet.setName("Summary");
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
workbook.getWorksheets().add().setName("Overview");
IWorkbook targetWorkbook = new Workbook();
IWorksheet movedSheet = worksheet.move(targetWorkbook);
workbook - The workbook to which the sheet will be moved, or null to move the sheet to the end of the current workbook.The target sheet can belong to the same workbook or a different workbook.
worksheet.setName("Data");
IWorksheet summarySheet = workbook.getWorksheets().add();
summarySheet.setName("Summary");
IWorksheet movedSheet = summarySheet.moveBefore(worksheet);
targetSheet - The sheet before which the moved sheet will be placed. It can be the sheet of the same or another workbook.The target sheet can belong to the same workbook or another workbook.
worksheet.setName("Summary");
IWorksheet detailsSheet = workbook.getWorksheets().add();
detailsSheet.setName("Details");
IWorksheet movedSheet = worksheet.moveAfter(detailsSheet);
targetSheet - The sheet after which the moved sheet will be placed. It can be the sheet of the same or another workbook.The generated JSON represents the current worksheet content and can be used with fromJson(String) to load worksheet data.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = worksheet.toJson();
Serializes the current worksheet to JSON and applies the specified SerializationOptions during serialization. If serializationOptions is null, the worksheet is serialized with internally created default options.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
SerializationOptions options = new SerializationOptions();
options.setIgnoreStyle(true);
String json = worksheet.toJson(options);
serializationOptions - The SerializationOptions object to apply during serialization; may be null.Writes the worksheet content to the specified output stream in JSON format.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
ByteArrayOutputStream stream = new ByteArrayOutputStream();
worksheet.toJson(stream);
stream - The output stream that receives the worksheet JSON content. Must not be null.Writes the worksheet content as JSON to the specified output stream and applies the specified SerializationOptions during serialization.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
SerializationOptions options = new SerializationOptions();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
worksheet.toJson(stream, options);
stream - The output stream that receives the generated JSON content.serializationOptions - The SerializationOptions object to apply during serialization.Use this method to load worksheet content from JSON data.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = worksheet.toJson();
worksheet.fromJson(json);
json - The input JSON string that represents the worksheet.Use DeserializationOptions to control how the JSON data is loaded, such as whether formulas or styles are ignored and whether recalculation is prevented after loading.
worksheet.getRange("A1").setValue("Sample");
String json = worksheet.toJson();
DeserializationOptions options = new DeserializationOptions();
worksheet.fromJson(json, options);
json - The input JSON string that describes the worksheet content.deserializationOptions - The DeserializationOptions object that controls how the JSON is loaded.
try (InputStream stream = new FileInputStream("workbook.json")) {
worksheet.fromJson(stream);
}
stream - The input JSON stream that describes the worksheet content.
DeserializationOptions options = new DeserializationOptions();
options.setIgnoreStyle(true);
try (InputStream stream = new FileInputStream("workbook.json")) {
worksheet.fromJson(stream, options);
}
stream - The input JSON stream that describes the worksheet content.deserializationOptions - The DeserializationOptions object that controls how the JSON is loaded.
IRange range = worksheet.getRange("A1:A4");
range.setValue(new Object[][] {
{"North"},
{"North"},
{"South"},
{"South"}
});
worksheet.autoMerge(range);
range - The range to apply auto merge to. null is not supported.AutoMergeMode.Free. The auto merge selection mode is AutoMergeSelectionMode.Source. This method adds auto-merge information to the specified range so that adjacent cells with the same value can be merged automatically. If direction is AutoMergeDirection.None, the existing auto merge for the range is canceled.
IRange range = worksheet.getRange("A1:A4");
range.setValue(new Object[][] {
{"Fruit"}, {"Fruit"}, {"Vegetable"}, {"Vegetable"}
});
worksheet.autoMerge(range, AutoMergeDirection.Column);
range - The range to which auto-merge information is applied.direction - The direction used to evaluate and apply auto merge. Use AutoMergeDirection.None to cancel auto merge for the range.AutoMergeSelectionMode.Source. This method adds auto-merge information to the specified range so that neighboring cells with the same value can be merged automatically. The auto-merge operation takes effect when the worksheet is exported with auto-merged cells included. If direction is AutoMergeDirection.None, the auto merge for the range is canceled.
IRange range = worksheet.getRange("A1:B4");
range.setValue(new Object[][] {
{"Fruit", "Fruit"},
{"Apple", "Apple"},
{"Pear", "Pear"},
{"Pear", "Pear"}
});
worksheet.autoMerge(range, AutoMergeDirection.Column, AutoMergeMode.Restricted);
range - The range to which auto-merge information is applied.direction - The auto merge direction. Use AutoMergeDirection.None to cancel auto merge for the range.mode - The auto merge mode that determines how neighboring cells with identical values are merged.Auto merge combines neighboring cells that have the same value within the specified range. If AutoMergeDirection.None is specified, the existing auto merge setting for the range is canceled.
IRange range = worksheet.getRange("A1:B4");
range.setValue(new Object[][] {
{"Name", "Type"},
{"Apple", "Fruit"},
{"Apple", "Fruit"},
{"Pear", "Fruit"}
});
worksheet.autoMerge(range, AutoMergeDirection.Column, AutoMergeMode.Restricted, AutoMergeSelectionMode.Merged);
range - The range to which auto merge is applied.direction - The direction used to evaluate and apply auto merge. Specify AutoMergeDirection.None to cancel auto merge for the range.mode - The mode that determines how neighboring cells with the same value are merged.selectionMode - The selection mode to use for cells in the auto-merged range.Use this method to export the current worksheet as an image.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
worksheet.toImage("worksheet.png");
imageFile - The path and file name of the output image file.Use this method to render the current worksheet as an image and write the generated image data to imageFile. The output image format is determined by the file extension in imageFile.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
ImageSaveOptions options = new ImageSaveOptions();
options.setShowGridlines(true);
worksheet.toImage("worksheet.png", options);
imageFile - The path and file name of the output image file.options - The options that control how the worksheet is exported to the image; may be null.IllegalArgumentException - if an error occurs while writing the image file.Use this method to render the current worksheet as an image in the format specified by imageType and write the generated image data to stream.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
worksheet.toImage(stream, ImageType.PNG);
stream - The output stream that receives the generated image data.imageType - The type of image to create.Use this method to export the current worksheet as an image and write the generated data to an OutputStream.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
ImageSaveOptions options = new ImageSaveOptions();
worksheet.toImage(stream, ImageType.PNG, options);
stream - The output stream that receives the generated image data.imageType - The type of image to create.options - The options that control image output; can be null.IllegalArgumentException - if imageType is unsupported.The worksheet is protected without a password.
worksheet.getRange("A1").setValue("Name");
worksheet.protect();
If password is not null or empty, the worksheet is protected with that password. Otherwise, the worksheet is protected without a password.
worksheet.getRange("A1").setValue("Name");
// Protect the worksheet with a password retrieved from a secure source
String password = getPasswordFromSecureSource();
worksheet.protect(password);
password - The password used to protect the worksheet. Specify null or an empty string to protect the worksheet without a password.
worksheet.getRange("A1").setValue("Name");
worksheet.protect();
worksheet.unprotect();
// Protect the worksheet with a password retrieved from a secure source
String password = getPasswordFromSecureSource();
worksheet.protect(password);
worksheet.unprotect(password);
password - The password used to remove worksheet protection. Specify the same password that was used to protect the worksheet.IllegalArgumentException - if the worksheet is password-protected and the specified password is null, empty, or incorrect.