[]
        
(Showing Draft Content)

Workbook

Class Workbook

java.lang.Object
com.grapecity.documents.excel.Workbook
All Implemented Interfaces:
IWorkbook

public final class Workbook extends Object implements IWorkbook
Represents a workbook.

This 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);
 
  • Field Details

    • FontsFolderPath

      public static String FontsFolderPath
      Gets or sets the path to the directory that contains font files. These fonts are utilized for rendering and measurement in PDF, HTML, and image export, as well as AutoFit functionality.
      
       Workbook.FontsFolderPath = java.nio.file.Paths.get("Resources", "Fonts").toString();
       String fontsFolderPath = Workbook.FontsFolderPath;
       
    • FontProvider

      public static IFontProvider FontProvider
      Gets or sets the font provider that supplies font files as streams for AutoFit, PDF export, and image export.
  • Constructor Details

    • Workbook

      public Workbook()
      Creates the workbook.
    • Workbook

      public Workbook(WorkbookOptions options)
      Creates the workbook.
      Parameters:
      options - The workbook options.
    • Workbook

      public Workbook(String licenseKey)
      Creates a workbook and applies the specified license.

      Important: For licenses of the Chinese market, use SetLicenseFile or set the license in the GCEXCEL_JAVA_DEPLOY_LICENSE_V7 environment variable instead.

      Parameters:
      licenseKey - The license key.
    • Workbook

      public Workbook(String licenseKey, WorkbookOptions options)
      Creates a workbook and applies the specified license.

      Important: For licenses of the Chinese market, use SetLicenseFile or set the license in the GCEXCEL_JAVA_DEPLOY_LICENSE_V7 environment variable instead.

      Parameters:
      licenseKey - The license key.
      options - The workbook options.
  • Method Details

    • getAllowDynamicArray

      @Deprecated public boolean getAllowDynamicArray()
      Deprecated.
      This method is obsolete. Use IRange.setFormula2(String) to set a dynamic array formula.
      Gets whether dynamic array formulas are allowed for compatibility with 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).

      Specified by:
      getAllowDynamicArray in interface IWorkbook
      Returns:
      true if dynamic array formulas are allowed for compatibility with IRange.setFormula(String); otherwise, false.
    • setAllowDynamicArray

      @Deprecated public void setAllowDynamicArray(boolean value)
      Deprecated.
      This method is obsolete. Use IRange.setFormula2(String) to set a dynamic array formula.
      Sets whether dynamic array formulas are allowed for compatibility with 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).

      Specified by:
      setAllowDynamicArray in interface IWorkbook
      Parameters:
      value - true if dynamic array formulas are allowed for compatibility with IRange.setFormula(String); otherwise, false.
    • getDeferUpdateDirtyState

      public boolean getDeferUpdateDirtyState()
      Gets whether updates to the dirty states of dependent formulas affected by cell value changes are deferred.

      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();
       
      Specified by:
      getDeferUpdateDirtyState in interface IWorkbook
      Returns:
      true if updates to the dirty states of dependent formulas affected by cell value changes are deferred; otherwise, false.
    • setDeferUpdateDirtyState

      public void setDeferUpdateDirtyState(boolean value)
      Sets whether updates to the dirty states of dependent formulas affected by cell value changes are deferred.

      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();
       
      Specified by:
      setDeferUpdateDirtyState in interface IWorkbook
      Parameters:
      value - true if updates to the dirty states of dependent formulas affected by cell value changes are deferred; otherwise, false.
    • getName

      public String getName()
      Gets the name of the workbook.

      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();
       
      Specified by:
      getName in interface IWorkbook
      Returns:
      The name of the workbook.
    • setName

      public void setName(String name)
      Sets the name of the workbook.

      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");
       
      Specified by:
      setName in interface IWorkbook
      Parameters:
      name - The name of the workbook.
    • getFullName

      public String getFullName()
      Gets the workbook name, including its full path.

      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();
       
      Specified by:
      getFullName in interface IWorkbook
      Returns:
      The workbook name including its full path.
    • getPath

      public String getPath()
      Gets the path of the workbook file represented by this workbook object.

      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();
       
      Specified by:
      getPath in interface IWorkbook
      Returns:
      The path of the workbook file represented by this workbook object.
    • setPath

      public void setPath(String path)
      Sets the path of the workbook file represented by this workbook object.

      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();
       
      Specified by:
      setPath in interface IWorkbook
      Parameters:
      path - The path of the workbook file represented by this workbook object.
    • open

      public void open(String fileName)
      Opens a workbook file.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      fileName - The path and name of the workbook file to open. Must not be null.
    • open

      public List<JsonError> open(String fileName, DeserializationOptions deserializationOptions)
      Opens the specified JSON file.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      fileName - The JSON file to open.
      deserializationOptions - The options that control JSON deserialization.
      Returns:
      A list of JsonError objects generated while opening the JSON file.
    • open

      @Deprecated public void open(String fileName, String password)
      Deprecated.
      Opens the specified Excel file with a password.

      This method opens a password-protected workbook from the specified file path.

      Specified by:
      open in interface IWorkbook
      Parameters:
      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.
    • open

      public void open(String fileName, OpenFileFormat fileFormat)
      Opens a file using the specified file format.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      fileName - The file to open.
      fileFormat - The format of the file.
    • open

      public void open(String fileName, OpenOptionsBase options)
      Opens a file with the specified open options.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      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.
    • open

      public final void open(InputStream fileStream)
      Opens the specified Excel file stream.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      fileStream - The stream that contains the Excel file data. Must not be null.
    • open

      @Deprecated public void open(InputStream fileStream, String password)
      Deprecated.
      Opens the specified Excel file stream with a password.

      Use this method to load a password-protected workbook from an InputStream.

      Specified by:
      open in interface IWorkbook
      Parameters:
      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.
    • open

      public void open(InputStream fileStream, OpenFileFormat fileFormat)
      Opens the specified Excel file stream using the specified file format.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      fileStream - The specified file stream.
      fileFormat - The format of the file stream.
    • open

      public void open(InputStream fileStream, OpenOptionsBase options)
      Opens the stream with the specified options.

      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);
       
      Specified by:
      open in interface IWorkbook
      Parameters:
      fileStream - The file stream.
      options - The options used to open the file stream. Possible types:
    • save

      public void save(String fileName)
      Saves the workbook to disk.
      
       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);
       
      Specified by:
      save in interface IWorkbook
      Parameters:
      fileName - The path of the destination file.
    • save

      @Deprecated public void save(String fileName, String password)
      Deprecated.
      Saves the workbook to the specified Excel file with a password.

      Use this method to write the current workbook to disk and apply password protection to the saved file.

      Specified by:
      save in interface IWorkbook
      Parameters:
      fileName - The path of the destination file.
      password - The password used to protect the saved file.
    • save

      public void save(String fileName, SaveOptionsBase options)
      Saves the workbook to a file with the specified save options.

      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);
       
      Specified by:
      save in interface IWorkbook
      Parameters:
      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.
    • save

      public void save(String fileName, SaveFileFormat fileFormat)
      Saves the workbook to the specified file in the specified format.

      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);
       
      Specified by:
      save in interface IWorkbook
      Parameters:
      fileName - The path of the destination file.
      fileFormat - The file format to use when saving the workbook.
    • save

      public void save(OutputStream outputStream)
      Saves the workbook to the specified stream.

      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) {
       }
       
      Specified by:
      save in interface IWorkbook
      Parameters:
      outputStream - The output stream to which the workbook is saved. Must not be null.
    • save

      @Deprecated public void save(OutputStream outputStream, String password)
      Deprecated.
      Saves the workbook to the specified stream.
      Specified by:
      save in interface IWorkbook
      Parameters:
      outputStream - The output stream to which the workbook is saved.
      password - The password of the file.
    • save

      public void save(OutputStream fileStream, SaveOptionsBase options)
      Saves the workbook to a stream with the specified save options.

      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();
       
      Specified by:
      save in interface IWorkbook
      Parameters:
      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.
    • save

      public void save(OutputStream fileStream, SaveFileFormat fileFormat)
      Saves the workbook to the specified stream in the specified file format.

      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
       }
       
      Specified by:
      save in interface IWorkbook
      Parameters:
      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.
    • getAfterSaveEvent

      public Event<EventHandler<EventArgs>> getAfterSaveEvent()
      Occurs after the workbook is saved.
      
       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];
       
      Specified by:
      getAfterSaveEvent in interface IWorkbook
      Returns:
      The event that occurs after the workbook is saved.
    • getBeforeSaveEvent

      public Event<EventHandler<EventArgs>> getBeforeSaveEvent()
      Occurs before 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];
       
      Specified by:
      getBeforeSaveEvent in interface IWorkbook
      Returns:
      The event that occurs before the workbook is saved.
    • getNewSheetEvent

      public Event<EventHandler<SheetEventArgs>> getNewSheetEvent()
      Occurs when a new sheet is created in the workbook.
      
       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];
       
      Specified by:
      getNewSheetEvent in interface IWorkbook
      Returns:
      The event that occurs when a new sheet is created in the workbook.
    • getOpenedEvent

      public Event<EventHandler<EventArgs>> getOpenedEvent()
      Occurs when the workbook is opened.
      
       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];
       
      Specified by:
      getOpenedEvent in interface IWorkbook
      Returns:
      The event that occurs when the workbook is opened.
    • getSheetActivateEvent

      public Event<EventHandler<SheetEventArgs>> getSheetActivateEvent()
      Occurs when a sheet is activated.
      
       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];
       
      Specified by:
      getSheetActivateEvent in interface IWorkbook
      Returns:
      The event that occurs when a sheet is activated.
    • getSheetBeforeDeleteEvent

      public Event<EventHandler<SheetEventArgs>> getSheetBeforeDeleteEvent()
      Occurs before a sheet is deleted.
      
       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];
       
      Specified by:
      getSheetBeforeDeleteEvent in interface IWorkbook
      Returns:
      The event that occurs before a sheet is deleted.
    • getSheetChangeEvent

      public Event<EventHandler<RangeEventArgs>> getSheetChangeEvent()
      Occurs when something changes in the cells of a sheet.
      
       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];
       
      Specified by:
      getSheetChangeEvent in interface IWorkbook
      Returns:
      The event that occurs when something changes in the cells of a sheet.
    • getSheetDeactivateEvent

      public Event<EventHandler<SheetEventArgs>> getSheetDeactivateEvent()
      Occurs when a sheet is deactivated.
      
       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];
       
      Specified by:
      getSheetDeactivateEvent in interface IWorkbook
      Returns:
      The event that occurs when a sheet is deactivated.
    • getSheetSelectionChange

      public Event<EventHandler<RangeEventArgs>> getSheetSelectionChange()
      Occurs when the selection changes on a sheet.
      
       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];
       
      Specified by:
      getSheetSelectionChange in interface IWorkbook
      Returns:
      The event that occurs when the selection changes on a sheet.
    • getOptions

      public IExcelOptions getOptions()
      Gets the workbook options.

      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");
       
      Specified by:
      getOptions in interface IWorkbook
      Returns:
      The IExcelOptions object that contains workbook option settings.
    • getBuiltInDocumentProperties

      public IBuiltInDocumentPropertyCollection getBuiltInDocumentProperties()
      Gets the collection of built-in document properties in the workbook.

      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();
       
      Specified by:
      getBuiltInDocumentProperties in interface IWorkbook
      Returns:
      The collection that represents all built-in document properties of the workbook.
    • getCustomDocumentProperties

      public ICustomDocumentPropertyCollection getCustomDocumentProperties()
      Gets the collection of custom document properties in the workbook.

      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");
       
      Specified by:
      getCustomDocumentProperties in interface IWorkbook
      Returns:
      The collection that represents all custom document properties of the workbook.
    • getCustomXmlParts

      public ICustomXmlPartCollection getCustomXmlParts()
      Gets the collection of Custom XML parts in the workbook.

      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();
       
      Specified by:
      getCustomXmlParts in interface IWorkbook
      Returns:
      The collection that represents all Custom XML parts in the workbook.
    • getCustomViews

      public ICustomViews getCustomViews()
      Gets the custom views of the workbook.

      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();
       
      Specified by:
      getCustomViews in interface IWorkbook
      Returns:
      The ICustomViews collection that contains the workbook's custom views.
    • getWriteProtection

      public WriteProtection getWriteProtection()
      Gets the workbook write protection options.

      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);
       
      Specified by:
      getWriteProtection in interface IWorkbook
      Returns:
      The WriteProtection object for the workbook.
    • getSignatures

      public ISignatureSet getSignatures()
      Gets the collection of digital signatures attached to 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);
       
      Specified by:
      getSignatures in interface IWorkbook
      Returns:
      The collection of digital signatures attached to the workbook.
    • getTagJsonSerializer

      public static IJsonSerializer getTagJsonSerializer()
      Gets the JSON serializer used for tag custom types in JSON import and export.

      Use 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();
       
      Returns:
      The JSON serializer for tag custom types, or null if no serializer has been set.
    • setTagJsonSerializer

      public static void setTagJsonSerializer(IJsonSerializer value)
      Sets the JSON serializer used for tag custom types in JSON import and export.

      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);
       
      Parameters:
      value - The JSON serializer for tag custom types. Specify null to remove the current serializer.
    • getValueJsonSerializer

      public static IJsonSerializer getValueJsonSerializer()
      Gets the JSON serializer used for custom values in from/to JSON operations.

      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();
       
      Returns:
      The current JSON serializer for custom value types, or null if no custom serializer is set.
    • setValueJsonSerializer

      public static void setValueJsonSerializer(IJsonSerializer value)
      Sets the JSON serializer used for custom cell values in JSON import and export.

      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);
       
      Parameters:
      value - The JSON serializer for custom cell values. null clears the current serializer.
    • getAutoParse

      public boolean getAutoParse()
      Gets whether string values are automatically parsed when assigned to a range.

      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();
       
      Specified by:
      getAutoParse in interface IWorkbook
      Returns:
      true if string values are automatically parsed when assigned to a range; otherwise, false.
    • setAutoParse

      public void setAutoParse(boolean value)
      Sets whether string values are automatically parsed when assigned to a range.

      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();
       
      Specified by:
      setAutoParse in interface IWorkbook
      Parameters:
      value - true if string values are automatically parsed when assigned to a range; otherwise, false.
    • getAutoRoundValue

      public boolean getAutoRoundValue()
      Gets whether numeric values are rounded to 15 significant digits when they are retrieved.

      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();
       
      Specified by:
      getAutoRoundValue in interface IWorkbook
      Returns:
      true if numeric values are rounded to 15 significant digits when retrieved; otherwise, false.
    • setAutoRoundValue

      public void setAutoRoundValue(boolean value)
      Sets whether numeric values are rounded to 15 significant digits when they are retrieved.

      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();
       
      Specified by:
      setAutoRoundValue in interface IWorkbook
      Parameters:
      value - true if numeric values are rounded to 15 significant digits when retrieved; otherwise, false.
    • getBookView

      public IWorkbookView getBookView()
      Gets the view settings of this workbook.

      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);
       
      Specified by:
      getBookView in interface IWorkbook
      Returns:
      The IWorkbookView object that represents the view settings of this workbook.
    • getProtectStructure

      public boolean getProtectStructure()
      Gets a value indicating whether the workbook structure is protected.

      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();
       
      Specified by:
      getProtectStructure in interface IWorkbook
      Returns:
      true if the order of the sheets in the workbook is protected; otherwise, false.
    • getProtectWindows

      public boolean getProtectWindows()
      Gets a value indicating whether the workbook windows are protected.

      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();
       
      Specified by:
      getProtectWindows in interface IWorkbook
      Returns:
      true if the workbook windows are protected; otherwise, false.
    • getReferenceStyle

      public ReferenceStyle getReferenceStyle()
      Gets the reference style used by 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]");
       
      Specified by:
      getReferenceStyle in interface IWorkbook
      Returns:
      The current reference style. The returned value is ReferenceStyle.A1 or ReferenceStyle.R1C1.
    • setReferenceStyle

      public void setReferenceStyle(ReferenceStyle value)
      Sets the reference style used for cell references in the workbook.

      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]");
       
      Specified by:
      setReferenceStyle in interface IWorkbook
      Parameters:
      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.
    • getWorksheets

      public IWorksheets getWorksheets()
      Gets the 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");
       
      Specified by:
      getWorksheets in interface IWorkbook
      Returns:
      The IWorksheets collection that represents all worksheets in the workbook.
    • getSheetTabs

      public ISheetTabs getSheetTabs()
      Gets the collection of sheet tabs contained 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();
       }
       
      Specified by:
      getSheetTabs in interface IWorkbook
      Returns:
      An ISheetTabs object that represents the sheet tabs in the workbook.
    • getActiveSheet

      public IWorksheet getActiveSheet()
      Gets the active worksheet 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();
       
      Specified by:
      getActiveSheet in interface IWorkbook
      Returns:
      The active IWorksheet, or null if no worksheet is active.
    • getTheme

      public ITheme getTheme()
      Gets the theme associated with the 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();
       
      Specified by:
      getTheme in interface IWorkbook
      Returns:
      The ITheme instance associated with the workbook.
    • setTheme

      public void setTheme(ITheme value)
      Sets the theme applied to the current 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();
       
      Specified by:
      setTheme in interface IWorkbook
      Parameters:
      value - The theme to apply to the workbook. Must not be null.
      Throws:
      IllegalArgumentException - if value is null.
    • getIconSets

      public IIconSets getIconSets()
      Gets the collection of icon sets available in the workbook.

      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();
       
      Specified by:
      getIconSets in interface IWorkbook
      Returns:
      The collection of icon sets available in the workbook.
    • getDefaultTableStyle

      public String getDefaultTableStyle()
      Gets the table style name applied by default to newly created tables in the workbook.

      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();
       
      Specified by:
      getDefaultTableStyle in interface IWorkbook
      Returns:
      The name of the default table style.
    • setDefaultTableStyle

      public void setDefaultTableStyle(String value)
      Sets the table style name applied by default to newly created tables in the workbook.

      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();
       
      Specified by:
      setDefaultTableStyle in interface IWorkbook
      Parameters:
      value - The name of the default table style.
    • getCulture

      public Locale getCulture()
      Gets the culture information of the workbook.

      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();
       
      Specified by:
      getCulture in interface IWorkbook
      Returns:
      The culture information of the workbook.
    • setCulture

      public void setCulture(Locale value)
      Sets the culture for the workbook.

      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();
       
      Specified by:
      setCulture in interface IWorkbook
      Parameters:
      value - The locale to apply to the workbook. Use a locale that includes both language and country or region.
      API Note:
      The culture is init-only. It must be set in the initialization code of the workbook instance.
    • getEnableCalculation

      public boolean getEnableCalculation()
      Gets whether the calculation engine is enabled 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();
       
      Specified by:
      getEnableCalculation in interface IWorkbook
      Returns:
      true if the calculation engine is enabled; otherwise, false.
    • setEnableCalculation

      public void setEnableCalculation(boolean value)
      Sets whether the calculation engine is enabled 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();
       
      Specified by:
      setEnableCalculation in interface IWorkbook
      Parameters:
      value - true if the calculation engine is enabled; otherwise, false.
    • AddCustomFunction

      public static void AddCustomFunction(CustomFunction func)
      Add custom function into the function set.
      
       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)");
       
      Parameters:
      func - the custom function instance.
    • AddCustomFunction

      public static void AddCustomFunction(CustomFunction func, boolean canOverride)
      Add custom function into the function set.
      
       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)");
       
      Parameters:
      func - the custom function instance.
      canOverride - override the exist function.
    • getPivotCaches

      public IPivotCaches getPivotCaches()
      Gets the 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"));
       
      Specified by:
      getPivotCaches in interface IWorkbook
      Returns:
      The IPivotCaches collection for the workbook.
    • getSlicerCaches

      public ISlicerCaches getSlicerCaches()
      Gets the 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");
       
      Specified by:
      getSlicerCaches in interface IWorkbook
      Returns:
      The ISlicerCaches collection associated with the workbook.
    • getUsedFonts

      public List<FontInfo> getUsedFonts()
      Gets all font information used in 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();
       
      Specified by:
      getUsedFonts in interface IWorkbook
      Returns:
      A list of FontInfo objects that represent the fonts used in the workbook.
    • calculate

      public void calculate()
      Calculates formulas in the workbook as needed.
      
       worksheet.getRange("A1").setValue(100);
       worksheet.getRange("B1").setFormula("=A1*2");
       workbook.calculate();
       Object value = worksheet.getRange("B1").getValue();
       
      Specified by:
      calculate in interface IWorkbook
    • dirty

      public void dirty()
      Marks all formulas in the workbook as dirty so they are recalculated the next time calculation runs.

      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();
       
      Specified by:
      dirty in interface IWorkbook
    • getStyles

      public IStyleCollection getStyles()
      Gets the collection of styles in the current workbook.

      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);
       
      Specified by:
      getStyles in interface IWorkbook
      Returns:
      The IStyleCollection that represents all styles in the current workbook.
    • getTableStyles

      public ITableStyleCollection getTableStyles()
      Gets the 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);
       
      Specified by:
      getTableStyles in interface IWorkbook
      Returns:
      The ITableStyleCollection that represents the table styles in the current workbook.
    • getNames

      public INames getNames()
      Gets the collection of workbook-defined 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");
       
      Specified by:
      getNames in interface IWorkbook
      Returns:
      The INames collection that represents the workbook-specified names.
    • getAuthor

      public String getAuthor()
      Gets the author of the workbook.

      Use setAuthor(String) to assign the author metadata before retrieving it.

      
       workbook.setAuthor("Author");
       String author = workbook.getAuthor();
       
      Specified by:
      getAuthor in interface IWorkbook
      Returns:
      The author of the workbook.
    • setAuthor

      public void setAuthor(String value)
      Sets the author of the workbook.
      
       workbook.setAuthor("Author");
       
      Specified by:
      setAuthor in interface IWorkbook
      Parameters:
      value - The author of the workbook.
    • isEncryptedFile

      public boolean isEncryptedFile(String fileName)
      Determines whether the specified file is password protected.

      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);
       
      Specified by:
      isEncryptedFile in interface IWorkbook
      Parameters:
      fileName - The name or path of the file to check. Must not be null.
      Returns:
      true if the specified file is password protected; otherwise, false.
    • isEncryptedFile

      public boolean isEncryptedFile(InputStream fileStream)
      Determines whether the specified file stream is password protected.

      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);
       
      Specified by:
      isEncryptedFile in interface IWorkbook
      Parameters:
      fileStream - The input file stream to inspect.
      Returns:
      true if the specified file stream is password protected; otherwise, false.
    • toJson

      public String toJson()
      Generates a JSON string from the workbook.

      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();
       
      Specified by:
      toJson in interface IWorkbook
      Returns:
      The JSON string that represents the current workbook.
    • toJson

      public String toJson(SerializationOptions serializationOptions)
      Generates a JSON string from the workbook using the specified serialization options.

      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);
       
      Specified by:
      toJson in interface IWorkbook
      Parameters:
      serializationOptions - The SerializationOptions object that specifies how the workbook is serialized to JSON.
      Returns:
      The JSON string that represents the workbook.
    • toJson

      public void toJson(OutputStream stream)
      Generates a JSON stream from the workbook.

      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);
       
      Specified by:
      toJson in interface IWorkbook
      Parameters:
      stream - The output stream that receives the generated JSON data.
    • toJson

      public void toJson(OutputStream stream, SerializationOptions serializationOptions)
      Generates a JSON stream from the workbook.

      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);
       
      Specified by:
      toJson in interface IWorkbook
      Parameters:
      stream - The output stream that receives the generated JSON content.
      serializationOptions - The SerializationOptions object that specifies how the workbook is serialized to JSON.
    • fromJson

      public List<JsonError> fromJson(String json)
      Loads workbook content from a SpreadJS JSON (SSJSON) string into this workbook.

      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);
       
      Specified by:
      fromJson in interface IWorkbook
      Parameters:
      json - The SpreadJS JSON (SSJSON) string to load into this workbook. Must not be null.
      Returns:
      A list of JsonError objects found during deserialization.
    • fromJson

      public List<JsonError> fromJson(String json, DeserializationOptions deserializationOptions)
      Loads workbook content from a SpreadJS JSON (SSJSON) string into this workbook.

      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);
       
      Specified by:
      fromJson in interface IWorkbook
      Parameters:
      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.
      Returns:
      A list of JsonError objects found during deserialization.
    • fromJson

      public List<JsonError> fromJson(InputStream stream)
      Loads workbook content from a SpreadJS JSON (SSJSON) stream into this workbook.

      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())
       );
       
      Specified by:
      fromJson in interface IWorkbook
      Parameters:
      stream - The input stream that provides the SpreadJS JSON (SSJSON) content to load. Must not be null.
      Returns:
      A list of JsonError objects found during deserialization.
    • fromJson

      public List<JsonError> fromJson(InputStream stream, DeserializationOptions deserializationOptions)
      Loads workbook content from a SpreadJS JSON (SSJSON) stream into this workbook.

      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
       );
       
      Specified by:
      fromJson in interface IWorkbook
      Parameters:
      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.
      Returns:
      A list of JsonError objects found during deserialization.
    • fromSjsJson

      public void fromSjsJson(String json)
      Generates a workbook from a JSON string containing the contents of .sjs file format.
      
       worksheet.getRange("A1:B2").setValue(new Object[][] {
           {"Name", "Value"},
           {"Test", 100}
       });
       String json = workbook.toSjsJson();
       workbook.fromSjsJson(json);
       
      Specified by:
      fromSjsJson in interface IWorkbook
      Parameters:
      json - The JSON string.
    • fromSjsJson

      public void fromSjsJson(String json, SjsOpenOptions openOptions)
      Generates a workbook from a JSON string containing the contents of .sjs file format.
      
       worksheet.getRange("A1:B2").setValue(new Object[][] {
           {"Name", "Value"},
           {"Test", 100}
       });
       String json = workbook.toSjsJson();
       SjsOpenOptions openOptions = new SjsOpenOptions();
       workbook.fromSjsJson(json, openOptions);
       
      Specified by:
      fromSjsJson in interface IWorkbook
      Parameters:
      json - The JSON string.
      openOptions - The open options for opening SpreadJS .sjs file.
    • fromSjsJson

      public void fromSjsJson(InputStream stream)
      Generates a workbook from a JSON stream containing the contents of .sjs file format.
      
       worksheet.getRange("A1:B2").setValue(new Object[][] {
           {"Name", "Value"},
           {"Test", 100}
       });
       String json = workbook.toSjsJson();
       workbook.fromSjsJson(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
       
      Specified by:
      fromSjsJson in interface IWorkbook
      Parameters:
      stream - The JSON stream.
    • waitForCalculationToFinish

      public void waitForCalculationToFinish()
      Waits for all calculations in the workbook to finish.

      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();
       
      Specified by:
      waitForCalculationToFinish in interface IWorkbook
    • getWebRequestHandler

      public static IWebRequestHandler getWebRequestHandler()
      Gets the singleton IWebRequestHandler 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();
       
      Returns:
      The singleton IWebRequestHandler instance, or null if no handler has been set.
    • setWebRequestHandler

      public static void setWebRequestHandler(IWebRequestHandler webRequestHandler)
      Sets the global 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);
       
      Parameters:
      webRequestHandler - The IWebRequestHandler instance to use for web requests, or null to clear the current handler.
    • setAIModelRequestHandler

      public static void setAIModelRequestHandler(IAIModelRequestHandler modelRequestHandler)
      Sets the global AI model request handler for processing AI-related operations.
      
       IAIModelRequestHandler handler = new IAIModelRequestHandler() {
           @Override
           public CompletableFuture<AIModelResponse> sendRequestAsync(AIModelRequest request) {
               return CompletableFuture.completedFuture(new AIModelResponse(true, "[[\"Accepted\"]]"));
           }
       };
       Workbook.setAIModelRequestHandler(handler);
       
      Parameters:
      modelRequestHandler - The handler to process AI model requests, or null to clear the current handler.
    • getAIModelRequestHandler

      public static IAIModelRequestHandler getAIModelRequestHandler()
      Gets the global AI model request handler for processing AI-related operations.
      
       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();
       
      Returns:
      The handler to process AI model requests, or null if no handler is set.
    • fromSjsJson

      public void fromSjsJson(InputStream stream, SjsOpenOptions openOptions)
      Generates a workbook from a JSON stream containing the contents of .sjs file format.
      
       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
       );
       
      Specified by:
      fromSjsJson in interface IWorkbook
      Parameters:
      stream - The JSON stream.
      openOptions - The open options for opening SpreadJS .sjs file.
    • protect

      public void protect()
      Protects the workbook structure without a password.

      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();
       
      Specified by:
      protect in interface IWorkbook
    • protect

      public void protect(boolean structure)
      Protects a workbook so that it cannot be modified.

      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);
       
      Specified by:
      protect in interface IWorkbook
      Parameters:
      structure - true to protect the workbook structure; otherwise, false.
    • protect

      public void protect(boolean structure, boolean windows)
      Protects the workbook from modification based on the specified structure and window settings.

      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);
       
      Specified by:
      protect in interface IWorkbook
      Parameters:
      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.
    • protect

      public void protect(String password)
      Protects the workbook with a password so that it cannot be modified.

      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);
       
      Specified by:
      protect in interface IWorkbook
      Parameters:
      password - The password used to protect the workbook. If null or empty, the workbook is still protected without a password.
    • protect

      public void protect(String password, boolean structure)
      Protects the workbook so that it cannot be modified.

      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);
       
      Specified by:
      protect in interface IWorkbook
      Parameters:
      password - The password used to protect the workbook.
      structure - true to protect the workbook structure; otherwise, false.
    • protect

      public void protect(String password, boolean structure, boolean windows)
      Protects a workbook so that it cannot be modified.

      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);
       
      Specified by:
      protect in interface IWorkbook
      Parameters:
      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.
    • unprotect

      public void unprotect()
      Removes protection from the workbook.

      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();
       
      Specified by:
      unprotect in interface IWorkbook
    • unprotect

      public void unprotect(String password)
      Removes protection from the workbook.

      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();
       
      Specified by:
      unprotect in interface IWorkbook
      Parameters:
      password - The password used to unprotect the workbook.
    • addDataSource

      public void addDataSource(String name, Object dataSource)
      Adds a named data source for template processing.

      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();
       
      Specified by:
      addDataSource in interface IWorkbook
      Parameters:
      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.
    • processTemplate

      public void processTemplate()
      Processes the workbook as a template by evaluating template fields and replacing them with data from the workbook's data sources.

      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();
       
      Specified by:
      processTemplate in interface IWorkbook
    • processTemplate

      public void processTemplate(CancellationToken cancellationToken)
      Processes the workbook as a template and observes cancellation requests through the specified cancellation token.

      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
       }
       
      Specified by:
      processTemplate in interface IWorkbook
      Parameters:
      cancellationToken - A token used to monitor cancellation requests. Pass null if cancellation is not required.
      Throws:
      CancellationException - if the specified CancellationToken is canceled while template processing is in progress.
      API Note:
      The caller must decide whether to keep the partially processed workbook or restore the previous state. If restoration is required, serialize the workbook before calling this method and deserialize it after the operation is canceled.
    • generateReport

      public IWorkbook generateReport()
      Process the template and return the instance of report workbook.
      
       worksheet.getRange("A1").setValue("Class: {{className}}");
       workbook.addDataSource("className", "Class 3");
       IWorkbook report = workbook.generateReport();
       Object value = report.getWorksheets().get(0).getRange("A1").getValue();
       
      Specified by:
      generateReport in interface IWorkbook
      Returns:
      The new Workbook object.
    • generateReport

      public IWorkbook generateReport(IWorksheet... worksheets)
      Processes the template and returns a new report workbook that includes only the specified 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();
       
      Specified by:
      generateReport in interface IWorkbook
      Parameters:
      worksheets - The worksheets to process.
      Returns:
      A new Workbook object that contains the generated report.
    • getResetAdjacentRangeBorder

      public boolean getResetAdjacentRangeBorder()
      Gets whether adjacent range borders are reset when a border is applied to a range.

      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();
       
      Specified by:
      getResetAdjacentRangeBorder in interface IWorkbook
      Returns:
      true if borders of adjacent ranges are reset when setting a border for a range; otherwise, false.
    • setResetAdjacentRangeBorder

      public void setResetAdjacentRangeBorder(boolean value)
      Sets whether adjacent range borders are reset when a border is applied to a range.

      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();
       
      Specified by:
      setResetAdjacentRangeBorder in interface IWorkbook
      Parameters:
      value - true if borders of adjacent ranges are reset when setting a border for a range; otherwise, false.
    • SetLicenseKey

      public static void SetLicenseKey(String key)
      Sets license for all workbook instances.
      Parameters:
      key - The license key.
    • SetLicenseFile

      @Deprecated public static void SetLicenseFile(String licenseFilePath)
      Deprecated.
      This method has been deprecated since version 9.0. Use SetLicenseKey(String) instead.
      For licenses of the Chinese market, apply deployment license or unlimited dev license from file.

      This method shouldn't be called if your license was purchased from other markets.

      Parameters:
      licenseFilePath - The file that contains license key
    • getGraphicsInfo

      public final IGraphicsInfo getGraphicsInfo()
      Gets the graphics information used by the workbook.

      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();
       
      Specified by:
      getGraphicsInfo in interface IWorkbook
      Returns:
      The graphics information used by the workbook.
    • setGraphicsInfo

      public final void setGraphicsInfo(IGraphicsInfo value)
      Sets the graphics information used by the workbook.

      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);
       
      Specified by:
      setGraphicsInfo in interface IWorkbook
      Parameters:
      value - The graphics information to use for digit-width measurement and related layout calculations. Set to null to use the built-in graphics information.
    • getSelectedSheets

      public final IWorksheets getSelectedSheets()
      Gets the collection of selected worksheets in the workbook.

      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();
       
      Specified by:
      getSelectedSheets in interface IWorkbook
      Returns:
      An IWorksheets collection that represents all selected worksheets in the workbook.
    • getExcelLinkSources

      public List<String> getExcelLinkSources()
      Gets the names of the linked Excel documents 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);
       
      Specified by:
      getExcelLinkSources in interface IWorkbook
      Returns:
      A list of linked Excel document names.
    • updateExcelLinks

      public void updateExcelLinks()
      Updates all Excel links in the workbook.

      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();
       
      Specified by:
      updateExcelLinks in interface IWorkbook
    • updateExcelLink

      public void updateExcelLink(String name)
      Updates the Excel link with the specified name.

      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();
       
      Specified by:
      updateExcelLink in interface IWorkbook
      Parameters:
      name - The name of the Excel link to update. This value should match one of the linked workbook names; null behavior is undefined.
    • updateExcelLink

      public void updateExcelLink(String name, IWorkbook sourceWorkbook)
      Updates the Excel link with the specified name.

      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();
       
      Specified by:
      updateExcelLink in interface IWorkbook
      Parameters:
      name - 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.
    • getNames

      public static String[] getNames(String fileName)
      Gets the collection of workbook-defined 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");
       
      Parameters:
      fileName - The path of the workbook file from which to get defined names.
      Returns:
      The INames collection that represents the workbook-specified names.
    • getNames

      public static String[] getNames(InputStream fileStream)
      Gets the collection of workbook-defined 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");
       
      Parameters:
      fileStream - The workbook file stream from which to get defined names.
      Returns:
      The INames collection that represents the workbook-specified names.
    • importData

      public static Object[][] importData(String fileName, String sourceName)
      Imports all data from the specified source in a workbook 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".

      
       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");
       
      Parameters:
      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.
      Returns:
      A two-dimensional array that contains the imported data, or null if sourceName cannot be resolved to a supported source.
      Throws:
      IllegalArgumentException - if fileName is not a valid path.
      RuntimeException - if an I/O error occurs while opening or reading the file.
    • importData

      public static Object[][] importData(String fileName, String worksheetName, int row, int column, int rowCount, int columnCount)
      Imports data from a specified range in a workbook 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);
       
      Parameters:
      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.
      Returns:
      A two-dimensional array that contains the imported data.
      Throws:
      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.
    • importData

      public static Object[][] importData(InputStream fileStream, String sourceName)
      Imports all data from the specified source in a workbook stream.

      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");
       
      Parameters:
      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.
      Returns:
      A two-dimensional array that contains the imported data, or null if sourceName cannot be resolved to a supported source or the specified worksheet is a chart sheet.
      Throws:
      IllegalArgumentException - if the specified worksheet does not exist, or if the stream content cannot be parsed for the requested source.
    • importData

      public static Object[][] importData(InputStream fileStream, String worksheetName, int row, int column, int rowCount, int columnCount)
      Imports data from a specified range in a workbook stream.

      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);
       
      Parameters:
      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.
      Returns:
      A two-dimensional array that contains the imported data.
      Throws:
      IllegalArgumentException - if the specified worksheet does not exist.
    • toSjsJson

      public void toSjsJson(OutputStream stream)
      Integrates all JSON files from the SpreadJS .sjs file into a single string, then put the string into the stream.
      
       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);
       
      Specified by:
      toSjsJson in interface IWorkbook
      Parameters:
      stream - The specified file stream.
    • toSjsJson

      public void toSjsJson(OutputStream stream, SjsSaveOptions options)
      Integrates all JSON files from the SpreadJS .sjs file into a single string, then put the string into the stream.
      
       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);
       
      Specified by:
      toSjsJson in interface IWorkbook
      Parameters:
      stream - The specified file stream.
      options - Option for opening SpreadJS .sjs file.
    • toSjsJson

      public String toSjsJson()
      Generates a single JSON payload that represents the workbook in SpreadJS .sjs format.
      
       worksheet.getRange("A1:B2").setValue(new Object[][] {
           {"Name", "Value"},
           {"Test", 100}
       });
       String sjsJson = workbook.toSjsJson();
       
      Specified by:
      toSjsJson in interface IWorkbook
      Returns:
      A JSON string that contains the workbook content in SpreadJS .sjs format.
    • toSjsJson

      public String toSjsJson(SjsSaveOptions options)
      Generates a single JSON payload that represents the workbook in SpreadJS .sjs format, using the specified save options.
      
       worksheet.getRange("A1:B2").setValue(new Object[][] {
           {"Name", "Value"},
           {"Test", 100}
       });
       SjsSaveOptions options = new SjsSaveOptions();
       options.setIncludeEmptyRegionCells(false);
       String sjsJson = workbook.toSjsJson(options);
       
      Specified by:
      toSjsJson in interface IWorkbook
      Parameters:
      options - The save options used to generate the SJS JSON content.
      Returns:
      A JSON string that contains the workbook content in SpreadJS .sjs format.
    • convertBarcodeToPicture

      public void convertBarcodeToPicture()
      Convert the calculated barcodes to pictures and place them in their respective positions.
      The original barcode formulas will be cleared.
      The 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);
       
      Specified by:
      convertBarcodeToPicture in interface IWorkbook
    • convertBarcodeToPicture

      public void convertBarcodeToPicture(ImageType imageType)
      Convert the calculated barcodes to pictures and place them in their respective positions.
      The original barcode formulas will be cleared.
      Not support ImageType.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);
       
      Specified by:
      convertBarcodeToPicture in interface IWorkbook
      Parameters:
      imageType - Specify the ImageType of converted image.
      Throws:
      UnsupportedOperationException - If convert to ImageType.EMF or ImageType.WMF image type.
    • getShowPivotTableFieldList

      public boolean getShowPivotTableFieldList()
      Gets a value indicating whether the PivotTable field list can be shown.

      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();
       
      Specified by:
      getShowPivotTableFieldList in interface IWorkbook
      Returns:
      true if the PivotTable field list can be shown; otherwise, false.
    • setShowPivotTableFieldList

      public void setShowPivotTableFieldList(boolean value)
      Sets a value indicating whether the PivotTable field list can be shown.

      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();
       
      Specified by:
      setShowPivotTableFieldList in interface IWorkbook
      Parameters:
      value - true if the PivotTable field list can be shown; otherwise, false.
    • clone

      public Workbook clone()
      Clones the current workbook and returns a new instance of the workbook.
      Specified by:
      clone in interface IWorkbook
      Overrides:
      clone in class Object
      Returns:
      A new workbook instance that is an exact copy of the current workbook.