[]
IWorkbookThis class provides 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.
A new workbook is initialized in memory and contains one empty worksheet named Sheet1 in the getWorksheets() collection.
Workbook 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);
static IFontProviderstatic StringWorkbook()Workbook(WorkbookOptions options) Workbook(String licenseKey,
WorkbookOptions options) static voidstatic voidAddCustomFunction(CustomFunction func,
boolean canOverride) 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) generateReport(IWorksheet... worksheets) static IAIModelRequestHandlerbooleanbooleanbooleanbooleanbooleanfinal IGraphicsInfogetName()getNames()static String[]getNames(InputStream fileStream) static String[]getPath()IPivotCaches collection that contains all IPivotTable caches in the workbook.booleanbooleanbooleanfinal IWorksheetsbooleanISlicerCaches collection associated with the workbook.ITableStyleCollection for the current workbook.static IJsonSerializergetTheme()static IJsonSerializerstatic IWebRequestHandlerIWebRequestHandler instance that is used to handle web requests.IWorksheets collection that represents all worksheets in the workbook.static Object[][]importData(InputStream fileStream,
String sourceName) static Object[][]importData(InputStream fileStream,
String worksheetName,
int row,
int column,
int rowCount,
int columnCount) static Object[][]importData(String fileName,
String sourceName) static Object[][]importData(String fileName,
String worksheetName,
int row,
int column,
int rowCount,
int columnCount) booleanisEncryptedFile(InputStream fileStream) booleanisEncryptedFile(String fileName) final 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) voidsave(String,SaveOptionsBase) instead.static voidsetAIModelRequestHandler(IAIModelRequestHandler modelRequestHandler) voidsetAllowDynamicArray(boolean value) voidvoidsetAutoParse(boolean value) voidsetAutoRoundValue(boolean value) voidsetCulture(Locale value) voidsetDefaultTableStyle(String value) voidsetDeferUpdateDirtyState(boolean value) voidsetEnableCalculation(boolean value) final voidsetGraphicsInfo(IGraphicsInfo value) static voidSetLicenseFile(String licenseFilePath) static voidSetLicenseKey(String key) voidvoidvoidsetReferenceStyle(ReferenceStyle value) voidsetResetAdjacentRangeBorder(boolean value) voidsetShowPivotTableFieldList(boolean value) static voidvoidstatic voidstatic voidsetWebRequestHandler(IWebRequestHandler webRequestHandler) IWebRequestHandler instance that is used to handle web requests.toJson()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
Workbook.FontsFolderPath = java.nio.file.Paths.get("Resources", "Fonts").toString();
String fontsFolderPath = Workbook.FontsFolderPath;
options - The workbook options. Important: For licenses of the Chinese market, use SetLicenseFile or set the license in the GCEXCEL_JAVA_DEPLOY_LICENSE_V7 environment variable instead.
licenseKey - The license key. Important: For licenses of the Chinese market, use SetLicenseFile or set the license in the GCEXCEL_JAVA_DEPLOY_LICENSE_V7 environment variable instead.
licenseKey - The license key.options - The workbook options.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).
getAllowDynamicArray in interface IWorkbooktrue if dynamic array formulas are allowed for compatibility with IRange.setFormula(String); otherwise, false.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).
setAllowDynamicArray in interface IWorkbookvalue - true if dynamic array formulas are allowed for compatibility with IRange.setFormula(String); 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();
getDeferUpdateDirtyState in interface IWorkbooktrue 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();
setDeferUpdateDirtyState in interface IWorkbookvalue - 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");
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();
getFullName in interface IWorkbookUse 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();
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);
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);
open(String,OpenOptionsBase) instead.This method opens a password-protected workbook from the specified file path.
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);
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);
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);
open(InputStream,OpenOptionsBase) instead.Use this method to load a password-protected workbook from an InputStream.
Use this overload when the stream content format should be provided explicitly instead of being inferred from the stream data.
worksheet.getRange("A1").setValue("Name");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.save(stream, SaveFileFormat.Xlsx);
InputStream fileStream = new ByteArrayInputStream(stream.toByteArray());
workbook.open(fileStream, OpenFileFormat.Xlsx);
Use this overload to control how the workbook is loaded for supported stream formats. The options argument supports CsvOpenOptions, SjsOpenOptions, XlsmOpenOptions, XlsxOpenOptions, or XltxOpenOptions.
worksheet.getRange("A1").setValue("Name");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
workbook.save(stream, SaveFileFormat.Xlsx);
InputStream fileStream = new ByteArrayInputStream(stream.toByteArray());
XlsxOpenOptions options = new XlsxOpenOptions();
options.setDoNotRecalculateAfterOpened(true);
workbook.open(fileStream, options);
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);
save(String,SaveOptionsBase) instead.Use this method to write the current workbook to disk and apply password protection to 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);
save in interface IWorkbookfileName - 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);
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) {
}
save(OutputStream,SaveOptionsBase) instead.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();
save in interface IWorkbookfileStream - 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
}
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];
getAfterSaveEvent in interface IWorkbook
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];
getBeforeSaveEvent in interface IWorkbook
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];
getNewSheetEvent in interface IWorkbook
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.getActiveSheet().getRange("A1").setValue("Opened");
workbook.save(outputStream);
Workbook 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];
getOpenedEvent in interface IWorkbook
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];
getSheetActivateEvent in interface IWorkbook
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];
getSheetBeforeDeleteEvent in interface IWorkbook
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];
getSheetChangeEvent in interface IWorkbook
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];
getSheetDeactivateEvent in interface IWorkbook
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];
getSheetSelectionChange in interface IWorkbookReturns 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");
getOptions in interface IWorkbookIExcelOptions object that contains workbook option settings.The returned IBuiltInDocumentPropertyCollection provides access to built-in metadata such as author, title, subject, company, and other standard document properties.
workbook.getBuiltInDocumentProperties().setAuthor("Beryl");
workbook.getBuiltInDocumentProperties().setCompany("Example");
IBuiltInDocumentPropertyCollection properties = workbook.getBuiltInDocumentProperties();
getBuiltInDocumentProperties in interface IWorkbookUse 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");
getCustomDocumentProperties in interface IWorkbookUse 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();
getCustomXmlParts in interface IWorkbookThe 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();
getCustomViews in interface IWorkbookICustomViews 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("Eric");
protection.setReadOnlyRecommended(true);
// Get the password from user input via getPasswordFromSecureSource().
String password = getPasswordFromSecureSource();
protection.setWritePassword(password);
boolean writeReserved = protection.getWriteReserved();
boolean passwordMatches = protection.validatePassword(password);
getWriteProtection in interface IWorkbookWriteProtection object for the workbook.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);
getSignatures in interface IWorkbookUse this method to retrieve the serializer previously assigned through setTagJsonSerializer(IJsonSerializer). If no serializer has been set, this method returns null.
class TagSerializer implements IJsonSerializer {
public String serialize(Object value) {
return "\"" + value.toString() + "\"";
}
public Object deserialize(String json) {
return json.substring(1, json.length() - 1);
}
}
IJsonSerializer serializer = new TagSerializer();
Workbook.setTagJsonSerializer(serializer);
IJsonSerializer currentSerializer = Workbook.getTagJsonSerializer();
null if no serializer has been set.Use this method to register a custom IJsonSerializer for serializing and deserializing tag values when a workbook is converted to or from JSON. Set this parameter to null to clear the current serializer.
class TagSerializer implements IJsonSerializer {
public String serialize(Object value) {
return "\"" + value.toString() + "\"";
}
public Object deserialize(String json) {
return json.substring(1, json.length() - 1);
}
}
IJsonSerializer serializer = new TagSerializer();
Workbook.setTagJsonSerializer(serializer);
value - The JSON serializer for tag custom types. Specify null to remove the current serializer.Use this method to retrieve the current serializer configured by setValueJsonSerializer(IJsonSerializer) for custom value types when a workbook is converted to or from JSON.
class ValueWithUnit {
public double amount;
public String unit;
}
class ValueSerializer implements IJsonSerializer {
public String serialize(Object value) {
ValueWithUnit data = (ValueWithUnit) value;
return "{\"amount\":" + data.amount + ",\"unit\":\"" + data.unit + "\"}";
}
public Object deserialize(String json) {
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
ValueWithUnit data = new ValueWithUnit();
data.amount = jsonObject.get("amount").getAsDouble();
data.unit = jsonObject.get("unit").getAsString();
return data;
}
}
IJsonSerializer serializer = new ValueSerializer();
Workbook.setValueJsonSerializer(serializer);
IJsonSerializer currentSerializer = Workbook.getValueJsonSerializer();
null if no custom serializer is set.Use this method to register an IJsonSerializer that converts custom value objects when the workbook is converted to or from JSON. Set this parameter to null to clear the current custom value serializer.
class ValueWithUnit {
public double amount;
public String unit;
}
class ValueSerializer implements IJsonSerializer {
public String serialize(Object value) {
ValueWithUnit data = (ValueWithUnit) value;
return "{\"amount\":" + data.amount + ",\"unit\":\"" + data.unit + "\"}";
}
public Object deserialize(String json) {
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
ValueWithUnit data = new ValueWithUnit();
data.amount = jsonObject.get("amount").getAsDouble();
data.unit = jsonObject.get("unit").getAsString();
return data;
}
}
IJsonSerializer serializer = new ValueSerializer();
Workbook.setValueJsonSerializer(serializer);
value - The JSON serializer for custom cell values. null clears the current serializer.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();
getAutoParse in interface IWorkbooktrue 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();
setAutoParse in interface IWorkbookvalue - 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();
getAutoRoundValue in interface IWorkbooktrue 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();
setAutoRoundValue in interface IWorkbookvalue - 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);
getBookView in interface IWorkbookIWorkbookView 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();
getProtectStructure in interface IWorkbooktrue 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();
getProtectWindows in interface IWorkbooktrue if the workbook windows are protected; otherwise, false.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]");
getReferenceStyle in interface IWorkbookReferenceStyle.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]");
setReferenceStyle in interface IWorkbookvalue - 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.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");
getWorksheets in interface IWorkbookIWorksheets 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.
workbook.open("import.sjs");
ISheetTabs sheetTabs = workbook.getSheetTabs();
if (sheetTabs.getCount() > 0) {
ISheetTab firstTab = sheetTabs.get(0);
String tabName = firstTab.getName();
}
getSheetTabs in interface IWorkbookISheetTabs 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();
getActiveSheet in interface IWorkbookIWorksheet, or null if no worksheet is active.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();
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();
setTheme in interface IWorkbookvalue - 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();
getIconSets in interface IWorkbookUse 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();
getDefaultTableStyle in interface IWorkbookUse 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();
setDefaultTableStyle in interface IWorkbookvalue - The name of the default table style.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();
getCulture in interface IWorkbookThis 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();
setCulture in interface IWorkbookvalue - The locale to apply to the workbook. Use a locale that includes both language and country or region.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();
getEnableCalculation in interface IWorkbooktrue 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();
setEnableCalculation in interface IWorkbookvalue - true if the calculation engine is enabled; otherwise, false.
class MyAddFunction extends CustomFunction {
public MyAddFunction() {
super("WORKBOOK_API_MYADD", FunctionValueType.Number, new Parameter[] {
new Parameter(FunctionValueType.Number, 0d),
new Parameter(FunctionValueType.Number, 0d)
});
}
@Override
public Object evaluate(Object[] arguments, ICalcContext context) {
return (double) arguments[0] + (double) arguments[1];
}
}
Workbook.AddCustomFunction(new MyAddFunction());
worksheet.getRange("A1").setFormula("=WORKBOOK_API_MYADD(1,2)");
func - the custom function instance.
class MyAddFunction extends CustomFunction {
public MyAddFunction() {
super("MYADD_OVERRIDE", FunctionValueType.Number, new Parameter[] {
new Parameter(FunctionValueType.Number, 0d),
new Parameter(FunctionValueType.Number, 0d)
});
}
@Override
public Object evaluate(Object[] arguments, ICalcContext context) {
return (double) arguments[0] + (double) arguments[1];
}
}
Workbook.AddCustomFunction(new MyAddFunction(), true);
worksheet.getRange("A1").setFormula("=MYADD_OVERRIDE(1,2)");
func - the custom function instance.canOverride - override the exist function.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"));
getPivotCaches in interface IWorkbookIPivotCaches collection for the workbook.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");
getSlicerCaches in interface IWorkbookISlicerCaches collection associated with the workbook.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();
getUsedFonts in interface IWorkbookFontInfo objects that represent the fonts used in the workbook.
worksheet.getRange("A1").setValue(100);
worksheet.getRange("B1").setFormula("=A1*2");
workbook.calculate();
Object value = worksheet.getRange("B1").getValue();
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();
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);
getStyles in interface IWorkbookIStyleCollection 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);
getTableStyles in interface IWorkbookITableStyleCollection that represents the table styles in the current workbook.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");
Use setAuthor(String) to assign the author metadata before retrieving it.
workbook.setAuthor("Author");
String author = workbook.getAuthor();
workbook.setAuthor("Author");
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).
String fileName = java.nio.file.Paths.get("Users", "DefaultApps", "Documents", "EncryptedWorkbook.xlsx").toString();
boolean isEncrypted = workbook.isEncryptedFile(fileName);
isEncryptedFile in interface IWorkbookfileName - 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).
boolean encrypted = workbook.isEncryptedFile(fileStream);
isEncryptedFile in interface IWorkbookfileStream - The input file stream to inspect.true if the specified file stream is password protected; otherwise, false.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);
toJson in interface IWorkbookserializationOptions - 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);
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);
toJson in interface IWorkbookstream - The output stream that receives the generated JSON content.serializationOptions - The SerializationOptions object that specifies how the workbook is serialized to JSON.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);
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");
worksheet.getRange("B1").setValue("Test");
String json = workbook.toJson();
DeserializationOptions options = new DeserializationOptions();
List<JsonError> errors = workbook.fromJson(json, options);
fromJson in interface IWorkbookjson - 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())
);
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
);
fromJson in interface IWorkbookstream - 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.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toSjsJson();
workbook.fromSjsJson(json);
fromSjsJson in interface IWorkbookjson - The JSON string.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toSjsJson();
SjsOpenOptions openOptions = new SjsOpenOptions();
workbook.fromSjsJson(json, openOptions);
fromSjsJson in interface IWorkbookjson - The JSON string.openOptions - The open options for opening SpreadJS .sjs file.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toSjsJson();
workbook.fromSjsJson(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
fromSjsJson in interface IWorkbookstream - The JSON stream.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();
waitForCalculationToFinish in interface IWorkbookIWebRequestHandler instance that is used to handle web requests.This method provides centralized access to the application-level web request handler. The returned handler is the same instance that was previously assigned by setWebRequestHandler(IWebRequestHandler). It is used by workbook features that need to retrieve remote content, such as the IMAGE() function when the image source is a web URL.
class WebHandler implements IWebRequestHandler {
public CompletableFuture<WebRequestResult> getAsync(String requestUri) {
return CompletableFuture.completedFuture(new WebRequestResult());
}
}
IWebRequestHandler handler = new WebHandler();
Workbook.setWebRequestHandler(handler);
IWebRequestHandler currentHandler = Workbook.getWebRequestHandler();
IWebRequestHandler instance, or null if no handler has been set.IWebRequestHandler instance that is used to handle web requests.Use this method to register the application-level handler that workbook features use when a web request handler is required. Typical scenarios include features that need to retrieve remote content, such as the IMAGE() function when the image source is a web URL. Pass null to clear the current handler.
class WebHandler implements IWebRequestHandler {
public CompletableFuture<WebRequestResult> getAsync(String requestUri) {
return CompletableFuture.completedFuture(new WebRequestResult());
}
}
IWebRequestHandler handler = new WebHandler();
Workbook.setWebRequestHandler(handler);
webRequestHandler - The IWebRequestHandler instance to use for web requests, or null to clear the current handler.
IAIModelRequestHandler handler = new IAIModelRequestHandler() {
@Override
public CompletableFuture<AIModelResponse> sendRequestAsync(AIModelRequest request) {
return CompletableFuture.completedFuture(new AIModelResponse(true, "[[\"Accepted\"]]"));
}
};
Workbook.setAIModelRequestHandler(handler);
modelRequestHandler - The handler to process AI model requests, or null to clear the current handler.
IAIModelRequestHandler handler = new IAIModelRequestHandler() {
@Override
public CompletableFuture<AIModelResponse> sendRequestAsync(AIModelRequest request) {
return CompletableFuture.completedFuture(new AIModelResponse(true, "[[\"Accepted\"]]"));
}
};
Workbook.setAIModelRequestHandler(handler);
IAIModelRequestHandler currentHandler = Workbook.getAIModelRequestHandler();
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
String json = workbook.toSjsJson();
SjsOpenOptions openOptions = new SjsOpenOptions();
workbook.fromSjsJson(
new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)),
openOptions
);
fromSjsJson in interface IWorkbookstream - The JSON stream.openOptions - The open options for opening SpreadJS .sjs file.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);
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);
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);
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);
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);
protect in interface IWorkbookpassword - 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();
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();
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();
addDataSource in interface IWorkbookname - 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();
processTemplate in interface IWorkbookUse 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
}
processTemplate in interface IWorkbookcancellationToken - 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.
worksheet.getRange("A1").setValue("Class: {{className}}");
workbook.addDataSource("className", "Class 3");
IWorkbook report = workbook.generateReport();
Object value = report.getWorksheets().get(0).getRange("A1").getValue();
generateReport in interface IWorkbookWorkbook object.
worksheet.getRange("A1").setValue("{{name}}");
workbook.addDataSource("name", "Quarterly Report");
IWorkbook report = workbook.generateReport(worksheet);
Object value = report.getWorksheets().get(0).getRange("A1").getValue();
generateReport in interface IWorkbookworksheets - The worksheets to process.Workbook object that contains the generated report.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();
getResetAdjacentRangeBorder in interface IWorkbooktrue 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();
setResetAdjacentRangeBorder in interface IWorkbookvalue - true if borders of adjacent ranges are reset when setting a border for a range; otherwise, false.key - The license key.SetLicenseKey(String) instead.This method shouldn't be called if your license was purchased from other markets.
licenseFilePath - The file that contains license keyIf 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();
getGraphicsInfo in interface IWorkbookUse 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);
setGraphicsInfo in interface IWorkbookvalue - The graphics information to use for digit-width measurement and related layout calculations. Set to null to use the built-in graphics information.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();
getSelectedSheets in interface IWorkbookIWorksheets collection that represents all selected worksheets in the workbook.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();
String linkName = linkSources.get(0);
getExcelLinkSources in interface IWorkbookUse 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();
updateExcelLinks in interface IWorkbookUse 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();
updateExcelLink in interface IWorkbookname - 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 a linked workbook reference identified by name. To obtain available link names, use getExcelLinkSources().
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();
updateExcelLink in interface IWorkbookname - The name of the Excel link to update. This value should match one of the linked workbook names; null behavior is undefined.sourceWorkbook - The workbook that provides the source data for the specified link.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");
fileName - The path of the workbook file from which to get defined names.INames collection that represents the workbook-specified names.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");
fileStream - The workbook file stream from which to get defined names.INames collection that represents the workbook-specified names.The source is identified by sourceName. It can specify a worksheet, a table, or a range, such as "Sheet1", "Sheet1!Table1", or "Sheet1!A1:C5".
worksheet.getRange("A1:C5").setValue(new Object[][] {
{"Name", "Q1", "Q2"},
{"North", 1200, 1500},
{"South", 900, 1100},
{"East", 1000, 1300},
{"West", 950, 1250}
});
String filePath = java.nio.file.Paths.get("Users", "DefaultApps", "Documents", "input.xlsx").toString();
workbook.save(filePath);
Object[][] data = Workbook.importData(filePath, "Sheet1!A1:C5");
fileName - The path and name of the workbook file. Must be a valid file path.sourceName - The name of the source data. This can be a worksheet name, a table reference, or a range reference; must not be null.null if sourceName cannot be resolved to a supported source.IllegalArgumentException - if fileName is not a valid path.RuntimeException - if an I/O error occurs while opening or reading the file.This method opens the workbook file identified by fileName and imports the data from the range specified by worksheetName, row, column, rowCount, and columnCount.
If the imported range contains a single cell value, the result is still returned as a two-dimensional array with one row and one column.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100},
{"Hello", 200}
});
String filePath = java.nio.file.Paths.get("Users", "DefaultApps", "Documents", "input.xlsx").toString();
workbook.save(filePath);
Object[][] data = Workbook.importData(filePath, "Sheet1", 0, 0, 3, 2);
fileName - The path and name of the workbook file. Must be a valid file path.worksheetName - The name of the worksheet that contains the range to import.row - The first row of the range to import.column - The first column of the range to import.rowCount - The number of rows to import.columnCount - The number of columns to import.IllegalArgumentException - if fileName is not a valid path, or if the specified worksheet does not exist.RuntimeException - if an I/O error occurs while opening or reading the file.The source is identified by sourceName. It can specify a worksheet, a table, or a range, such as "Sheet1", "Sheet1!Table1", or "Sheet1!A1:C5".
If sourceName does not contain '!', this method imports data from the worksheet identified by that name. If sourceName is parsed as a range reference, this method imports the referenced range. If sourceName is parsed as a named item reference, this method imports the referenced table data.
worksheet.getRange("A1:B2").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100}
});
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.save(outputStream, SaveFileFormat.Xlsx);
Object[][] data = Workbook.importData(new ByteArrayInputStream(outputStream.toByteArray()), "Sheet1!A1:B2");
fileStream - The input stream that contains workbook data. Must not be null.sourceName - The name of the source data. This can be a worksheet name, a table reference, or a range reference; must not be null.null if sourceName cannot be resolved to a supported source or the specified worksheet is a chart sheet.IllegalArgumentException - if the specified worksheet does not exist, or if the stream content cannot be parsed for the requested source.This method reads the range identified by worksheetName, row, column, rowCount, and columnCount from the workbook data in fileStream.
If the imported range contains a single cell value, the result is still returned as a two-dimensional array with one row and one column.
worksheet.getRange("A1:B3").setValue(new Object[][] {
{"Name", "Value"},
{"Test", 100},
{"Hello", 200}
});
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.save(outputStream, SaveFileFormat.Xlsx);
Object[][] data = Workbook.importData(
new ByteArrayInputStream(outputStream.toByteArray()), "Sheet1", 0, 0, 3, 2);
fileStream - The input stream that contains workbook data. Must not be null.worksheetName - The name of the worksheet that contains the range to import.row - The zero-based row index of the first row in the range.column - The zero-based column index of the first column in the range.rowCount - The number of rows to import.columnCount - The number of columns to import.IllegalArgumentException - if the specified worksheet does not exist.
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);
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);
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);
ImageType of converted image is 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);
convertBarcodeToPicture in interface IWorkbookImageType.EMF and ImageType.WMF image types.
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);
convertBarcodeToPicture in interface IWorkbookimageType - Specify the ImageType of converted image.UnsupportedOperationException - If convert to ImageType.EMF or ImageType.WMF image type.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();
getShowPivotTableFieldList in interface IWorkbooktrue 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();
setShowPivotTableFieldList in interface IWorkbookvalue - true if the PivotTable field list can be shown; otherwise, false.