[]
WorkbookThis interface defines the workbook-level API for working with spreadsheets, including managing worksheets, accessing the active sheet, configuring workbook settings, handling workbook events, and performing operations such as calculation, opening, and saving.
The Workbook class is the known public implementation of this interface.
IWorkbook workbook = new Workbook();
workbook.getBuiltInDocumentProperties().setTitle("Quarterly Sales");
workbook.getOptions().getFormulas().setEnableIterativeCalculation(true);
workbook.getActiveSheet().getRange("A1").setValue("Revenue");
IWorksheet worksheet = workbook.getWorksheets().get(0);
voidaddDataSource(String name,
Object dataSource) voidclone()voidvoidconvertBarcodeToPicture(ImageType imageType) voiddirty()fromJson(InputStream stream) fromJson(InputStream stream,
DeserializationOptions deserializationOptions) fromJson(String json,
DeserializationOptions deserializationOptions) voidfromSjsJson(InputStream stream) voidfromSjsJson(InputStream stream,
SjsOpenOptions openOptions) voidfromSjsJson(String json) voidfromSjsJson(String json,
SjsOpenOptions openOptions) SjsOpenOptions.generateReport(IWorksheet... worksheets) booleanbooleanbooleanbooleanbooleangetName()getNames()getPath()IPivotCaches collection that contains all IPivotTable caches in the workbook.booleanbooleanbooleanbooleanISlicerCaches collection associated with the workbook.ITableStyleCollection for the current workbook.getTheme()IWorksheets collection that represents all worksheets in the workbook.booleanisEncryptedFile(InputStream fileStream) booleanisEncryptedFile(String fileName) voidopen(InputStream fileStream) voidopen(InputStream fileStream,
OpenFileFormat fileFormat) voidopen(InputStream fileStream,
OpenOptionsBase options) voidopen(InputStream fileStream,
String password) open(InputStream,OpenOptionsBase) instead.voidopen(String fileName,
DeserializationOptions deserializationOptions) voidopen(String fileName,
OpenFileFormat fileFormat) voidopen(String fileName,
OpenOptionsBase options) voidopen(String,OpenOptionsBase) instead.voidvoidprocessTemplate(CancellationToken cancellationToken) voidprotect()voidprotect(boolean structure) voidprotect(boolean structure,
boolean windows) voidvoidvoidvoidsave(OutputStream outputStream) voidsave(OutputStream fileStream,
SaveFileFormat fileFormat) voidsave(OutputStream fileStream,
SaveOptionsBase options) voidsave(OutputStream outputStream,
String password) save(OutputStream,SaveOptionsBase) instead.voidvoidsave(String fileName,
SaveFileFormat fileFormat) voidsave(String fileName,
SaveOptionsBase options) voidvoidsetAllowDynamicArray(boolean value) IRange.setFormula2(String) to set dynamic array formulas.voidvoidsetAutoParse(boolean value) voidsetAutoRoundValue(boolean value) voidsetCulture(Locale value) voidsetDefaultTableStyle(String value) voidsetDeferUpdateDirtyState(boolean value) voidsetEnableCalculation(boolean value) voidsetGraphicsInfo(IGraphicsInfo value) voidvoidvoidsetReferenceStyle(ReferenceStyle value) voidsetResetAdjacentRangeBorder(boolean value) voidsetShowPivotTableFieldList(boolean value) voidtoJson()toJson(SerializationOptions serializationOptions) voidtoJson(OutputStream stream) voidtoJson(OutputStream stream,
SerializationOptions serializationOptions) toSjsJson(SjsSaveOptions options) voidtoSjsJson(OutputStream stream) voidtoSjsJson(OutputStream stream,
SjsSaveOptions options) voidvoidvoidupdateExcelLink(String name) voidupdateExcelLink(String name,
IWorkbook sourceWorkbook) voidvoid
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final boolean[] afterSaveHandled = {false};
Event<EventHandler<EventArgs>> afterSaveEvent = workbook.getAfterSaveEvent();
afterSaveEvent.addListener(new EventHandler<EventArgs>() {
public void invoke(Object sender, EventArgs e) {
afterSaveHandled[0] = outputStream.size() > 0;
}
});
workbook.getActiveSheet().getRange("A1").setValue("Ready");
workbook.save(outputStream);
boolean saved = afterSaveHandled[0];
Event that occurs after the workbook is saved.
final boolean[] beforeSaveHandled = {false};
Event<EventHandler<EventArgs>> beforeSaveEvent = workbook.getBeforeSaveEvent();
beforeSaveEvent.addListener(new EventHandler<EventArgs>() {
public void invoke(Object sender, EventArgs e) {
beforeSaveHandled[0] = "Ready".equals(workbook.getActiveSheet().getRange("A1").getValue());
}
});
workbook.getActiveSheet().getRange("A1").setValue("Ready");
workbook.save(new ByteArrayOutputStream());
boolean saving = beforeSaveHandled[0];
Event that occurs before the workbook is saved.
final IWorksheet[] sheetFromEvent = {null};
Event<EventHandler<SheetEventArgs>> newSheetEvent = workbook.getNewSheetEvent();
newSheetEvent.addListener(new EventHandler<SheetEventArgs>() {
public void invoke(Object sender, SheetEventArgs e) {
sheetFromEvent[0] = e.getSheet();
}
});
workbook.getWorksheets().add();
IWorksheet newSheet = sheetFromEvent[0];
Event that occurs when a new sheet is created in the workbook.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.getActiveSheet().getRange("A1").setValue("Opened");
workbook.save(outputStream);
IWorkbook openedWorkbook = new Workbook();
final boolean[] openedHandled = {false};
Event<EventHandler<EventArgs>> openedEvent = openedWorkbook.getOpenedEvent();
openedEvent.addListener(new EventHandler<EventArgs>() {
public void invoke(Object sender, EventArgs e) {
openedHandled[0] = true;
}
});
openedWorkbook.open(new ByteArrayInputStream(outputStream.toByteArray()));
boolean opened = openedHandled[0];
Event that occurs when the workbook is opened.
IWorksheet detailSheet = workbook.getWorksheets().add();
final IWorksheet[] sheetFromEvent = {null};
Event<EventHandler<SheetEventArgs>> sheetActivateEvent = workbook.getSheetActivateEvent();
sheetActivateEvent.addListener(new EventHandler<SheetEventArgs>() {
public void invoke(Object sender, SheetEventArgs e) {
sheetFromEvent[0] = e.getSheet();
}
});
detailSheet.activate();
IWorksheet activeSheet = sheetFromEvent[0];
Event that occurs when a sheet is activated.
IWorksheet sheetToDelete = workbook.getWorksheets().add();
final IWorksheet[] sheetFromEvent = {null};
Event<EventHandler<SheetEventArgs>> sheetBeforeDeleteEvent = workbook.getSheetBeforeDeleteEvent();
sheetBeforeDeleteEvent.addListener(new EventHandler<SheetEventArgs>() {
public void invoke(Object sender, SheetEventArgs e) {
sheetFromEvent[0] = e.getSheet();
}
});
sheetToDelete.delete();
IWorksheet deletedSheet = sheetFromEvent[0];
Event that occurs before a sheet is deleted.
final IRange[] rangeFromEvent = {null};
Event<EventHandler<RangeEventArgs>> sheetChangeEvent = workbook.getSheetChangeEvent();
sheetChangeEvent.addListener(new EventHandler<RangeEventArgs>() {
public void invoke(Object sender, RangeEventArgs e) {
rangeFromEvent[0] = e.getRange();
}
});
workbook.getActiveSheet().getRange("A1").setValue("Updated");
IRange changedRange = rangeFromEvent[0];
Event that occurs when something changes in the cells of a sheet.
IWorksheet summarySheet = workbook.getWorksheets().add();
final IWorksheet[] sheetFromEvent = {null};
Event<EventHandler<SheetEventArgs>> sheetDeactivateEvent = workbook.getSheetDeactivateEvent();
sheetDeactivateEvent.addListener(new EventHandler<SheetEventArgs>() {
public void invoke(Object sender, SheetEventArgs e) {
sheetFromEvent[0] = e.getSheet();
}
});
summarySheet.activate();
IWorksheet deactivatedSheet = sheetFromEvent[0];
Event that occurs when a sheet is deactivated.
final IRange[] rangeFromEvent = {null};
Event<EventHandler<RangeEventArgs>> sheetSelectionChangeEvent = workbook.getSheetSelectionChange();
sheetSelectionChangeEvent.addListener(new EventHandler<RangeEventArgs>() {
public void invoke(Object sender, RangeEventArgs e) {
rangeFromEvent[0] = e.getRange();
}
});
workbook.getActiveSheet().getRange("B2").select();
IRange selectedRange = rangeFromEvent[0];
Event that occurs when the selection changes on a sheet.IRange.setFormula2(String) to set a dynamic array formula.IRange.setFormula(String). This method is obsolete. Dynamic array formulas should be defined by using IRange.setFormula2(String) instead. This property is retained for compatibility with earlier versions that enabled dynamic array behavior together with IRange.setFormula(String).
true if dynamic array formulas are allowed for compatibility with IRange.setFormula(String); otherwise, false.IRange.setFormula2(String) to set dynamic array formulas.This method is deprecated. Use IRange.setFormula2(String) to assign dynamic array formulas directly instead of relying on this workbook-level setting.
value - true to allow dynamic array formulas in the workbook; otherwise, false.When a cell value changes, dirty-state propagation normally runs immediately along the formula dependency chain. In scenarios with complex dependencies and frequent bulk value updates, this repeated propagation can introduce additional performance overhead.
When this property is true, value changes are queued and the dirty states of dependent formulas are not updated immediately. When this property is set back to false, the workbook processes the queued changes and updates the affected dirty states in a batch. Therefore, true and false must be used in pairs: each time this property is set to true, it must be set back to false after bulk updates are complete. Otherwise, objects that rely on cached or delayed refresh results, such as charts, might still return stale values before the queued changes are processed.
This property is intended for bulk cell value updates and can improve performance by reducing repeated dependency analysis and dirty-state propagation. It is not recommended when getValue and setValue operations are interleaved.
worksheet.getRange("B1").setFormula("=SUM(A:A)");
workbook.setDeferUpdateDirtyState(true);
boolean deferred;
try {
deferred = workbook.getDeferUpdateDirtyState();
for (int i = 0; i < 1000; i++) {
worksheet.getRange(i, 0).setValue(i);
}
} finally {
workbook.setDeferUpdateDirtyState(false);
}
Object value = worksheet.getRange("B1").getValue();
true if updates to the dirty states of dependent formulas affected by cell value changes are deferred; otherwise, false.When a cell value changes, dirty-state propagation normally runs immediately along the formula dependency chain. In scenarios with complex dependencies and frequent bulk value updates, this repeated propagation can introduce additional performance overhead.
When this property is true, value changes are queued and the dirty states of dependent formulas are not updated immediately. When this property is set back to false, the workbook processes the queued changes and updates the affected dirty states in a batch. Therefore, true and false must be used in pairs: each time this property is set to true, it must be set back to false after bulk updates are complete. Otherwise, objects that rely on cached or delayed refresh results, such as charts, might still return stale values before the queued changes are processed.
This property is intended for bulk cell value updates and can improve performance by reducing repeated dependency analysis and dirty-state propagation. It is not recommended when getValue and setValue operations are interleaved.
worksheet.getRange("B1").setFormula("=SUM(A:A)");
workbook.setDeferUpdateDirtyState(true);
try {
for (int i = 0; i < 1000; i++) {
worksheet.getRange(i, 0).setValue(i);
}
} finally {
workbook.setDeferUpdateDirtyState(false);
}
Object value = worksheet.getRange("B1").getValue();
value - true if updates to the dirty states of dependent formulas affected by cell value changes are deferred; otherwise, false.This method returns the workbook name without the file path. To get the workbook name together with its path, use getFullName().
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir")).toString();
workbook.setPath(filePath);
workbook.setName("QuarterlyReport.xlsx");
String name = workbook.getName();
This method sets the workbook name without the file path. To get the workbook name together with its path, use getFullName().
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir")).toString();
workbook.setPath(filePath);
workbook.setName("QuarterlyReport.xlsx");
name - The name of the workbook.This method returns the full workbook name composed from the workbook name and path information associated with this workbook.
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir")).toString();
workbook.setPath(filePath);
workbook.setName("QuarterlyReport.xlsx");
String fullName = workbook.getFullName();
Use this method to retrieve the path information associated with the current workbook. To get the workbook name together with its path, use getFullName().
String directoryPath = java.nio.file.Paths.get(System.getProperty("user.dir"), "Documents").toString();
workbook.setPath(directoryPath);
workbook.setName("Report.xlsx");
String path = workbook.getPath();
String fullName = workbook.getFullName();
Use this method to set the path information associated with the current workbook. To set the workbook file name, use setName(String). To get the workbook name together with its path, use getFullName().
String directoryPath = java.nio.file.Paths.get(System.getProperty("user.dir"), "Documents").toString();
workbook.setPath(directoryPath);
workbook.setName("Report.xlsx");
String fullName = workbook.getFullName();
path - The path of the workbook file represented by this workbook object.The returned IWorksheets object represents all worksheets that are currently selected.
IWorksheet sheet2 = workbook.getWorksheets().add();
workbook.getWorksheets().get(new String[] {worksheet.getName(), sheet2.getName()}).select();
IWorksheets selectedSheets = workbook.getSelectedSheets();
IWorksheets collection that represents all selected worksheets in the workbook.Returns the IExcelOptions object that contains settings used to control workbook behavior, such as formula-related options and data-related options.
IExcelOptions options = workbook.getOptions();
workbook.getActiveSheet().getRange("A1").setFormula("SUM(1, 2)");
options.getFormulas().setCalculationMode(CalculationMode.Manual);
workbook.save("path/to/manual-mode.xlsx");
IExcelOptions object that contains workbook option settings.The default value is true.
worksheet.getRange("D2:D3").getBorders().get(BordersIndex.EdgeLeft).setLineStyle(BorderLineStyle.Thick);
workbook.setResetAdjacentRangeBorder(true);
boolean resetAdjacentBorder = workbook.getResetAdjacentRangeBorder();
worksheet.getRange("B2:C3").getBorders().get(BordersIndex.EdgeRight).setLineStyle(BorderLineStyle.Thin);
BorderLineStyle adjacentLeftBorder = worksheet.getRange("D2:D3").getBorders().get(BordersIndex.EdgeLeft).getLineStyle();
true if borders of adjacent ranges are reset when setting a border for a range; otherwise, false.The default value is true.
worksheet.getRange("D2:D3").getBorders().get(BordersIndex.EdgeLeft).setLineStyle(BorderLineStyle.Thick);
workbook.setResetAdjacentRangeBorder(true);
worksheet.getRange("B2:C3").getBorders().get(BordersIndex.EdgeRight).setLineStyle(BorderLineStyle.Thin);
BorderLineStyle adjacentLeftBorder = worksheet.getRange("D2:D3").getBorders().get(BordersIndex.EdgeLeft).getLineStyle();
value - true if borders of adjacent ranges are reset when setting a border for a range; otherwise, false.When this property is true, string values assigned with IRange.setValue(Object) may be interpreted as numbers, date/time values, boolean values, error values, or empty cell values instead of being kept as plain text.
workbook.setAutoParse(true);
worksheet.getRange("A1").setValue("123");
Object value = worksheet.getRange("A1").getValue();
boolean autoParse = workbook.getAutoParse();
true if string values are automatically parsed when assigned to a range; otherwise, false.When this property is true, string values assigned with IRange.setValue(Object) may be interpreted as numbers, date/time values, boolean values, error values, or empty cell values instead of being kept as plain text.
workbook.setAutoParse(true);
worksheet.getRange("A1").setValue("123");
Object value = worksheet.getRange("A1").getValue();
value - true if string values are automatically parsed when assigned to a range; otherwise, false.Use this property to determine whether the workbook applies automatic rounding when reading numeric cell values.
worksheet.getRange("A1").setValue(1.2345678901234567d);
workbook.setAutoRoundValue(true);
boolean autoRoundValue = workbook.getAutoRoundValue();
Object value = worksheet.getRange("A1").getValue();
true if numeric values are rounded to 15 significant digits when retrieved; otherwise, false.Use this property to set whether the workbook applies automatic rounding when reading numeric cell values.
worksheet.getRange("A1").setValue(1.2345678901234567d);
workbook.setAutoRoundValue(true);
Object value = worksheet.getRange("A1").getValue();
value - true if numeric values are rounded to 15 significant digits when retrieved; otherwise, false.Use the returned IWorkbookView object to configure workbook-level display options such as workbook tabs, scroll bars, and tab ratio.
IWorkbookView bookView = workbook.getBookView();
bookView.setDisplayWorkbookTabs(true);
bookView.setDisplayVerticalScrollBar(false);
IWorkbookView object that represents the view settings of this workbook.When the workbook structure is protected, the order of worksheets cannot be changed until the protection is removed by using unprotect().
worksheet.getRange("A1").setValue("Quarterly Report");
workbook.protect(true);
boolean protectStructure = workbook.getProtectStructure();
true if the order of the sheets in the workbook is protected; otherwise, false.This property reflects the workbook window protection state set by protect(boolean,boolean). When workbook windows are protected, the window layout cannot be modified until the protection is removed.
worksheet.getRange("A1").setValue("Quarterly Report");
workbook.protect(true, true);
boolean protectWindows = workbook.getProtectWindows();
true if the workbook windows are protected; otherwise, false.The returned ISignatureSet provides access to the signatures in the document, including signature lines and non-visible signatures.
workbook.getSignatures().addSignatureLine(worksheet, 100.0, 50.0);
ISignatureSet signatures = workbook.getSignatures();
ISignature signature = signatures.get(0);
The returned IBuiltInDocumentPropertyCollection provides access to built-in metadata such as author, title, subject, company, and other standard document properties.
workbook.getBuiltInDocumentProperties().setAuthor("Author");
workbook.getBuiltInDocumentProperties().setCompany("Example");
IBuiltInDocumentPropertyCollection properties = workbook.getBuiltInDocumentProperties();
Use the returned ICustomDocumentPropertyCollection to add, remove, and retrieve workbook metadata defined by the application, such as string, numeric, Boolean, date, or linked-content properties.
worksheet.getRange("A1").setValue("Quarterly Report");
workbook.getNames().add("ReportTitle", "=Sheet1!$A$1");
ICustomDocumentPropertyCollection properties = workbook.getCustomDocumentProperties();
properties.add("Department", "Finance");
properties.addLinkToContent("TitleProperty", "ReportTitle");
Use the returned ICustomXmlPartCollection to add, retrieve, enumerate, or remove workbook-level Custom XML parts. Custom XML parts are stored in the OpenXML package as raw XML payloads and are preserved when saving to OpenXML workbook formats such as XLSX and XLSM.
This API stores and returns the XML bytes only. It does not validate the XML against a schema.
Workbook workbook = new Workbook();
ICustomXmlPart customXmlPart = workbook.getCustomXmlParts().add();
customXmlPart.setData("<payload><customer id=\"42\"/></payload>"
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String customXmlPartId = customXmlPart.getId();
workbook.save("customXmlWorkbook.xlsm");
Workbook uploadedWorkbook = new Workbook();
uploadedWorkbook.open("customXmlWorkbook.xlsm");
ICustomXmlPart uploadedPart = uploadedWorkbook.getCustomXmlParts().get(customXmlPartId);
byte[] uploadedXmlData = uploadedPart.getData();
The returned ICustomViews collection contains the custom views stored in the workbook. Each custom view is represented by an ICustomView object and stores the view state of all worksheets in the current workbook.
worksheet.getRange("A1").setValue("Name");
ICustomViews customViews = workbook.getCustomViews();
customViews.add("Normal", true, true);
ICustomView customView = workbook.getCustomViews().get("Normal");
customView.show();
ICustomViews collection that contains the workbook's custom views.The returned WriteProtection object provides access to settings that control write protection behavior when the workbook is opened in an Excel application, such as recommending read-only mode and setting a password required for modification.
WriteProtection protection = workbook.getWriteProtection();
protection.setWriteReservedBy("User");
protection.setReadOnlyRecommended(true);
String password = getPasswordFromSecureSource();
protection.setWritePassword(password);
boolean writeReserved = protection.getWriteReserved();
boolean passwordMatches = protection.validatePassword(password);
WriteProtection object for the workbook.When this property is false, formulas in the current workbook are no longer recalculated. If formula results are retrieved while calculation is disabled, the last calculated results from before calculation was disabled are returned.
This property is intended for large batch updates of values or formulas when updated calculation results are not needed until the batch is complete. Set this property to false before the batch to improve performance, and set it back to true when you need to calculate the workbook again.
worksheet.getRange("A1").setValue(1);
worksheet.getRange("B1").setFormula("=A1*2");
workbook.calculate();
workbook.setEnableCalculation(false);
worksheet.getRange("A1").setValue(10);
workbook.calculate();
Object value = worksheet.getRange("B1").getValue();
boolean enabled = workbook.getEnableCalculation();
true if the calculation engine is enabled; otherwise, false.When this property is false, formulas in the current workbook are no longer recalculated. If formula results are retrieved while calculation is disabled, the last calculated results from before calculation was disabled are returned.
This property is intended for large batch updates of values or formulas when updated calculation results are not needed until the batch is complete. Set this property to false before the batch to improve performance, and set it back to true when you need to calculate the workbook again.
worksheet.getRange("A1").setValue(1);
worksheet.getRange("B1").setFormula("=A1*2");
workbook.calculate();
workbook.setEnableCalculation(false);
worksheet.getRange("A1").setValue(10);
workbook.calculate();
Object value = worksheet.getRange("B1").getValue();
value - true if the calculation engine is enabled; otherwise, false.The returned culture affects culture-related features such as localized formatting and formula behavior. If no culture has been explicitly set, the default value is Locale.getDefault().
workbook.setCulture(Locale.US);
worksheet.getRange("A1").setValue(43245.5922);
worksheet.getRange("A1").setNumberFormat("[$-x-sysdate]dddd, mmmm dd, yyyy");
String text = worksheet.getRange("A1").getText();
Locale culture = workbook.getCulture();
This setting affects culture-sensitive features such as localized formulas and culture-dependent date and time formats.
The locale should include both language and country or region, such as Locale.CHINA, Locale.KOREA, or Locale.US.
workbook.setCulture(Locale.US);
worksheet.getRange("A1").setValue(43245.5922);
worksheet.getRange("A1").setNumberFormat("[$-x-sysdate]dddd, mmmm dd, yyyy");
String text = worksheet.getRange("A1").getText();
value - The locale to apply to the workbook. Use a locale that includes both language and country or region.Use this method to retrieve the table style name that new tables use by default in the workbook.
workbook.setDefaultTableStyle("TableStyleMedium3");
worksheet.getRange("A1:B2").setValue(new Object[][]{
{"Product", "Sales"},
{"Tablet", 1200}
});
ITable table = worksheet.getTables().add(worksheet.getRange("A1:B2"), true);
ITableStyle tableStyle = table.getTableStyle();
String tableStyleName = tableStyle.getName();
String defaultTableStyle = workbook.getDefaultTableStyle();
Use this method to set the table style name that new tables use by default in the workbook.
workbook.setDefaultTableStyle("TableStyleMedium3");
worksheet.getRange("A1:B2").setValue(new Object[][]{
{"Product", "Sales"},
{"Tablet", 1200}
});
ITable table = worksheet.getTables().add(worksheet.getRange("A1:B2"), true);
ITableStyle tableStyle = table.getTableStyle();
String tableStyleName = tableStyle.getName();
value - The name of the default table style.Use the returned INames collection to add, retrieve, and manage names defined at the workbook level.
workbook.getNames().add("SalesTotal", "=Sheet1!$A$1:$A$3");
INames names = workbook.getNames();
IName name = names.get("SalesTotal");
INames collection that represents the workbook-specified names.Use setAuthor(String) to assign the author metadata before retrieving it.
workbook.setAuthor("Author");
String author = workbook.getAuthor();
workbook.setAuthor("Author");
value - The author of the workbook.IPivotCaches collection that contains all IPivotTable caches in the workbook.Use this method to access existing PivotTable caches or create a new cache from source data before adding a PivotTable.
worksheet.getRange("A1:B4").setValue(new Object[][] {
{"Product", "Sales"},
{"Apple", 100},
{"Pear", 200},
{"Orange", 150}
});
IPivotCaches pivotCaches = workbook.getPivotCaches();
IPivotCache pivotCache = pivotCaches.create(worksheet.getRange("A1:B4"));
IPivotCaches collection for the workbook.The reference style determines how cell references are represented in formulas and addresses, such as ReferenceStyle.A1 style references like A1 or ReferenceStyle.R1C1 style references like R1C1.
worksheet.getRange("B1").setValue(100);
worksheet.getRange("C1").setValue(200);
workbook.setReferenceStyle(ReferenceStyle.R1C1);
ReferenceStyle style = workbook.getReferenceStyle();
worksheet.getRange("A1").setFormula("=RC[1]+RC[2]");
ReferenceStyle.A1 or ReferenceStyle.R1C1.Use this method to switch between ReferenceStyle.A1 references such as A1 and ReferenceStyle.R1C1 references such as R1C1 or R[0]C[1].
worksheet.getRange("B1").setValue(100);
worksheet.getRange("C1").setValue(200);
workbook.setReferenceStyle(ReferenceStyle.R1C1);
worksheet.getRange("A1").setFormula("=RC[1]+RC[2]");
value - The reference style to use for cell references. Use ReferenceStyle.A1 for A1-style references or ReferenceStyle.R1C1 for R1C1-style references. If null, A1-style references are used.This method returns an IStyleCollection that provides access to the built-in and custom styles available in the workbook.
IStyleCollection styles = workbook.getStyles();
IStyle style = styles.add("DataStyle");
style.getFont().setBold(true);
worksheet.getRange("A1").setStyle(style);
IStyleCollection that represents all styles in the current workbook.ITableStyleCollection for the current workbook.This collection contains the table styles available in the workbook, including built-in styles and any custom table styles added to it.
ITableStyleCollection tableStyles = workbook.getTableStyles();
ITableStyle customStyle = tableStyles.add("SalesStyle");
ITableStyle builtInStyle = tableStyles.get("TableStyleMedium3");
worksheet.getTables().add(worksheet.getRange("A1:B3"), true).setTableStyle(builtInStyle);
ITableStyleCollection that represents the table styles in the current workbook.Use this method to access the current ITheme applied to the workbook. The returned theme can be inspected or reused with setTheme(ITheme).
ITheme theme = Themes.GetFacet();
workbook.setTheme(theme);
String themeName = theme.getName();
ITheme currentTheme = workbook.getTheme();
ITheme instance associated with the workbook.The specified theme becomes the workbook's active theme and is used to update theme-based formatting in the workbook.
ITheme theme = Themes.GetFacet();
workbook.setTheme(theme);
String themeName = theme.getName();
value - The theme to apply to the workbook. Must not be null.IllegalArgumentException - if value is null.The returned IIconSets object can be used to retrieve built-in icon sets for icon set conditional formatting and icon-based filtering.
worksheet.getRange("A1:A3").setValue(new Object[][] {
{"Score"},
{30},
{90}
});
IIconSetCondition condition = worksheet.getRange("A2:A3").getFormatConditions().addIconSetCondition();
condition.setIconSet(workbook.getIconSets().get(IconSetType.Icon3TrafficLights1));
IIconSets iconSets = workbook.getIconSets();
IWorksheets collection that represents all worksheets in the workbook.This method returns the workbook-level worksheets collection. Use the returned collection to access worksheets by index or name, and to manage worksheets in the workbook.
worksheet.setName("Summary");
IWorksheets sheets = workbook.getWorksheets();
IWorksheet firstSheet = sheets.get(0);
IWorksheet summarySheet = sheets.get("Summary");
IWorksheets collection that represents all worksheets in the workbook.Use the returned ISheetTabs object to access sheet tab information such as the number of tabs or a specific tab by index or name.
ISheetTabs sheetTabs = workbook.getSheetTabs();
if (sheetTabs.getCount() > 0) {
ISheetTab firstTab = sheetTabs.get(0);
String tabName = firstTab.getName();
}
ISheetTabs object that represents the sheet tabs in the workbook.Returns the worksheet that is currently active in the workbook. Returns null if no worksheet is active.
IWorksheet detailSheet = workbook.getWorksheets().add();
detailSheet.activate();
IWorksheet activeSheet = workbook.getActiveSheet();
IWorksheet, or null if no worksheet is active.ISlicerCaches collection associated with the workbook.Use this collection to access existing slicer caches in the workbook or to add new ones for supported data sources such as tables and PivotTables.
worksheet.getRange("A1:B3").setValue(new Object[][]{
{"Category", "Amount"},
{"Fruit", 100},
{"Vegetable", 200}
});
ITable table = worksheet.getTables().add(worksheet.getRange("A1:B3"), true);
ISlicerCaches slicerCaches = workbook.getSlicerCaches();
ISlicerCache slicerCache = slicerCaches.add(table, "Category");
ISlicerCaches collection associated with the workbook.This method recalculates workbook formulas that require calculation. If iterative calculation is enabled, all formulas in the workbook are marked for recalculation before the calculation is performed.
worksheet.getRange("A1").setValue(100);
worksheet.getRange("B1").setFormula("=A1*2");
workbook.calculate();
Object value = worksheet.getRange("B1").getValue();
Use this method to invalidate cached formula results for the entire workbook. After calling this method, invoke calculate(), or retrieve formula results while calculation is enabled, to trigger recalculation.
worksheet.getRange("A1").setValue(1);
worksheet.getRange("A2").setFormula("=A1*2");
workbook.dirty();
workbook.calculate();
Object value = worksheet.getRange("A2").getValue();
The returned list contains any JsonError objects found during deserialization.
String json = "{\"version\":\"7.0.0\",\"sheets\":{\"Sheet1\":{\"data\":{\"dataTable\":{\"0\":{\"0\":{\"value\":\"Name\"},\"1\":{\"value\":\"Test\"}}}}}}}";
List<JsonError> errors = workbook.fromJson(json);
json - The SpreadJS JSON (SSJSON) string to load into this workbook. Must not be null.JsonError objects found during deserialization.Use this method to control deserialization behavior with a DeserializationOptions instance. The returned list contains any JsonError objects found during deserialization.
String json = "{\"version\":\"7.0.0\",\"sheets\":{\"Sheet1\":{\"data\":{\"dataTable\":{\"0\":{\"0\":{\"value\":\"Name\"},\"1\":{\"value\":\"Test\"}}}}}}}";
DeserializationOptions options = new DeserializationOptions();
List<JsonError> errors = workbook.fromJson(json, options);
json - The SpreadJS JSON (SSJSON) string to load into this workbook. Must not be null.deserializationOptions - The DeserializationOptions object that controls how the JSON content is deserialized. If null, default deserialization options are used.JsonError objects found during deserialization.The returned list contains any JsonError objects found during deserialization.
worksheet.getRange("A1").setValue("Name");
String json = workbook.toJson();
DeserializationOptions options = new DeserializationOptions();
options.setDoNotRecalculateAfterLoad(true);
List<JsonError> errors = workbook.fromJson(
new ByteArrayInputStream(json.getBytes())
);
stream - The input stream that provides the SpreadJS JSON (SSJSON) content to load. Must not be null.JsonError objects found during deserialization.Use this method to control deserialization behavior with a DeserializationOptions instance. The returned list contains any JsonError objects found during deserialization.
worksheet.getRange("A1").setValue("Name");
String json = workbook.toJson();
DeserializationOptions options = new DeserializationOptions();
options.setDoNotRecalculateAfterLoad(true);
List<JsonError> errors = workbook.fromJson(
new ByteArrayInputStream(json.getBytes()),
options
);
stream - The input stream that provides the SpreadJS JSON (SSJSON) content to load. Must not be null.deserializationOptions - The DeserializationOptions object that controls how the JSON content is deserialized. If null, default deserialization options are used.JsonError objects found during deserialization.Use this method to serialize the current workbook content to JSON.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toJson();
Use SerializationOptions to control how workbook content is serialized, such as whether styles or formulas are included in the generated JSON.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
SerializationOptions options = new SerializationOptions();
options.setIgnoreStyle(true);
String json = workbook.toJson(options);
serializationOptions - The SerializationOptions object that specifies how the workbook is serialized to JSON.This method writes the workbook content to the specified output stream in JSON format. The current implementation forwards to toJson(OutputStream,SerializationOptions) with null for the serialization options.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.toJson(outputStream);
String json = new String(outputStream.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
stream - The output stream that receives the generated JSON data.Use SerializationOptions to control how workbook content is serialized, such as whether styles or formulas are included in the generated JSON.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
ByteArrayOutputStream stream = new ByteArrayOutputStream();
SerializationOptions serializationOptions = new SerializationOptions();
serializationOptions.setIgnoreStyle(true);
workbook.toJson(stream, serializationOptions);
String json = new String(stream.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
stream - The output stream that receives the generated JSON content.serializationOptions - The SerializationOptions object that specifies how the workbook is serialized to JSON.Use this method to check whether a workbook file requires a password before opening it. If the file is encrypted, open it with open(String,String).
worksheet.getRange("A1").setValue("Confidential");
String fileName = java.nio.file.Files.createTempFile("protected-report", ".xlsx").toString();
String password = getPasswordFromSecureSource();
workbook.save(fileName, password);
boolean isEncrypted = workbook.isEncryptedFile(fileName);
fileName - The name or path of the file to check. Must not be null.true if the specified file is password protected; otherwise, false.Use this method before opening a workbook stream to decide whether a password should be supplied to open(InputStream,String).
worksheet.getRange("A1").setValue("Confidential");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String password = getPasswordFromSecureSource();
workbook.save(outputStream, password);
InputStream fileStream = new ByteArrayInputStream(outputStream.toByteArray());
boolean encrypted = workbook.isEncryptedFile(fileStream);
fileStream - The input file stream to inspect.true if the specified file stream is password protected; otherwise, false.This method opens the specified file by using the default open options. The file type is inferred from the file name extension.
The fileName value is used directly as a file system path. Pass only validated paths from trusted sources.
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir"), "QuarterlyReport.xlsx").toString();
workbook.open(filePath);
fileName - The path and name of the workbook file to open. Must not be null.Uses the provided DeserializationOptions to control how the JSON content is deserialized into the workbook.
DeserializationOptions options = new DeserializationOptions();
options.setIgnoreStyle(true);
List<JsonError> errors = workbook.open("spread_js_exported.json", options);
fileName - The JSON file to open.deserializationOptions - The options that control JSON deserialization.JsonError objects generated while opening the JSON file.open(String,OpenOptionsBase) instead.This method opens a password-protected workbook from the specified file path.
fileName - The path and name of the Excel file to open. Must not be null.password - The password for the file. Use the password required by the workbook; null if no password is needed.Use this overload to control how the workbook is loaded for supported file formats. The options argument can be an instance of CsvOpenOptions, SjsOpenOptions, XlsmOpenOptions, XlsxOpenOptions, or XltxOpenOptions.
XlsxOpenOptions options = new XlsxOpenOptions();
options.setDoNotRecalculateAfterOpened(true);
String fileName = java.nio.file.Paths.get(System.getProperty("user.dir"), "OpenWorkbookWithOptions.xlsx").toString();
workbook.open(fileName, options);
fileName - The file to open.options - The open options for the file. Must be compatible with the file format; null uses no explicit open options.Use this overload when the file format should be provided explicitly instead of being inferred from the file name.
workbook.open("Template.sjs", OpenFileFormat.Sjs);
IWorksheet firstSheet = workbook.getWorksheets().get(0);
fileName - The file to open.fileFormat - The format of the file.Use this method to load workbook data from an InputStream.
worksheet.getRange("A1").setValue("Name");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.save(stream, SaveFileFormat.Xlsx);
InputStream fileStream = new ByteArrayInputStream(stream.toByteArray());
workbook.open(fileStream);
fileStream - The stream that contains the Excel file data. Must not be null.open(InputStream,OpenOptionsBase) instead.Use this method to load a password-protected workbook from an InputStream.
fileStream - The file stream to open. Must not be null.password - The password for the file. Use an empty string if the file has no password.
String fileName = java.nio.file.Paths.get(System.getProperty("user.dir"), "Report.xlsx").toString();
XlsxOpenOptions options = new XlsxOpenOptions();
options.setDoNotRecalculateAfterOpened(true);
try (InputStream fileStream = new java.io.FileInputStream(fileName)) {
workbook.open(fileStream, options);
}
IWorksheet firstSheet = workbook.getWorksheets().get(0);
String sheetName = firstSheet.getName();
fileStream - The file stream.options - The options used when opening the file stream. Possible types:
String fileName = java.nio.file.Paths.get(System.getProperty("user.dir"), "Report.xlsx").toString();
try (InputStream fileStream = new java.io.FileInputStream(fileName)) {
workbook.open(fileStream, OpenFileFormat.Xlsx);
}
IWorksheet firstSheet = workbook.getWorksheets().get(0);
String sheetName = firstSheet.getName();
fileStream - The specified file stream.fileFormat - The format of the file stream.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir"), "SalesReport.xlsx").toString();
workbook.save(filePath);
fileName - The path of the destination file.Use this method to write the current workbook to disk and apply password protection to the saved file.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B1").setValue("Value");
worksheet.getRange("A2").setValue("Test");
worksheet.getRange("B2").setValue(100);
String password = getPasswordFromSecureSource();
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir"), "ProtectedReport.xlsx").toString();
workbook.save(filePath, password);
fileName - The path of the destination file.password - The password used to protect the saved file.Use this method to control how the workbook is written by providing a SaveOptionsBase implementation for the target file type.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
PdfSaveOptions options = new PdfSaveOptions();
workbook.save("report.pdf", options);
fileName - The path of the destination file.options - The save options that determine how the file is written. Supported types include CsvSaveOptions, HtmlSaveOptions, PdfSaveOptions, SjsSaveOptions, XlsmSaveOptions, XlsxSaveOptions, and XltxSaveOptions. null behavior is not specified.Use this method when the target file format needs to be specified explicitly instead of being inferred from the file name.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String filePath = java.nio.file.Paths.get(System.getProperty("user.dir"), "SalesReport.xlsx").toString();
workbook.save(filePath, SaveFileFormat.Xlsx);
fileName - The path of the destination file.fileFormat - The file format to use when saving the workbook.Use this method to write the current workbook data to an OutputStream.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
workbook.save(outputStream);
byte[] bytes = outputStream.toByteArray();
} catch (IOException e) {
}
outputStream - The output stream to which the workbook is saved. Must not be null.save(OutputStream,SaveOptionsBase) instead.outputStream - The output stream to which the workbook is saved.password - The password of the file.Use this method to write workbook data to an OutputStream and control the output by providing a SaveOptionsBase implementation. Supported option types include CsvSaveOptions, HtmlSaveOptions, PdfSaveOptions, SjsSaveOptions, XlsmSaveOptions, XlsxSaveOptions, and XltxSaveOptions.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
XlsxSaveOptions options = new XlsxSaveOptions();
options.setIncludeAutoMergedCells(true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.save(stream, options);
byte[] bytes = stream.toByteArray();
fileStream - The destination stream to receive the saved workbook data.options - The save options that control how the workbook is written. This parameter should be an instance of a supported SaveOptionsBase derived type.Use this method to write the current workbook content to an OutputStream when the target format must be specified explicitly.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
workbook.save(outputStream, SaveFileFormat.Xlsx);
byte[] bytes = outputStream.toByteArray();
} catch (Exception e) {
// Handle exception
}
fileStream - The destination stream to receive the saved workbook data. Must not be null.fileFormat - The format used to save the workbook to the stream.This method returns a collection of FontInfo objects that describe the fonts currently used by workbook content and styles.
worksheet.getRange("A1").setValue("Title");
worksheet.getRange("A1").getFont().setName("Wide Latin");
worksheet.getRange("B1").setValue("Body");
worksheet.getRange("B1").getFont().setName("Calibri");
List<FontInfo> fonts = workbook.getUsedFonts();
FontInfo objects that represent the fonts used in the workbook.The default call protects the workbook structure with structure set to true and leaves workbook window protection disabled because windows is false. This protection restricts workbook structure operations, such as adding, moving, deleting, hiding, unhiding, or renaming worksheets, in supported spreadsheet applications. It does not encrypt the workbook, provide content access control, or prevent changes made through the object model before saving.
worksheet.getRange("A1").setValue("Quarterly Report");
worksheet.setVisible(false);
workbook.protect();
If structure is true, workbook structure is protected to prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets.
worksheet.getRange("A1").setValue("Quarterly Report");
workbook.protect(true);
structure - true to protect the workbook structure; otherwise, false.Set structure to true to prevent users from viewing hidden worksheets, adding, moving, deleting, hiding, or renaming worksheets. Set windows to true to prevent users from moving, resizing, or closing the workbook window, or hiding and unhiding windows. The window protection option is available only in Excel 2007, Excel 2010, Excel for Mac 2011, and Excel 2016 for Mac.
worksheet.getRange("A1").setValue("Quarterly Report");
workbook.protect(true, true);
structure - true to protect the workbook structure; otherwise, false.windows - true to protect the workbook windows; otherwise, false. This option is available only in Excel 2007, Excel 2010, Excel for Mac 2011, and Excel 2016 for Mac.Use this method to apply workbook protection with a password. Protected workbooks prevent users from modifying the workbook when it is opened in a supported spreadsheet application.
worksheet.getRange("A1").setValue("Quarterly Report");
// Get the password from user input via getPasswordFromSecureSource().
String password = getPasswordFromSecureSource();
workbook.protect(password);
workbook.unprotect(password);
password - The password used to protect the workbook. If null or empty, the workbook is still protected without a password.If structure is true, workbook structure is protected to prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
// Get the password from user input via getPasswordFromSecureSource().
String password = getPasswordFromSecureSource();
workbook.protect(password, true);
password - The password used to protect the workbook.structure - true to protect the workbook structure; otherwise, false.Use this overload to protect both workbook structure and workbook windows with a password. Set structure to true to prevent users from viewing hidden worksheets, adding, moving, deleting, hiding, or renaming worksheets. Set windows to true to prevent users from moving, resizing, or closing the workbook window, or hiding and unhiding windows.
This protection only restricts workbook structure and window operations in supported spreadsheet applications. It does not encrypt workbook contents and should not be used as a confidentiality or access-control mechanism. To protect sensitive data, use file encryption such as password-protected XlsxSaveOptions or other access-control measures, and avoid storing unencrypted sensitive data in hidden worksheets.
worksheet.getRange("A1").setValue("Quarterly Report");
// Get the password from user input via getPasswordFromSecureSource().
String password = getPasswordFromSecureSource();
workbook.protect(password, true, true);
workbook.unprotect(password);
password - Password to protect the workbook.structure - True to protect the structure of the workbook (To prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets).windows - True to prevent users from moving, resizing, or closing the workbook window, or hide/unhide windows. This option is available only in Excel 2007, Excel 2010, Excel for Mac 2011, and Excel 2016 for Mac.Use this method to remove protection that was applied with protect() or another non-password overload of protect. If the workbook was protected with a password, use unprotect(String) with the correct password instead.
worksheet.getRange("A1").setValue("Confidential");
workbook.protect();
workbook.unprotect();
Pass the password that was used with protect(String) to remove workbook protection. If the workbook was protected without a password, the password argument is ignored.
worksheet.getRange("A1").setValue("Confidential");
// Get the password from user input via getPasswordFromSecureSource().
String password = getPasswordFromSecureSource();
workbook.protect(password);
workbook.unprotect(password);
password - The password used to protect the workbook. This value is ignored if the workbook was protected without a password.Use this method to register an alias that can be referenced by binding fields in a template. For example, after adding a data source with the alias title, the template can use {{title}}} in its binding fields.
worksheet.getRange("A1").setValue("{{title}}");
String reportTitle = "Sales Report";
workbook.addDataSource("title", reportTitle);
workbook.processTemplate();
Object value = worksheet.getRange("A1").getValue();
name - The alias name of the data source used by template binding fields.dataSource - The data source to register. Common choices include a JsonDataSource, a ResultSet, an ITableDataSource, a custom object or object collection, or a scalar value such as a string, number, or date.Call this method after adding one or more data sources with addDataSource(String,Object).
worksheet.getRange("A1").setValue("{{ds.name}}");
String json = "[{\"name\":\"jack\",\"age\":12,\"height\":160},{\"name\":\"alice\",\"age\":25,\"height\":165},{\"name\":\"peter\",\"age\":21,\"height\":180}]";
workbook.addDataSource("ds", new JsonDataSource(json));
workbook.processTemplate();
Object value = worksheet.getRange("A1").getValue();
Use this method to process template data in the current workbook while allowing the operation to be canceled through a CancellationToken. If cancellation occurs, the workbook can remain in a partially processed state.
worksheet.getRange("A1").setValue("{{ds.name}}");
String json = "[{\"name\":\"jack\",\"age\":12,\"height\":160},{\"name\":\"alice\",\"age\":25,\"height\":165},{\"name\":\"peter\",\"age\":21,\"height\":180}]";
workbook.addDataSource("ds", new JsonDataSource(json));
try (CancellationTokenSource cancellation = new CancellationTokenSource()) {
workbook.processTemplate(cancellation.getToken());
} catch (Exception e) {
// Handle exception
}
cancellationToken - A token used to monitor cancellation requests. Pass null if cancellation is not required.CancellationException - if the specified CancellationToken is canceled while template processing is in progress.Unlike processTemplate(), this method generates the report in a new IWorkbook so the current template workbook can be retained for further use.
worksheet.getRange("A1").setValue("Class: {{className}}");
workbook.addDataSource("className", "Class 3");
IWorkbook report = workbook.generateReport();
Object value = report.getWorksheets().get(0).getRange("A1").getValue();
IWorkbook instance that contains the generated report.Use this method to generate a new IWorkbook from the current template workbook while limiting report generation to the provided worksheets.
worksheet.getRange("A1").setValue("{{name}}");
workbook.addDataSource("name", "Quarterly Report");
IWorkbook report = workbook.generateReport(worksheet);
Object value = report.getWorksheets().get(0).getRange("A1").getValue();
worksheets - The worksheets to process.IWorkbook object that contains the generated report.If no graphics information has been assigned, the workbook uses built-in graphics information.
worksheet.getRange("A1").setValue("12345");
class CustomGraphicsInfo implements IGraphicsInfo {
@Override
public double getDigitWidth(TextFormatInfo textFormat) {
if ("Calibri".equals(textFormat.getFontFamily())) {
return 8 * textFormat.getFontSize() / 11;
}
return 7 * textFormat.getFontSize() / 11;
}
}
IGraphicsInfo graphicsInfo = new CustomGraphicsInfo();
workbook.setGraphicsInfo(graphicsInfo);
IGraphicsInfo currentGraphicsInfo = workbook.getGraphicsInfo();
Use this property to provide custom digit-width measurement logic for workbook rendering and layout calculations. If value is null, the workbook uses built-in graphics information.
worksheet.getRange("A1").setValue("12345");
class CustomGraphicsInfo implements IGraphicsInfo {
@Override
public double getDigitWidth(TextFormatInfo textFormat) {
if ("Calibri".equals(textFormat.getFontFamily())) {
return 8 * textFormat.getFontSize() / 11;
}
return 7 * textFormat.getFontSize() / 11;
}
}
IGraphicsInfo graphicsInfo = new CustomGraphicsInfo();
workbook.setGraphicsInfo(graphicsInfo);
value - The graphics information to use for digit-width measurement and related layout calculations. Set to null to use the built-in graphics information.Use this method to retrieve the external workbook names referenced by cross-workbook formulas before calling updateExcelLink(String) or updateExcelLink(String,IWorkbook) to refresh linked data.
worksheet.getRange("B1").setFormula("='[SourceIWorkbook.xlsx]Sheet1'!A1");
List<String> linkSources = workbook.getExcelLinkSources();
Use this method to refresh a linked workbook reference identified by name. To obtain available link names, use getExcelLinkSources().
String sourceFileName = "SourceWorkbook.xlsx";
IWorkbook sourceWorkbook = new Workbook();
sourceWorkbook.getWorksheets().get(0).getRange("A1").setValue("Updated value");
sourceWorkbook.save(sourceFileName);
worksheet.getRange("B1").setFormula("='[" + sourceFileName + "]Sheet1'!A1");
for (String linkSource : workbook.getExcelLinkSources()) {
workbook.updateExcelLink(linkSource);
}
Object updatedValue = worksheet.getRange("B1").getValue();
name - The name of the Excel link to update. This value should match one of the linked workbook names; null behavior is undefined.Use this method to refresh the cached data for one linked workbook referenced by formulas in the current workbook. The name should match the linked workbook name used in the external reference.
worksheet.getRange("B1").setFormula("='[SourceWorkbook.xlsx]Sheet1'!A1");
IWorkbook sourceWorkbook = new Workbook();
sourceWorkbook.getWorksheets().get(0).getRange("A1").setValue("Hello");
workbook.updateExcelLink("SourceWorkbook.xlsx", sourceWorkbook);
Object updatedValue = worksheet.getRange("B1").getValue();
name - The name of the linked workbook to update.sourceWorkbook - The workbook that provides the source data for the specified link. null behavior is undefined.Use this method to refresh the caches of external workbook links used by cross-workbook formulas.
String sourceFileName = "SourceWorkbook.xlsx";
IWorkbook sourceWorkbook = new Workbook();
sourceWorkbook.getWorksheets().get(0).getRange("A1").setValue("Updated value");
sourceWorkbook.save(sourceFileName);
worksheet.getRange("B1").setFormula("='[" + sourceFileName + "]Sheet1'!A1");
List<String> linkSources = workbook.getExcelLinkSources();
workbook.updateExcelLinks();
Object updatedValue = worksheet.getRange("B1").getValue();
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String sjsJson = workbook.toSjsJson();
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
SjsSaveOptions options = new SjsSaveOptions();
options.setIncludeEmptyRegionCells(false);
String sjsJson = workbook.toSjsJson(options);
options - The save options used to generate the SJS JSON content.Use SjsSaveOptions to control how workbook content is included when generating the SJS JSON output.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
SjsSaveOptions options = new SjsSaveOptions();
options.setIncludeFormulas(true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.toSjsJson(stream, options);
String sjsJson = new String(stream.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
stream - The output stream that receives the integrated JSON string.options - The save options used when generating the SpreadJS .sjs JSON output.Use this method to export the workbook as a single SJS JSON payload through an OutputStream.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.toSjsJson(stream);
String sjsJson = new String(stream.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
stream - The output stream that receives the generated SJS JSON content. Must not be null.The original barcode formulas are cleared after the conversion. The converted pictures use ImageType.SVG.
worksheet.getRange("B2").setValue("Policy:411");
worksheet.getRange("C2").setFormula("=BC_QRCODE(B2)");
workbook.calculate();
workbook.convertBarcodeToPicture();
int pictureCount = worksheet.getShapes().getCount();
String fileName = "BarcodeReport.xlsx";
workbook.save(fileName);
The converted pictures are placed at the original barcode positions, and the original barcode formulas are cleared after the conversion.
worksheet.getRange("A1").setValue("Policy:411");
worksheet.getRange("B1").setFormula("=BC_QRCODE(A1)");
workbook.convertBarcodeToPicture(ImageType.JPG);
int pictureCount = worksheet.getShapes().getCount();
String fileName = "BarcodeReportJpg.xlsx";
workbook.save(fileName);
imageType - The ImageType of the converted barcode pictures.UnsupportedOperationException - if imageType is ImageType.EMF or ImageType.WMF.
worksheet.getRange("A1").setValue("Name");
worksheet.getRange("B1").setValue("Value");
String sjsJson = workbook.toSjsJson();
IWorkbook importedWorkbook = new Workbook();
importedWorkbook.fromSjsJson(sjsJson);
json - The JSON string containing .sjs file content.SjsOpenOptions.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toSjsJson();
SjsOpenOptions openOptions = new SjsOpenOptions();
IWorkbook importedWorkbook = new Workbook();
importedWorkbook.fromSjsJson(json, openOptions);
json - The JSON string that contains workbook data in SpreadJS .sjs format.openOptions - The options used to open the SpreadJS .sjs content.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toSjsJson();
SjsOpenOptions openOptions = new SjsOpenOptions();
IWorkbook importedWorkbook = new Workbook();
try (InputStream stream = new ByteArrayInputStream(json.getBytes(java.nio.charset.StandardCharsets.UTF_8))) {
importedWorkbook.fromSjsJson(stream, openOptions);
}
stream - The JSON stream.openOptions - The open options for opening SpreadJS .sjs file.
worksheet.getRange("A1").setValue("Name");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.toSjsJson(stream);
InputStream inputStream = new ByteArrayInputStream(stream.toByteArray());
IWorkbook importedWorkbook = new Workbook();
importedWorkbook.fromSjsJson(inputStream);
stream - The JSON stream that contains SpreadJS .sjs file content. Must not be null.This method blocks the current thread until all pending calculations, including asynchronous calculations, have completed. Call this method before performing operations that depend on calculated results.
worksheet.getRange("A1").setFormula("=IMAGE(\"https://example.com/logo.jpg\")");
workbook.calculate();
workbook.waitForCalculationToFinish();
CellPicture picture = worksheet.getRange("A1").getCellPicture();
Use this property to determine whether users can display the PivotTable field list for PivotTables in the workbook. The default value is true.
worksheet.getRange("A1:B4").setValue(new Object[][] {
{"Product", "Sales"},
{"Laptop", 1200},
{"Tablet", 900},
{"Laptop", 700}
});
IPivotCache pivotCache = workbook.getPivotCaches().create(worksheet.getRange("A1:B4"));
IPivotTable pivotTable = worksheet.getPivotTables().add(pivotCache, worksheet.getRange("D1"), "SalesPivot");
pivotTable.getPivotFields().get("Product").setOrientation(PivotFieldOrientation.RowField);
pivotTable.addDataField(pivotTable.getPivotFields().get("Sales"), "Sum of Sales", ConsolidationFunction.Sum);
workbook.setShowPivotTableFieldList(false);
boolean canShowFieldList = workbook.getShowPivotTableFieldList();
true if the PivotTable field list can be shown; otherwise, false.Use this property to set whether users can display the PivotTable field list for PivotTables in the workbook.
worksheet.getRange("A1:B4").setValue(new Object[][] {
{"Product", "Sales"},
{"Laptop", 1200},
{"Tablet", 900},
{"Laptop", 700}
});
IPivotCache pivotCache = workbook.getPivotCaches().create(worksheet.getRange("A1:B4"));
IPivotTable pivotTable = worksheet.getPivotTables().add(pivotCache, worksheet.getRange("D1"), "SalesPivot");
pivotTable.getPivotFields().get("Product").setOrientation(PivotFieldOrientation.RowField);
pivotTable.addDataField(pivotTable.getPivotFields().get("Sales"), "Sum of Sales", ConsolidationFunction.Sum);
workbook.setShowPivotTableFieldList(false);
boolean canShowFieldList = workbook.getShowPivotTableFieldList();
value - true if the PivotTable field list can be shown; otherwise, false.The cloned workbook is an exact copy of the current workbook at the time this method is called. Changes made to the cloned workbook do not affect the original workbook.
For user-defined objects stored in workbook content, the cloning process uses the object's clone implementation when available. Otherwise, those objects are copied by reference. IWorkbook and worksheet events are not cloned and must be registered again on the cloned workbook if needed.
IWorkbook instance that is an exact copy of the current workbook.