Class Workbook
- All Implemented Interfaces:
AutoCloseable
Start with create() for a new workbook or open(Path)
for a file. A new workbook has no sheets; add one with
createSheet(String).
try (Workbook wb = Workbook.create()) {
Sheet sheet = wb.createSheet("Data");
sheet.cell(0, 0).setValue(CellValue.text("Total"));
sheet.cell(0, 1).setValue(CellValue.number(42));
sheet.cell(1, 1).setFormula("=B1*2");
wb.save(Path.of("out.xlsx"));
}
try (Workbook wb = Workbook.open(Path.of("out.xlsx"))) {
CellValue result = wb.sheet("Data").cell(1, 1).value(); // Number[value=84.0]
}
Sheet, Range and Cell are lightweight views that
hold no native resource. Close the workbook with try-with-resources or
close() to free its memory. After close, every method of the
workbook and of its views throws IllegalStateException.
Calculation is automatic, as in Excel. Opening keeps the results the
file carries, and every write recalculates its dependents, so reads and
saved files are current. Only in CalcMode.MANUAL do results wait for
recalculate().
Threads
Use one workbook from one thread at a time. Separate workbooks run in
parallel on separate threads. A call made while another call on the same
workbook is still running, from a second thread or from a user-defined
function, throws AxyraException ("workbook is already in use"). It
does not wait. See the package documentation.
Licensing
Licensing is process-wide; install a key with setLicense(byte[])
and read the state with licenseStatus() or License. A
release build enforces the license at all times. Without a license in force
it runs as an evaluation copy:
- Saved files carry an evaluation mark on every sheet, and a workbook file gets an extra first tab, "Axyra Evaluation Copy". Every PDF and image page carries an evaluation banner. No data is dropped, and the in-memory workbook is not changed.
- Each open, save, render and sign counts as one file operation. After
100 file operations, or 72 hours after the first one, these calls
throw
AxyraExceptionuntil the process restarts. - The first counted operation prints one evaluation notice to standard error.
A development build applies these rules only when the
axyra.license.enforce=1 system property or the
AXYRA_LICENSE_ENFORCE=1 environment variable is set. See
LicenseInfo for the state a key puts in force.
-
Method Summary
Modifier and TypeMethodDescriptionThe active sheet: the tab Excel shows when the file opens.intaddChartSheet(String name, Chart chart) Append a chart-sheet tab namednamehostingchart— a dedicated full-page chart tab (ECMA-376 §18.3.1.12chartsheet), as opposed to a chart floating on a worksheet viaSheet.addChart(io.keikai.axyra.sheets.content.Chart).voidAdds a workbook-scoped defined name, or replaces one.voidAdds a defined name scoped toscope, or replaces one; the rules ofaddName(String, String)apply.intaddOleObject(String name, String progId, byte[] data) Embeds an OLE object (raw bytes, optional ProgID) at workbook level.voidAdds a slicer descriptor namednamebound tosource, a table or pivot field name.voidaddSlicer(String name, String source, String pivotTable, int sheetIndex, int row, int col, int endRow, int endCol) Adds a slicer that displays in Excel: bound to the pivot fieldsourceofpivotTable, anchored on sheetsheetIndexwith a two-cell drawing anchor spanningrow/coltoendRow/endCol(0-based, exclusive-corner semantics of ECMA-376 §20.5.2.32).voidaddSlicer(String name, String source, String pivotTable, String cacheName, int sheetIndex, int row, int col, int endRow, int endCol) Adds a slicer that displays in Excel, keeping an explicit backing cache name.voidaddTimeline(String name, String source, String dateField) Adds a timeline descriptor (a date slicer) that filters pivot tablesourceoverdateField.voidaddTimeline(String name, String source, String dateField, int sheetIndex, int row, int col, int endRow, int endCol) Adds a timeline that displays in Excel: it filters pivot tablesourceoverdateField, anchored on sheetsheetIndexspanningrow/coltoendRow/endCol.allDependents(Sheet sheet, int row, int column) Every cell that depends on a cell directly or through other cells; the cell itself is not included.The authoring application (ApplicationofdocProps/app.xml), ornullwhen none is set.The authoring application version (AppVersion), ornull.author()The author (OOXMLdc:creator), ornullwhen none is set.calcMode()The workbook calculation mode: the one the file carries, orAUTOMATICfor a new workbook.category()The document category (cp:category), ornull.chartSheetChart(int index) A live view of the chart hosted by the chart sheet atindex— the same read-back/edit viewSheet.chart(int)returns.intNumber of chart-sheet tabs in the workbook, authored and imported.chartSheetName(int index) The tab name of the chart sheet atindex(0-based position among the chart sheets, in tab order).voidclose()Frees the native workbook and its registered user-defined functions.voidAppends a deep copy of every sheet (visible and hidden) of each source workbook, in argument order, auto-suffixing colliding names.comments()The comments (OOXMLdc:description), ornullwhen none are set.company()The company (CompanyofdocProps/app.xml), ornull.The data connections defined in this workbook (Power Query and other), read fromxl/connections.xml, orxl/connections.binfor an.xlsbfile.The content status (cp:contentStatus, e.g.Appends a deep copy ofsourceundernewNameand returns a view of the copy.copySheetFrom(Workbook source, int sheetIndex) Appends a deep copy of sheetsheetIndex(0-based) of another workbook and returns a view of the copy.copySheetFrom(Workbook source, int sheetIndex, String newName) Appends a deep copy of sheetsheetIndex(0-based) of another workbook undernewNameand returns a view of the copy.static Workbookcreate()Creates a new empty workbook with no sheets, on the sparse storage backend (the general-purpose default).static WorkbookCreates a new empty workbook, with no sheets, on the columnar storage backend.created()The creation timestamp (dcterms:created, W3CDTF), ornull.createSheet(String name) Appends a new empty worksheet after the last tab and returns a view of it.The custom document properties, in file order — an immutable read view (empty list when the workbook has none).The workbook's CUSTOM table-style definitions (<tableStyles>+ their differential-format payloads) plus the default table/pivot style names, as one opaque JSON value object — ornullwhen the workbook defines none.booleandate1904()Whether the workbook uses the 1904 date system (ECMA-376 Part 1 §18.2.28<workbookPr date1904>).The workbook default ("Normal") style — what unstyled cells render with.voiddeleteSheet(int index) Deletes the sheet atindex(0-based).dependents(Sheet sheet, int row, int column) The direct dependents of a cell: the cells whose formulas read it.TheDocSecurityflags ofdocProps/app.xml, ornullwhen the workbook records none.The author-recorded document version (cp:versionofdocProps/core.xml), ornull.Evaluates an ad-hoc formula (leading=optional) in the first sheet's context.Evaluates an ad-hoc formula insheet's context: references without a sheet name read that sheet.intNumber of external workbook references (ECMA-376 §18.14), the size ofexternalLinks().Every external workbook reference — the linked workbooks that formulas such as[Book2]Sheet1!A1resolve against.externalLinkSource(int index) The current source path (primary relationship target) of the external workbook reference atindex(0-based), ornullwhen the index is negative or out of range.The first defined name spelled exactlyname(case-sensitive), in definition order and in any scope, ornullwhen none matches.formulaToA1(String formula, int anchorRow, int anchorColumn) Converts a formula's references from R1C1 back to A1 style, relative to the 1-based(anchorRow, anchorColumn); the rest of this API is 0-based.formulaToR1C1(String formula, int anchorRow, int anchorColumn) Converts a formula's cell references from A1 to R1C1 style, relative to the 1-based(anchorRow, anchorColumn); the rest of this API is 0-based.doubleFinds the value for thechangingcell that makes thetargetcell equaltargetValue(Excel's Goal Seek).booleanhasNamedStyle(String name) Whether a named style is registered undername(case-sensitive).The base URI relative hyperlinks resolve against (HyperlinkBaseofdocProps/app.xml), ornull.TheHyperlinksChangedflag ofdocProps/app.xml, ornullwhen the workbook records none.insertSheet(int index, String name) Inserts a new empty sheet atindex(0..sheetCount inclusive), shifting later sheets right, and return a view of it.booleanWhether the workbook structure is locked.booleanWhether the workbook structure is protected (alias ofisStructureLocked()).booleanWhether the workbook windows are locked (§18.2.29lockWindows).booleanWhether a modify password is stored.keywords()The document keywords (cp:keywords), ornullwhen none are set.language()The document language (dc:language, e.g.The user who last saved the workbook (cp:lastModifiedByofdocProps/core.xml), ornull.When the workbook was last printed (cp:lastPrinted, a W3CDTF timestamp), ornull.static LicenseInfoThe current process-wide license state, checked against the clock now.TheLinksUpToDateflag ofdocProps/app.xml, ornullwhen the workbook records none.locale()The workbook display locale as a BCP-47 tag (default"en-US").manager()The manager (ManagerofdocProps/app.xml), ornull.modified()The last-modified timestamp (dcterms:modified, W3CDTF), ornull.voidmoveSheet(int from, int to) Moves the sheet atfromto positionto, shifting the sheets in between.intNumber of registered named cell styles.names()Every defined name, in definition order, with its scope.The embedded OLE objects in this workbook, in index order: name, ProgID and raw bytes.static Workbookopen(InputStream in, String format) static WorkbookOpens a workbook from a file.static WorkbookOpens a workbook file, decrypting it withpasswordwhen it is encrypted.static WorkbookParses a workbook from bytes.static WorkbookParses a workbook from bytes, decrypting them withpasswordwhen they are encrypted.precedents(Sheet sheet, int row, int column) The direct precedents of a cell: the cells its formula reads, on any sheet.voidprotect(boolean lockStructure) Sets or clears the workbook structure lock, without a password; the window lock is cleared.voidprotect(boolean lockStructure, boolean lockWindows) Sets or clears the workbook structure and window locks, without a password.voidprotectStructure(String password) Lock the workbook structure (ECMA-376 §18.2.29lockStructure) with a password (ISO Write Protection hash, [MS-OFFCRYPTO] §2.4.2.2).voidprotectStructure(String password, boolean lockWindows) Locks the workbook structure and optionally the windows (§18.2.29), with a password as forprotectStructure(String).A range parsed from a sheet-qualified A1 reference — the spelling a defined name stores, e.g.voidRecalculates every formula cell in the workbook, whatever is marked dirty (Excel's Ctrl+Alt+F9).voidRecalculates only the formula cells marked dirty since the last calculation (Excel's F9).voidregisterFunction(String name, UserFunction function) Registers a user-defined function callable from formulas byname.voidregisterNamedStyle(String name, CellStyle style) Registers a reusable named cell style (for example"Good"or"Title").voidregisterTypedFunction(String name, TypedUserFunction function) Register a typed user-defined function callable from formulas byname.booleanremoveChartSheet(int index) Removes the chart sheet atindex(0-based position among the chart sheets).booleanremoveCustomProperty(String name) Removes the custom document propertyname(case-sensitive); returns whether it existed.booleanremoveExternalLink(int index) Removes the external workbook reference atindex(0-based, inexternalLinks()order): drops both the descriptor and the preservedexternalLinkpart so it is not written on save.booleanremoveName(String name) Removes every defined name spelled exactlyname(case-sensitive), in every scope.booleanremoveNamedStyle(String name) Delete a named cell style.booleanremoveOleObject(int index) Removes the embedded OLE object atindex(0-based); returns whether it existed (falsefor a negative index).voidRemoves the write protection and the read-only recommendation, without checking a password.voidrenameSheet(int index, String newName) Renames the sheet atindex(0-based) tonewName, rewriting formula references (OldName!A1becomesNewName!A1) and named ranges.byte[]renderPdf(PdfOptions options) Renders the workbook to PDF bytes honoringoptions(page range, sheet subset, fit override, encryption).voidRenders every sheet to one PDF file, following each sheet's page setup.voidrenderPdf(Path file, PdfOptions options) Renders the workbook to a PDF file honoringoptions; seerenderPdf(io.keikai.axyra.sheets.io.PdfOptions).byte[]renderRangeImage(int sheetIndex, String rangeA1, String format, ImageOptions options) Renders an A1 range (for example"B2:F20") of a sheet toformat, one of the tokensrenderSheetImage(int, String, io.keikai.axyra.sheets.io.ImageOptions)accepts.byte[]renderRangePng(int sheetIndex, String rangeA1, ImageOptions options) Renders an A1 range (for example"B2:F20") of a sheet to PNG bytes.byte[]renderRangeSvg(int sheetIndex, String rangeA1, ImageOptions options) Renders an A1 range of a sheet to SVG bytes; the range acts as forrenderRangePng(int, java.lang.String, io.keikai.axyra.sheets.io.ImageOptions).byte[]renderSheetImage(int sheetIndex, String format, ImageOptions options) Renders one printed page of a sheet (page 1, or the page the options select) toformat:"png","svg","jpeg"or"jpg","gif","bmp","tiff"or"tif".byte[]renderSheetPng(int sheetIndex, ImageOptions options) Renders one printed page of a sheet to PNG bytes: page 1, or the pageImageOptions.page()selects.byte[]renderSheetSvg(int sheetIndex, ImageOptions options) Renders one printed page of a sheet to SVG bytes: page 1, or the page the options select.revision()The revision number (cp:revision), ornull.voidsave(OutputStream out, String format) Serializes the workbook toformat(the tokenssaveBytes(String)accepts) and writes the bytes toout.voidWrites the workbook to a file; the format comes from the extension.voidsave(Path file, SaveOptions options) Writes the workbook with export options; the format comes from the extension, as forsave(Path).byte[]Serialize the workbook to the givenformat(an extension token, with or without the leading dot) and return the bytes — for writing to any sink without touching the filesystem.voidsaveCsv(Path file, CsvOptions options) Writes one sheet as delimited text, choosing which sheet, the separator, and whether numbers are written as display text (whatsave("x.csv")and Excel write) or as stored values for a data feed.voidsaveEncrypted(Path file, String password) Write the workbook withpasswordas its password to open.voidsaveHtml(Path file, HtmlOptions options) Writes the workbook as HTML in the shapeoptionsasks for.TheScaleCropflag ofdocProps/app.xml, ornullwhen the workbook records none.voidsetActiveSheet(int index) Makes the sheet atindex(0-based) the active sheet; it is saved as the tab the file opens on.voidsetApplication(String application) Sets theApplicationname written todocProps/app.xml;nullclears it.voidsetAppVersion(String appVersion) SetsAppVersion; Excel's form isMM.mmmm, for example16.0300.voidSets the author (OOXMLdc:creator);nullclears it.voidsetCalcMode(CalcMode mode) Sets the calculation mode (Excel's Calculation Options).voidsetCategory(String category) Setscp:category;nullclears it.voidsetComments(String comments) Sets the comments (OOXMLdc:description);nullclears them.voidsetCompany(String company) SetsCompany;nullclears it.booleansetConnectionCommand(String name, String command) Sets the command text (for example a SQL statement or an M query reference) of the named connection.booleansetConnectionString(String name, String connectionString) Sets the connection string of the named connection.voidsetContentStatus(String status) Setscp:contentStatus;nullclears it.voidsetCreated(String timestamp) Setsdcterms:created, a W3CDTF timestamp.voidsetCustomProperty(String name, boolean value) Sets (or replaces) the boolean-typed custom document propertyname.voidsetCustomProperty(String name, double value) Sets (or replaces) the number-typed custom document propertyname.voidsetCustomProperty(String name, String value) Sets (or replaces) the text-typed custom document propertyname.voidsetCustomProperty(String name, LocalDate value) Sets (or replaces) the date-typed custom document propertyname.voidsetCustomTableStyles(String json) Installs custom table-style definitions produced bycustomTableStyles().voidsetDate1904(boolean on) Switch the workbook date system.voidsetDefaultFont(CellStyle style) Replace the workbook default ("Normal") font with the font attributes ofstyle(name, size, color, bold, …); its non-font attributes are ignored.voidsetDocSecurity(Integer docSecurity) SetsDocSecurity;nullclears it.voidsetDocumentVersion(String version) Setcp:version;nullclears it.booleansetExternalLinkSource(int index, String newPath) Repoints the external workbook reference atindex(0-based, inexternalLinks()order) to a new source path.voidsetHyperlinkBase(String base) SetsHyperlinkBase;nullclears it.voidsetHyperlinksChanged(Boolean hyperlinksChanged) SetHyperlinksChanged(nullclears it).voidsetIterativeCalc(boolean enabled, int maxIterations, double maxChange) Enables or disables iterative calculation of circular references (Excel's Enable iterative calculation).voidsetKeywords(String keywords) Sets the document keywords (cp:keywords);nullclears them.voidsetLanguage(String language) Setsdc:language, an RFC 5646 language tag such asen-GB.voidsetLastModifiedBy(String user) Setscp:lastModifiedBy;nullclears it.voidsetLastPrinted(String timestamp) Setscp:lastPrinted, a W3CDTF timestamp such as2024-03-01T09:00:00Z.static LicenseInfosetLicense(byte[] token) Install a license token (raw bytes of thepayload.signatureenvelope) and return the resultingLicenseInfo.static LicenseInfosetLicense(byte[] token, LicenseMode mode) Installs a license token, choosing what happens when it does not put a license in force.static LicenseInfoInstalls a license token by reading all ofin; the stream is not closed.static LicenseInfosetLicense(String token) Installs a license token from its text form, encoded as UTF-8.static LicenseInfosetLicense(String token, LicenseMode mode) Installs a license token from its text form, encoded as UTF-8, choosing what happens when it is not in force; seesetLicense(byte[], LicenseMode).voidsetLinksUpToDate(Boolean linksUpToDate) SetLinksUpToDate(nullclears it).voidSet the workbook display locale ("de-DE","ja-JP", ...).voidsetManager(String manager) SetsManager;nullclears it.voidsetModified(String timestamp) Setsdcterms:modified, a W3CDTF timestamp.booleansetOleObjectData(int index, byte[] data) Replaces the embedded OLE object's bytes in place; returns whether the index existed (falsefor a negative index).voidsetRevision(String revision) Setscp:revision.voidsetScaleCrop(Boolean scaleCrop) SetScaleCrop(nullclears it).voidsetSharedDoc(Boolean sharedDoc) SetSharedDoc(nullclears it).booleansetSlicerSelection(String slicerName, String... selectedValues) Replaces a slicer's item selection, as clicking slicer buttons does.booleansetSlicerStyle(String slicerName, String styleName) Sets a slicer's style by name: a built-inSlicerStyleLight1..6/SlicerStyleDark1..6/SlicerStyleOther1..2, or a custom slicer style.voidsetSubject(String subject) Sets the document subject (dc:subject);nullclears it.voidSets the workbook theme (color scheme plus major and minor fonts).booleansetTimelineRange(String timelineName, LocalDate start, LocalDate end) Sets the selected date range of the named timeline.voidSets the document title (dc:title);nullclears it.voidsetWriteProtection(String password) Write-protect the workbook with a modify password (<fileSharing>— ECMA-376 Part 1 §18.2.12): Excel prompts for the password on open and offers read-only otherwise.voidsetWriteProtection(String password, String userName, boolean readOnlyRecommended) Write-protect the workbook:passwordgates editing (null = none),userNamerecords who reserved the file, andreadOnlyRecommendedshows the open-read-only prompt.TheSharedDocflag ofdocProps/app.xml, ornullwhen the workbook records none.sheet(int index) A view of the tab atindex(0-based, in tab order).The sheet with the given name, compared ignoring case as Excel compares sheet names; a sheet whose name matches exactly wins.intNumber of tabs, chart-sheet tabs included (seechartSheetCount()).intsheetPageCount(int sheetIndex) Number of printed pages the sheet paginates to — the valid range forImageOptions.Builder.page(int)and the PDF export's page numbering.sheets()A view of every tab, in tab order, chart-sheet tabs included.byte[]sign(byte[] privateKey, byte[] certificate) Serialize the workbook to an XLSX package and digitally sign it (an OPC package signature per ECMA-376 Part 2 §13: RSA-SHA256, or ECDSA-P256-SHA256 whenprivateKeyis an EC P-256 key), returning the signed file bytes.voidSigns likesign(byte[], byte[])and writes the signed XLSX package tofile, replacing an existing file.The digital-signature validation reports for this workbook's source file, captured when it was opened — an immutable read view, empty for unsigned or programmatically created workbooks.intNumber of slicers in the workbook, the size ofslicers().slicers()Every slicer in the workbook, each joined with its cache so the filtered field and the linked pivot tables travel with it.String[]slicerSelection(String slicerName) The selected item values of a slicer, as text.splitToFiles(Path dir, String pattern) Split this workbook into one single-sheet file per sheet, written todir(created if missing), and return the written paths in sheet order.subject()The document subject (dc:subject), ornullwhen none is set.theme()The workbook theme (color scheme + major/minor fonts), ornullwhen the workbook has no theme.intNumber of timelines in the workbook, the size oftimelines().timelineRange(String timelineName) The selected date range of the named timeline as[start, end], both inclusive, read in this workbook's date system.Every timeline in the workbook, each joined with its cache so the filtered date field, the granularity level and the on-sheet anchor travel with it; seeTimeline.title()The document title (dc:title), ornullwhen none is set.voidClears both workbook locks without checking a password.booleanunprotectStructure(String password) Clear the workbook protection after verifyingpasswordagainst the stored hash.booleanupdateNamedStyle(String name, CellStyle style) Redefine a named cell style and PROPAGATE the change: every cell (and row/column default) currently styled with it is restyled — Excel's "Modify…" on a cell style.The VBA code modules in this macro-enabled workbook (read-only): each module's editor name, kind ("standard"/"class"/"document"), and MS-OVBA-decompressed source text.booleanverifyWritePassword(String password) Verifiespasswordagainst the stored modify-password hash;falsewhen the workbook is not write-protected.The write-protection state, ornullwhen the workbook carries no<fileSharing>element.xmlMaps()The XML map definitions in this workbook (read-only): each map's id, name, root element, schema id, XSD schema text and cell bindings (XmlMap.bindings()), read fromxl/xmlMaps.xml.
-
Method Details
-
create
Creates a new empty workbook with no sheets, on the sparse storage backend (the general-purpose default). Add a sheet withcreateSheet(String)before callingsheet(int); until thensheet(0)throwsIndexOutOfBoundsException. For large, dense numeric data seecreateColumnar(). -
createColumnar
Creates a new empty workbook, with no sheets, on the columnar storage backend. It behaves likecreate()but uses far less memory for large, dense, numeric workbooks (roughly 4.6× smaller at rest at 10M cells), and saves at least as fast. Prefer it when generating big data exports; for small or scattered workbookscreate()is fine. A workbook read from a file uses the reader's own storage, whatever this choice. For a write-once export that never needs the whole workbook in memory, seeStreamWorkbook. -
open
Opens a workbook from a file. Formulas keep the results the file caches. A formula the file stores without a cached result is calculated while the file opens. Nothing else is recalculated until a cell changes orrecalculate()runs.The format comes from the extension, then from the container when the two disagree (a ZIP named
.xlsis read as the package it actually is). Readable:.xlsx/.xlsm/.xltx/.xltm/.xlsb,.xls(BIFF8, including a password-protected one viaopen(Path, String)),.csv/.tsv/.txt,.json,.html/.htm,.ods/.ots/.sxc/.fods, and SpreadsheetML 2003.xml.A format the engine knows but does not read —
.numbers,.pdf, an image — is refused with a message that names it and says why, and an unrecognised extension is refused with a list of what does work. Both arrive asAxyraIoException.An encrypted file needs
open(Path, String). To read from memory or a stream, useopenBytes(byte[], String)oropen(java.io.InputStream, String).- Throws:
AxyraIoException- if the file cannot be read, is encrypted, or has a format the engine does not readAxyraException- if the evaluation limit is reached (see Licensing)
-
open
Opens a workbook file, decrypting it withpasswordwhen it is encrypted. Three encryptions are read: an agile-encrypted OOXML package ([MS-OFFCRYPTO] §2.3.4, whatsaveEncrypted(java.nio.file.Path, java.lang.String)and Excel 2013 and later write), a password-to-open.xls(RC4 CryptoAPI, whatsaveEncrypted(java.nio.file.Path, java.lang.String)writes for.xls), and an encrypted.ods. A password for an unencrypted file is ignored, and the file opens normally. Formats and calculation are as foropen(Path).Error cases (all thrown as
AxyraIoException):- Wrong password — the message starts with "wrong password".
- Legacy OOXML encryption — the Standard and RC4 schemes (EncryptionInfo version 2.x/3.x, Excel 2007-era defaults) are refused; the message names agile encryption as the supported scheme.
- An encrypted file opened with the password-less
open(Path)fails with a message saying a password is required.
- Throws:
NullPointerException- ifpasswordisnullAxyraException- if the evaluation limit is reached (see Licensing)
-
save
Writes the workbook to a file; the format comes from the extension. An existing file is replaced.Workbook containers:
.xlsx/.xlsm/.xltx/.xltm,.xlsb,.xls(BIFF8),.ods, and SpreadsheetML 2003.xml. Text:.csv,.tsv/.txt(tab-separated),.json. Web:.html/.htm, and the web archive.mht/.mhtml.A delimited text file (
.csv,.tsv,.txt) holds one sheet: the active sheet, or the first visible sheet when the active one is hidden. To choose the sheet or the separator, usesaveCsv(java.nio.file.Path, io.keikai.axyra.sheets.io.CsvOptions).Before writing, every pivot table created or changed through this API since its last refresh is refreshed, so the file never holds a stale pivot body.
Rendered output is routed to the renderer rather than to a workbook writer:
.pdfpaginates the whole workbook, and.svg,.png,.jpg/.jpeg,.gif,.bmpand.tif/.tiffeach hold the first printed page of the active sheet. For control over the page range, fit or encryption userenderPdf(Path, io.keikai.axyra.sheets.io.PdfOptions); for image scale, page or gridlines userenderSheetImage(int, String, io.keikai.axyra.sheets.io.ImageOptions).An
.html/.htmname writes two things: the document itself and a<stem>_files/directory beside it holding one page per sheet, the stylesheet, the sheet tab strip and the images — the shape Excel's Save as Web Page produces. For one self-contained file instead, seesaveHtml(Path, io.keikai.axyra.sheets.io.HtmlOptions).A format the engine knows but cannot write, and an extension it does not recognise, are both refused as
AxyraIoException— the first naming the format, the second listing what does work. For export options (formulas as values, no comments) usesave(Path, SaveOptions); for a password to open usesaveEncrypted(Path, String).- Throws:
AxyraIoException- if the format cannot be written or the file cannot be createdAxyraException- if the evaluation limit is reached (see Licensing)
-
saveHtml
Writes the workbook as HTML in the shapeoptionsasks for. By default that is the package: the document plus a<stem>_files/directory, assave(Path)writes for.html. WithsingleFile(true)it is one self-contained document with the images inlined.- Throws:
AxyraIoException- if the file cannot be writtenAxyraException- if the evaluation limit is reached (see Licensing)- See Also:
-
save
Writes the workbook with export options; the format comes from the extension, as forsave(Path). Only the OOXML package formats (.xlsx,.xlsm,.xltx,.xltm) apply the options. Every other format ignores them, soFormulaPolicy.VALUES_ONLYdoes not strip formulas from an.odsor.xlsbfile.ODS keeps a formula as OpenFormula when it has a faithful translation; one that has not (an Excel-only function, a structured or external reference) is written as its value.
- Throws:
IllegalArgumentException- if the options explicitly ask to keep formulas andfile's format cannot carry them (CSV, TSV, TXT), or it is ODS and some formula has no OpenFormula translation (the message names the first) — the file would otherwise hold static values the caller believes are live formulas
-
saveCsv
Writes one sheet as delimited text, choosing which sheet, the separator, and whether numbers are written as display text (whatsave("x.csv")and Excel write) or as stored values for a data feed.With no sheet chosen, it writes the active sheet, or the first visible sheet when the active one is hidden. A sheet name matches ignoring case, as
sheet(String)does. The file is written whatever its extension.- Throws:
IllegalArgumentException- if no sheet has the chosen nameAxyraException- if no sheet has the chosen index, the delimiter is not a single ASCII character other than a quote or a line break, or the evaluation limit is reachedAxyraIoException- if the file cannot be written
-
saveEncrypted
Write the workbook withpasswordas its password to open. The format follows the file extension:.xlsx,.xlsm,.xltx,.xltm: an agile-encrypted XLSX package ([MS-OFFCRYPTO] §2.3.4, AES-256 — what Excel 2013+/365 writes and whatopen(Path, String)reads back), inside an encrypted CFB container..xls: a BIFF8 workbook encrypted with 128-bit RC4 CryptoAPI ([MS-OFFCRYPTO] §2.3.5), the only password to open the legacy format has. RC4 is a weak cipher and the password hash is not iterated, so this keeps the file from being opened casually, not from a determined attacker; a workbook that needs real protection belongs in.xlsx.
This never writes a readable file: a password that cannot protect anything is refused rather than silently ignored.
- Throws:
NullPointerException- ifpasswordisnull— usesave(Path)to write an unencrypted workbookIllegalArgumentException- ifpasswordis empty; Excel refuses an empty password as protection, and writing the package in the clear would leave the caller believing it was protectedAxyraException- if the extension is none of the above (an.ods,.xlsbor.csvcannot carry this encryption)
-
saveBytes
Serialize the workbook to the givenformat(an extension token, with or without the leading dot) and return the bytes — for writing to any sink without touching the filesystem.Accepts every token
save(Path)routes, rendered output included:"pdf"and"svg"come back as bytes here just as they would as a file. The one difference is"html", which has nowhere to put its sidecar directory and so returns a single self-contained document.- Returns:
- a new array holding the whole file
- Throws:
AxyraIoException- if the format is unknown or cannot be writtenAxyraException- if the evaluation limit is reached (see Licensing)
-
save
Serializes the workbook toformat(the tokenssaveBytes(String)accepts) and writes the bytes toout. The whole file is built in memory first.outis neither flushed nor closed.- Throws:
IOException- if writing tooutfails
-
sign
public byte[] sign(byte[] privateKey, byte[] certificate) Serialize the workbook to an XLSX package and digitally sign it (an OPC package signature per ECMA-376 Part 2 §13: RSA-SHA256, or ECDSA-P256-SHA256 whenprivateKeyis an EC P-256 key), returning the signed file bytes.Signing must be the last step. The signature covers the saved bytes; this workbook object is not changed by signing, and any further edit followed by
save(Path)/saveBytes(String)produces an unsigned file — the writer deliberately drops signature parts rather than emit a signature that no longer verifies. Re-sign after every save that must stay signed.Consumers (including
signatures()on reopen) verify the signature against the embedded certificate. Whether the certificate is trusted is a policy decision outside this API.- Parameters:
privateKey- the signing key: PKCS#8 DER or PEM (an RSA PKCS#1 key is also accepted)certificate- the signer's X.509 certificate, DER or PEM, whose public key matchesprivateKey- Returns:
- the signed XLSX package bytes
- Throws:
AxyraIoException- when the key material cannot be parsed or does not match, or signing failsAxyraException- when license enforcement is on and the license in force does not include thesignaturesfeature, or the evaluation limit is reached
-
sign
Signs likesign(byte[], byte[])and writes the signed XLSX package tofile, replacing an existing file.- Throws:
IOException- if the file cannot be written
-
signatures
The digital-signature validation reports for this workbook's source file, captured when it was opened — an immutable read view, empty for unsigned or programmatically created workbooks.Each report tells the signer, algorithm, claimed signing time and a
SignatureInfo.Statusverdict:VALID(all signed digests and the signature verify),INVALID(the content was modified after signing), orUNSUPPORTED(algorithm outside the implemented subset — deliberately not a guess either way). Certificate trust chains, expiry and revocation are not evaluated.The reports describe the file as it was opened; they do not change as the in-memory workbook is edited, and they are not carried into saved output (saving drops signature parts — see
sign(byte[], byte[])). -
openBytes
Parses a workbook from bytes.formatis an extension token such as"xlsx"or".csv", case-insensitive. When the bytes are a different container (a ZIP package given as"xls"), the container decides. Formats, calculation and errors are as foropen(Path). Encrypted bytes needopenBytes(byte[], String, String).- Throws:
AxyraIoException- if the bytes cannot be read in any supported format, or are encryptedAxyraException- if the evaluation limit is reached (see Licensing)
-
openBytes
Parses a workbook from bytes, decrypting them withpasswordwhen they are encrypted.formatis read as inopenBytes(byte[], String). The encryptions read and the error cases are those ofopen(Path, String): a wrong password or a legacy OOXML encryption scheme throwsAxyraIoExceptionwith a distinct message. A password for unencrypted bytes is ignored.- Throws:
NullPointerException- ifpasswordisnull
-
open
Parses a workbook by reading all ofin;formatis read as inopenBytes(byte[], String). The stream is read to its end and not closed.- Throws:
IOException- if readinginfails
-
renderPdf
Renders every sheet to one PDF file, following each sheet's page setup. For a page range, a sheet subset, fit or encryption userenderPdf(Path, io.keikai.axyra.sheets.io.PdfOptions).- Throws:
AxyraIoException- if rendering fails or the file cannot be writtenAxyraException- if the evaluation limit is reached (see Licensing)
-
renderPdf
Renders the workbook to PDF bytes honoringoptions(page range, sheet subset, fit override, encryption).nulloptions render likerenderPdf(Path).- Returns:
- a new array holding the whole PDF
-
renderPdf
Renders the workbook to a PDF file honoringoptions; seerenderPdf(io.keikai.axyra.sheets.io.PdfOptions).- Throws:
AxyraIoException- if the file cannot be written
-
renderSheetPng
Renders one printed page of a sheet to PNG bytes: page 1, or the pageImageOptions.page()selects. An empty sheet renders as one blank page.nulloptions use the defaults: scale 1.0 (96 DPI), the sheet's own gridline setting, page 1.- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- ifsheetIndexis out of range, the page is pastsheetPageCount(int), or the evaluation limit is reached
-
renderSheetSvg
Renders one printed page of a sheet to SVG bytes: page 1, or the page the options select.nulloptions use the defaults; seerenderSheetPng(int, io.keikai.axyra.sheets.io.ImageOptions).- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- ifsheetIndexis out of range, the page does not exist, or the evaluation limit is reached
-
renderSheetImage
Renders one printed page of a sheet (page 1, or the page the options select) toformat:"png","svg","jpeg"or"jpg","gif","bmp","tiff"or"tif". Write the token in lower case.nulloptions use the defaults ofrenderSheetPng(int, io.keikai.axyra.sheets.io.ImageOptions).- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- for an unknown format, asheetIndexout of range, a page that does not exist, or a reached evaluation limit
-
renderRangeImage
Renders an A1 range (for example"B2:F20") of a sheet toformat, one of the tokensrenderSheetImage(int, String, io.keikai.axyra.sheets.io.ImageOptions)accepts. The range replaces the sheet's print area for this export only.- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- for an unknown format, asheetIndexout of range, or a reached evaluation limit
-
renderRangePng
Renders an A1 range (for example"B2:F20") of a sheet to PNG bytes. The range replaces the sheet's print area for this export only, so pagination and gridline rules apply to just that rectangle.- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- ifsheetIndexis out of range or the evaluation limit is reached
-
renderRangeSvg
Renders an A1 range of a sheet to SVG bytes; the range acts as forrenderRangePng(int, java.lang.String, io.keikai.axyra.sheets.io.ImageOptions).- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- ifsheetIndexis out of range or the evaluation limit is reached
-
sheetPageCount
public int sheetPageCount(int sheetIndex) Number of printed pages the sheet paginates to — the valid range forImageOptions.Builder.page(int)and the PDF export's page numbering. An empty sheet reports 0 (its image export still yields one blank page).- Parameters:
sheetIndex- 0-based sheet position- Throws:
AxyraException- ifsheetIndexis out of range
-
setSlicerStyle
Sets a slicer's style by name: a built-inSlicerStyleLight1..6/SlicerStyleDark1..6/SlicerStyleOther1..2, or a custom slicer style. The name is stored as given, without a check.- Returns:
- whether a slicer named
slicerNameexists
-
setSlicerSelection
Replaces a slicer's item selection, as clicking slicer buttons does. Only rows whose value is amongselectedValuespass the filter. An empty array clears the filter (Excel's Clear Filter).Values match the slicer items as text: an integer without a decimal part (
"3", not"3.0"), a boolean asTRUEorFALSE. A value with no item is added as a selected item. A slicer created through this API gets its items from the pivot's source column on the first call.When the selection or the filter it writes into the pivots changes, the pivot tables the slicer filters are refreshed at once, as Excel does. A pivot whose source range cannot be read (an external or Data Model source, or a broken reference) keeps the output it had. A call that changes nothing refreshes nothing.
A slicer names the pivots it filters, not their sheets: a pivot of the same name on another sheet is filtered and refreshed too.
- Returns:
- whether a slicer named
slicerNameexists
-
slicerSelection
The selected item values of a slicer, as text. With no filter every item is selected and listed. An empty array means the slicer has no recorded items, which also means "no filter".- Returns:
- a new array, or
nullif no slicer is namedslicerName
-
addSlicer
Adds a slicer descriptor namednamebound tosource, a table or pivot field name. Its cache is namedSlicer_<source>. It has no on-sheet anchor and no pivot link, so a save does not write it; it still appears inslicers(). For a slicer that displays in Excel, useaddSlicer(String, String, String, int, int, int, int, int). -
addSlicer
public void addSlicer(String name, String source, String pivotTable, int sheetIndex, int row, int col, int endRow, int endCol) Adds a slicer that displays in Excel: bound to the pivot fieldsourceofpivotTable, anchored on sheetsheetIndexwith a two-cell drawing anchor spanningrow/coltoendRow/endCol(0-based, exclusive-corner semantics of ECMA-376 §20.5.2.32). On save the engine writes everything the control needs: the slicer part, the slicer cache, the workbook registration, the worksheet<x14:slicerList>extension and the drawing frame. A workbook built from scratch therefore shows the control in Excel.Negative
row,col,endRoworendColvalues are clamped to 0. The save leaves the slicer out whensheetIndexis negative, whenpivotTableisnull, or when it names no pivot table in the workbook. The slicer still appears inslicers(). The backing cache is namedSlicer_<source>; use theaddSlicer(String, String, String, String, int, int, int, int, int)overload to keep an existing cache name when round-tripping.Reference: ECMA-376 Part 4 §18.10; [MS-XLSX] x14 slicer.
-
addSlicer
public void addSlicer(String name, String source, String pivotTable, String cacheName, int sheetIndex, int row, int col, int endRow, int endCol) Adds a slicer that displays in Excel, keeping an explicit backing cache name. Same asaddSlicer(String, String, String, int, int, int, int, int), but a non-emptycacheNamereplaces the derivedSlicer_<source>name. When rebuilding an existing slicer, pass its cache name: the cache's reserved#N/Adefined name then keeps its spelling, and a round trip adds no defined name.Reference: ECMA-376 Part 4 §18.10; [MS-XLSX] x14 slicer.
-
slicerCount
public int slicerCount()Number of slicers in the workbook, the size ofslicers(). -
slicers
Every slicer in the workbook, each joined with its cache so the filtered field and the linked pivot tables travel with it. Symmetric withaddSlicer(String, String).The descriptor carries the name, caption, filtered field, linked pivots, column count, style and the on-sheet anchor; see
Slicer. It does not carry the item selection; read that withslicerSelection(String).- Returns:
- a new list, a snapshot; empty when the workbook has no slicers
-
addTimeline
Adds a timeline descriptor (a date slicer) that filters pivot tablesourceoverdateField. It has no on-sheet anchor, so a save does not write it; it still appears intimelines(). For a timeline that displays in Excel, useaddTimeline(String, String, String, int, int, int, int, int). -
addTimeline
public void addTimeline(String name, String source, String dateField, int sheetIndex, int row, int col, int endRow, int endCol) Adds a timeline that displays in Excel: it filters pivot tablesourceoverdateField, anchored on sheetsheetIndexspanningrow/coltoendRow/endCol. On save the engine writes the parts the control needs, as foraddSlicer(String, String, String, int, int, int, int, int).Coordinates are 0-based; negative values are clamped to 0. The save leaves the timeline out when
sheetIndexis negative, when no pivot table is namedsource, or when the pivot'sdateFielddoes not hold dates. It still appears intimelines().Reference: [MS-XLSX] x15 timeline / timelineCacheDefinition.
-
timelineCount
public int timelineCount()Number of timelines in the workbook, the size oftimelines(). -
timelines
Every timeline in the workbook, each joined with its cache so the filtered date field, the granularity level and the on-sheet anchor travel with it; seeTimeline. Symmetric withaddTimeline(String, String, String).The descriptor does not carry the selected date range. Read it with
timelineRange(String)and change it withsetTimelineRange(String, java.time.LocalDate, java.time.LocalDate).- Returns:
- a new list, a snapshot; empty when the workbook has no timelines
-
setTimelineRange
Sets the selected date range of the named timeline. The pivot it filters is refreshed at once, as Excel does when a timeline selection changes, and the range is saved with the workbook. That is the pivot the timeline was bound to on its own sheet, not a pivot of the same name on another sheet. The range is inclusive of both endpoints; passnullfor an open-ended bound. Dates convert to serials in this workbook's date system (date1904()).- Returns:
- whether a timeline named
timelineNameexists - Throws:
IllegalArgumentException- ifendis beforestartAxyraException- if the pivot cannot be refreshed because its source range cannot be read; the range is set all the same
-
timelineRange
The selected date range of the named timeline as[start, end], both inclusive, read in this workbook's date system. Either element isnullwhen that side is open.- Returns:
- a new two-element array, or
nullwhen the timeline is unknown or has no active selection
-
externalLinkCount
public int externalLinkCount()Number of external workbook references (ECMA-376 §18.14), the size ofexternalLinks(). -
externalLinks
Every external workbook reference — the linked workbooks that formulas such as[Book2]Sheet1!A1resolve against. The engine serves the values cached at the source's last save; the linked file is never opened. SeeExternalLink.- Returns:
- a new list, a snapshot; empty when the workbook has no links
-
removeExternalLink
public boolean removeExternalLink(int index) Removes the external workbook reference atindex(0-based, inexternalLinks()order): drops both the descriptor and the preservedexternalLinkpart so it is not written on save. Formulas that read the removed link answer#REF!. Links afterindexmove down by one position.- Returns:
trueif a link existed at that index;falsefor a negative or out-of-rangeindex
-
setExternalLinkSource
Repoints the external workbook reference atindex(0-based, inexternalLinks()order) to a new source path. The path is written as given, as a target relative to this file's folder. The link's display name becomes the path's file name. Cached values do not change; the engine never opens the linked file.- Returns:
trueif a link existed at that index;falsefor a negative or out-of-rangeindex
-
externalLinkSource
The current source path (primary relationship target) of the external workbook reference atindex(0-based), ornullwhen the index is negative or out of range. -
setLicense
Install a license token (raw bytes of thepayload.signatureenvelope) and return the resultingLicenseInfo. Licensing is process-global: this affects every workbook in the JVM, not just this one. A bad or tampered token never throws — it degrades toLicenseStatus.EXPIREDorLicenseStatus.INVALID(evaluation mode, fail-open), writes one line naming the cause to standard error, andLicenseInfo.reason()carries it. UsesetLicense(byte[], LicenseMode)withLicenseMode.REQUIREDto fail fast instead.This SDK reports the
javaplatform: a key issued for another platform, a key for another product, and an embedded OEM token (which licenses the host product it ships in, not this SDK) are all refused with a reason. When a key is put in force, its customer console message is printed to standard error once per process.While no license is in force, a release build runs as an evaluation copy: saved and rendered output is watermarked, and after 100 file operations (open, save, render, sign) or 72 hours those calls throw
AxyraException. See Licensing andLicense.- Parameters:
token- the raw bytes of the license token- Returns:
- the license state after the call
-
setLicense
Installs a license token, choosing what happens when it does not put a license in force. UnderLicenseMode.FALLBACK_TO_EVALUATIONit behaves assetLicense(byte[])and prints the cause to standard error.- Returns:
- the license state after the call
- Throws:
AxyraException- underLicenseMode.REQUIREDwhen the token does not put a license in force; the message names the cause
-
setLicense
Installs a license token from its text form, encoded as UTF-8. Same rules assetLicense(byte[]). -
setLicense
Installs a license token from its text form, encoded as UTF-8, choosing what happens when it is not in force; seesetLicense(byte[], LicenseMode). -
setLicense
Installs a license token by reading all ofin; the stream is not closed. Same rules assetLicense(byte[]).- Throws:
IOException- if readinginfails
-
licenseStatus
The current process-wide license state, checked against the clock now. Same asLicense.status(). -
recalculate
public void recalculate()Recalculates every formula cell in the workbook, whatever is marked dirty (Excel's Ctrl+Alt+F9). Nothing calls it for you. For the pending cells only, userecalculateDirty(). -
recalculateDirty
public void recalculateDirty()Recalculates only the formula cells marked dirty since the last calculation (Excel's F9). Under automatic calculation every write already did this, so the call matters mainly inCalcMode.MANUAL. For a full recalculation userecalculate(). -
evaluate
Evaluates an ad-hoc formula (leading=optional) in the first sheet's context. A formula error is aCellValue.Error, not an exception. An array result returns its top-left value. The formula is not stored and no cell changes. For another sheet's context useevaluate(String, Sheet).- Returns:
- the result
-
evaluate
Evaluates an ad-hoc formula insheet's context: references without a sheet name read that sheet. Results are as forevaluate(String).- Throws:
IllegalArgumentException- ifsheetbelongs to another workbook
-
calcMode
The workbook calculation mode: the one the file carries, orAUTOMATICfor a new workbook. -
setCalcMode
Sets the calculation mode (Excel's Calculation Options). InMANUAL, a write only marks its dependents dirty, and reading a dirty formula returns its last result untilrecalculate()orrecalculateDirty()runs. Switching to another mode recalculates every pending cell at once. The mode is saved with the workbook. -
setIterativeCalc
public void setIterativeCalc(boolean enabled, int maxIterations, double maxChange) Enables or disables iterative calculation of circular references (Excel's Enable iterative calculation). Withenabled == falsethe other arguments are stored, but iteration is off.- Parameters:
maxIterations- the most passes per recalculation; a negative value counts as 0maxChange- iteration stops once no value changes by more than this amount
-
date1904
public boolean date1904()Whether the workbook uses the 1904 date system (ECMA-376 Part 1 §18.2.28<workbookPr date1904>). Legacy Mac workbooks count date serials from 1904-01-01 instead of 1899-12-30. -
setDate1904
public void setDate1904(boolean on) Switch the workbook date system. This changes the epoch every stored date serial is interpreted against; existing serial values are NOT rebased, matching the OOXML flag semantics — a date-formatted cell shifts its displayed date by ~4 years when the flag flips. -
locale
The workbook display locale as a BCP-47 tag (default"en-US").The locale is a runtime rendering setting: it selects the month and weekday names, AM/PM markers, decimal / thousands separators, and the locale-adaptive builtin date formats used when cell values are turned into display text (
Cell.formattedText(), PDF / image rendering). It is not persisted into saved xlsx files — Excel stores no workbook display locale — and it never affects formula text, which stays canonical en-US per ECMA-376. -
setLocale
Set the workbook display locale ("de-DE","ja-JP", ...).nullor an empty tag clears back to"en-US". Unknown tags are kept but render as en-US. Seelocale()for scope. -
registerFunction
Registers a user-defined function callable from formulas byname. The function receives its arguments coerced todouble[]and returns adouble. Names are case-insensitive, and the last registration for a name wins.The function must not call back into this workbook while it runs: such a call throws
AxyraException. An exception that escapes the function makes the formula answer#VALUE!. For string/range/error arguments and non-numeric results, useregisterTypedFunction(String, io.keikai.axyra.sheets.formula.TypedUserFunction). -
registerTypedFunction
Register a typed user-defined function callable from formulas byname. Arguments arrive asCellValues — number, text, boolean, error, blank; a range argument arrives as a row-majorCellValue.Array— and the function returns anyCellValue(seeTypedUserFunctionfor the exact shapes). It must not call back into this workbook while it runs: such a call throwsAxyraException. An exception that escapes the function makes the formula answer#VALUE!.Registrations share one per-workbook namespace with
registerFunction(String, io.keikai.axyra.sheets.formula.UserFunction): names are case-insensitive and the last registration for a name wins. This is a distinct method rather than aregisterFunctionoverload because an overload would make every implicitly typed lambda (args -> ...) ambiguous at compile time, breaking existing numeric registrations. -
sheetCount
public int sheetCount()Number of tabs, chart-sheet tabs included (seechartSheetCount()). Indexes0..sheetCount()-1are valid forsheet(int). A new workbook fromcreate()has 0. -
sheet
A view of the tab atindex(0-based, in tab order). The view follows its tab when tabs are inserted, moved or deleted before it. For every tab at once usesheets(); by name usesheet(String).- Throws:
IndexOutOfBoundsException- ifindexis negative or at leastsheetCount()
-
sheet
The sheet with the given name, compared ignoring case as Excel compares sheet names; a sheet whose name matches exactly wins.- Throws:
IllegalArgumentException- if there is no such sheet
-
createSheet
Appends a new empty worksheet after the last tab and returns a view of it. The workbook structure lock (protect(boolean)) does not prevent it. The name must satisfy Excel's sheet-name rules (not blank, at most 31 UTF-16 units (name.length()), no: \ / ? * [ ], U+0000 or U+0003, no leading/trailing apostrophe, notHistory) and be unique in the workbook (case-insensitive).- Throws:
AxyraException- if the name is invalid or already used
-
insertSheet
Inserts a new empty sheet atindex(0..sheetCount inclusive), shifting later sheets right, and return a view of it. The name must satisfy Excel's sheet-name rules (not blank, at most 31 UTF-16 units (name.length()), no: \ / ? * [ ], U+0000 or U+0003, no leading/trailing apostrophe, notHistory, unique in the workbook); an invalid name or index throwsAxyraException.Existing
Sheetviews keep referring to their own tabs; theirSheet.index()reflects the shift. -
deleteSheet
public void deleteSheet(int index) Deletes the sheet atindex(0-based). Cross-sheet formula references to the deleted sheet become#REF!, and the active sheet moves the way Excel moves it: the next sheet activates, or the previous one when the deleted sheet was last. Deleting the only remaining sheet throwsAxyraException(a workbook must contain at least one sheet).Existing
Sheetviews of other sheets keep referring to their own tabs; a view of the deleted sheet throwsIllegalStateExceptionon use.- Throws:
AxyraException- ifindexis out of range or the sheet is the only one
-
renameSheet
Renames the sheet atindex(0-based) tonewName, rewriting formula references (OldName!A1becomesNewName!A1) and named ranges. The name is validated against Excel's sheet-name rules (seeinsertSheet(int, java.lang.String)).- Throws:
AxyraException- ifindexis out of range, or the name is invalid or already used by another sheet
-
moveSheet
public void moveSheet(int from, int to) Moves the sheet atfromto positionto, shifting the sheets in between. Both indexes are 0-based and must be belowsheetCount(). Formula references (including 3D sheet ranges) and the active sheet follow Excel's semantics. ExistingSheetviews keep referring to their own tabs.- Throws:
AxyraException- if either index is out of range
-
activeSheet
The active sheet: the tab Excel shows when the file opens. A plainsave("x.csv")writes it when it is visible. -
setActiveSheet
public void setActiveSheet(int index) Makes the sheet atindex(0-based) the active sheet; it is saved as the tab the file opens on.- Throws:
AxyraException- ifindexis out of range
-
addChartSheet
Append a chart-sheet tab namednamehostingchart— a dedicated full-page chart tab (ECMA-376 §18.3.1.12chartsheet), as opposed to a chart floating on a worksheet viaSheet.addChart(io.keikai.axyra.sheets.content.Chart). Returns the new chart sheet's 0-based index (its position among the workbook's chart sheets, seechartSheetCount()).The chart spec is the same
ChartbuilderSheet.addChart(io.keikai.axyra.sheets.content.Chart)takes (series, axes, legend, title, …); its anchor is ignored — a chart sheet always fills the page. Series references must point at ranges on regular worksheets and be sheet-qualified (e.g."Data!$B$2:$B$10") — the chart sheet has no cells of its own.Ordering: the new tab is appended AFTER all existing tabs (Excel's default position when adding a chart sheet), so it also appears as the last entry of the
sheetCount()tab order. The tab shares the worksheet name namespace; the name must satisfy Excel's sheet-name rules (seeinsertSheet(int, java.lang.String)) orAxyraExceptionis thrown. Extended (Office 2016+) chart types — waterfall, histogram, funnel, treemap, sunburst, box & whisker, pareto, map — are not supported on chart sheets and throwAxyraException. -
chartSheetCount
public int chartSheetCount()Number of chart-sheet tabs in the workbook, authored and imported. They are counted insheetCount()too. -
chartSheetName
The tab name of the chart sheet atindex(0-based position among the chart sheets, in tab order).- Throws:
IndexOutOfBoundsException- ifindexis negative or at leastchartSheetCount()
-
chartSheetChart
A live view of the chart hosted by the chart sheet atindex— the same read-back/edit viewSheet.chart(int)returns. Editing through the view marks the chart sheet modified, so an imported byte-preserved chartsheet is regenerated from the model on the next save.Returns
nullwhen the chart of an IMPORTED chartsheet could not be parsed into the model — the original bytes still round-trip verbatim on save; only the read-back is unavailable. An out-of-rangeindexthrowsIndexOutOfBoundsException. -
removeChartSheet
public boolean removeChartSheet(int index) Removes the chart sheet atindex(0-based position among the chart sheets). The workbook tab disappears and later tabs shift left, exactly likedeleteSheet(int).- Returns:
- whether it existed;
falsefor a negative or out-of-rangeindex
-
copySheet
Appends a deep copy ofsourceundernewNameand returns a view of the copy. For a sheet of another workbook usecopySheetFrom(Workbook, int, String).- Throws:
IllegalArgumentException- ifsourcebelongs to another workbookAxyraException- ifnewNamebreaks Excel's sheet-name rules or is already used
-
copySheetFrom
Appends a deep copy of sheetsheetIndex(0-based) of another workbook and returns a view of the copy. Styles, shared strings and formulas are re-interned into this workbook's pools, so formatting and text survive the move; if the source name collides here the copy is auto-renamed Excel-style (Sheet1→Sheet1 (2)).References qualified with the copied sheet's own name follow the rename; references to other sheets of the source workbook become links to it, as Excel makes them (
SUM(Data!A1:A2)becomesSUM([1]Data!A1:A2), link 1 being the source file), and keep answering the source's values. Sheet-scoped defined names come along, and so do the workbook-scoped names the sheet uses, pointing at the source; a name this workbook already defines is added scoped to the copied sheet instead. Pivot tables, slicers and timelines do not come along.- Throws:
IllegalArgumentException- ifsourceis this workbookIndexOutOfBoundsException- ifsheetIndexis out of range
-
copySheetFrom
Appends a deep copy of sheetsheetIndex(0-based) of another workbook undernewNameand returns a view of the copy. Same semantics ascopySheetFrom(Workbook, int), but the name is explicit: it must satisfy Excel's sheet-name rules and be unique in this workbook, orAxyraExceptionis thrown. Anullname means "source name, auto-suffixed on collision".- Throws:
IllegalArgumentException- ifsourceis this workbookIndexOutOfBoundsException- ifsheetIndexis out of range
-
combine
Appends a deep copy of every sheet (visible and hidden) of each source workbook, in argument order, auto-suffixing colliding names. It is the whole-workbook counterpart ofcopySheetFrom(Workbook, int), with the same copy rules and exclusions except as follows.Each source's sheets are copied as one group: a reference from one copied sheet to another follows that sheet's rename (
SUM(Data!A1:A2)becomesSUM('Data (2)'!A1:A2)whenDatahad to be renamed), so a combined region keeps summing its own data. The source's workbook-scoped names come along, rewritten the same way; a name this workbook already defines is added as a sheet-scoped name on each copied sheet, so the copies resolve it to their own data.All arguments are validated before any sheet is copied, so an invalid argument does not leave a partial merge behind. Each source is then copied by its own engine call: an engine error on a later source leaves the sheets of the earlier sources in this workbook.
- Throws:
NullPointerException- ifsourcesor any element isnullIllegalArgumentException- if any source is this workbookIllegalStateException- if any source is closed
-
splitToFiles
Split this workbook into one single-sheet file per sheet, written todir(created if missing), and return the written paths in sheet order.patternnames each file and must contain a{name}(sheet name, sanitized for the file system) or{index}(0-based sheet index) placeholder — e.g."{name}.xlsx"or"part-{index}.xlsx".Each output is built by copying the sheet into a fresh workbook with
copySheetFrom(Workbook, int)(same migration semantics and exclusions). A hidden sheet is made visible in its own file, since a workbook needs at least one visible sheet. This workbook is not modified.- Throws:
IllegalArgumentException- ifpatternhas no placeholderAxyraIoException- if a file cannot be written
-
sheets
A view of every tab, in tab order, chart-sheet tabs included.- Returns:
- a new list, a snapshot of the tabs; each view still follows its own tab
-
title
The document title (dc:title), ornullwhen none is set. -
setTitle
Sets the document title (dc:title);nullclears it. -
subject
The document subject (dc:subject), ornullwhen none is set. -
setSubject
Sets the document subject (dc:subject);nullclears it. -
author
The author (OOXMLdc:creator), ornullwhen none is set. -
setAuthor
Sets the author (OOXMLdc:creator);nullclears it. -
keywords
The document keywords (cp:keywords), ornullwhen none are set. -
setKeywords
Sets the document keywords (cp:keywords);nullclears them. -
comments
The comments (OOXMLdc:description), ornullwhen none are set. -
setComments
Sets the comments (OOXMLdc:description);nullclears them. -
lastModifiedBy
The user who last saved the workbook (cp:lastModifiedByofdocProps/core.xml), ornull. -
setLastModifiedBy
Setscp:lastModifiedBy;nullclears it. -
lastPrinted
When the workbook was last printed (cp:lastPrinted, a W3CDTF timestamp), ornull. Excel only updates this on an actual print. -
setLastPrinted
Setscp:lastPrinted, a W3CDTF timestamp such as2024-03-01T09:00:00Z. The text is stored as given, without a check;nullclears it. -
created
The creation timestamp (dcterms:created, W3CDTF), ornull. -
setCreated
Setsdcterms:created, a W3CDTF timestamp. The text is stored as given, without a check;nullclears it. -
modified
The last-modified timestamp (dcterms:modified, W3CDTF), ornull. -
setModified
Setsdcterms:modified, a W3CDTF timestamp. The text is stored as given, without a check;nullclears it. -
revision
The revision number (cp:revision), ornull. -
setRevision
Setscp:revision. It is stored as given and never incremented;nullclears it. -
contentStatus
The content status (cp:contentStatus, e.g. "Draft"), ornull. -
setContentStatus
Setscp:contentStatus;nullclears it. -
category
The document category (cp:category), ornull. -
setCategory
Setscp:category;nullclears it. -
language
The document language (dc:language, e.g.en-GB), ornull. -
setLanguage
Setsdc:language, an RFC 5646 language tag such asen-GB. The tag is stored as given;nullclears it. -
documentVersion
The author-recorded document version (cp:versionofdocProps/core.xml), ornull.Free text. Excel neither writes nor interprets it — a producer that sets it does so for its own readers — but it must survive a round trip, which is why it is modelled rather than dropped. Not to be confused with
appVersion(), the authoring application's version indocProps/app.xml. -
setDocumentVersion
Setcp:version;nullclears it. -
application
The authoring application (ApplicationofdocProps/app.xml), ornullwhen none is set. When it isnull, a saved.xlsxwrites the engine's own name asApplication. -
setApplication
Sets theApplicationname written todocProps/app.xml;nullclears it. -
appVersion
The authoring application version (AppVersion), ornull. -
setAppVersion
SetsAppVersion; Excel's form isMM.mmmm, for example16.0300.nullclears it. -
company
The company (CompanyofdocProps/app.xml), ornull. -
setCompany
SetsCompany;nullclears it. -
manager
The manager (ManagerofdocProps/app.xml), ornull. -
setManager
SetsManager;nullclears it. -
hyperlinkBase
The base URI relative hyperlinks resolve against (HyperlinkBaseofdocProps/app.xml), ornull. -
setHyperlinkBase
SetsHyperlinkBase;nullclears it. -
docSecurity
TheDocSecurityflags ofdocProps/app.xml, ornullwhen the workbook records none. A saved.xlsxwrites 0 when this isnull. -
setDocSecurity
SetsDocSecurity;nullclears it.- Throws:
AxyraException- ifdocSecurityis negative
-
scaleCrop
TheScaleCropflag ofdocProps/app.xml, ornullwhen the workbook records none. -
setScaleCrop
SetScaleCrop(nullclears it). -
linksUpToDate
TheLinksUpToDateflag ofdocProps/app.xml, ornullwhen the workbook records none. -
setLinksUpToDate
SetLinksUpToDate(nullclears it). -
hyperlinksChanged
TheHyperlinksChangedflag ofdocProps/app.xml, ornullwhen the workbook records none. -
setHyperlinksChanged
SetHyperlinksChanged(nullclears it). -
customProperties
The custom document properties, in file order — an immutable read view (empty list when the workbook has none). Each entry carries a typedCustomProperty.Value; write throughsetCustomProperty(String, String)and its overloads, remove withremoveCustomProperty(String).An integer (
vt:i4) and a real (vt:r8) both read asCustomProperty.Number. A date reads as the calendar date of its stored timestamp; the time of day is dropped. Any other type reads asCustomProperty.Rawand is saved unchanged. -
setCustomProperty
Sets (or replaces) the text-typed custom document propertyname. An existing property with the same name keeps its position; a new one is appended. Names are case-sensitive.- Throws:
NullPointerException- ifnameorvalueisnull
-
setCustomProperty
Sets (or replaces) the number-typed custom document propertyname. Placement and naming are as forsetCustomProperty(String, String). -
setCustomProperty
Sets (or replaces) the boolean-typed custom document propertyname. Placement and naming are as forsetCustomProperty(String, String). -
setCustomProperty
Sets (or replaces) the date-typed custom document propertyname. It is stored as the midnight-UTC timestamp of the given calendar date (the underlying variant type carries a full timestamp). Placement and naming are as forsetCustomProperty(String, String).- Throws:
NullPointerException- ifnameorvalueisnull
-
removeCustomProperty
Removes the custom document propertyname(case-sensitive); returns whether it existed. Removing the last property makes a saved file omit the custom properties part entirely. -
theme
The workbook theme (color scheme + major/minor fonts), ornullwhen the workbook has no theme. Theme colors are whatColor.theme(...)references resolve against. -
setTheme
Sets the workbook theme (color scheme plus major and minor fonts).Color.theme(...)references resolve against the new theme.- Throws:
NullPointerException- ifthemeisnull
-
defaultStyle
The workbook default ("Normal") style — what unstyled cells render with. Its font attributes (seesetDefaultFont(io.keikai.axyra.sheets.style.CellStyle)) determine the grid metrics of every sheet. -
setDefaultFont
Replace the workbook default ("Normal") font with the font attributes ofstyle(name, size, color, bold, …); its non-font attributes are ignored. The default font is layout-critical, not just cosmetic: Excel derives the pixel width of a column character unit (the max-digit-width) from it and auto-fits height-less rows to it, so two workbooks with the same widths/heights but different default fonts lay out on different grids. -
formulaToR1C1
Converts a formula's cell references from A1 to R1C1 style, relative to the 1-based(anchorRow, anchorColumn); the rest of this API is 0-based. Quoted strings and function names are kept. A defined name spelled like a cell reference is treated as a reference. The call does not read this workbook. The reverse isformulaToA1(String, int, int). -
formulaToA1
Converts a formula's references from R1C1 back to A1 style, relative to the 1-based(anchorRow, anchorColumn); the rest of this API is 0-based. The call does not read this workbook. The reverse isformulaToR1C1(String, int, int). -
precedents
The direct precedents of a cell: the cells its formula reads, on any sheet. Empty for a non-formula cell. The dependency graph is built on demand.rowandcolumnare 0-based;sheetmust belong to this workbook.- Returns:
- a new list, a snapshot sorted by sheet, row, then column
-
dependents
The direct dependents of a cell: the cells whose formulas read it.rowandcolumnare 0-based;sheetmust belong to this workbook. For the whole chain useallDependents(io.keikai.axyra.sheets.Sheet, int, int).- Returns:
- a new list, a snapshot sorted by sheet, row, then column
-
allDependents
Every cell that depends on a cell directly or through other cells; the cell itself is not included.rowandcolumnare 0-based;sheetmust belong to this workbook.- Returns:
- a new list, a snapshot sorted by sheet, row, then column
-
xmlMaps
The XML map definitions in this workbook (read-only): each map's id, name, root element, schema id, XSD schema text and cell bindings (XmlMap.bindings()), read fromxl/xmlMaps.xml. The definitions are preserved byte-exact on save.- Returns:
- a new list, a snapshot; empty when the workbook defines no XML maps
-
connections
The data connections defined in this workbook (Power Query and other), read fromxl/connections.xml, orxl/connections.binfor an.xlsbfile. The engine never runs a connection.- Returns:
- a new list, a snapshot; empty when the workbook has none
-
setConnectionCommand
Sets the command text (for example a SQL statement or an M query reference) of the named connection. Every other byte of the connections part is preserved. The engine does not run the command.- Returns:
- whether a connection named
nameexists
-
setConnectionString
Sets the connection string of the named connection. The engine does not open the connection.- Returns:
- whether a connection named
nameexists
-
vbaModules
The VBA code modules in this macro-enabled workbook (read-only): each module's editor name, kind ("standard"/"class"/"document"), and MS-OVBA-decompressed source text. Empty when the workbook has no VBA project. ThevbaProject.binis preserved byte-exact on save regardless. The engine never runs VBA.- Returns:
- a new list, a snapshot
-
oleObjects
The embedded OLE objects in this workbook, in index order: name, ProgID and raw bytes. It reads each object with its own engine calls.- Returns:
- a new list, a snapshot; empty when there are none
-
addOleObject
Embeds an OLE object (raw bytes, optional ProgID) at workbook level. The object is not shown on any sheet untilSheet.anchorOleObject(int, byte[], java.lang.String, int, int, int, int)anchors an icon for it.- Returns:
- the object's 0-based index in
oleObjects()
-
setOleObjectData
public boolean setOleObjectData(int index, byte[] data) Replaces the embedded OLE object's bytes in place; returns whether the index existed (falsefor a negative index). Name and ProgID are kept, and — unlikeremoveOleObject(int)— any worksheet anchors from an opened XLSX stay intact: the sheet keeps displaying the object's icon, now backed by the new content. -
removeOleObject
public boolean removeOleObject(int index) Removes the embedded OLE object atindex(0-based); returns whether it existed (falsefor a negative index). Later objects move down by one index. On workbooks opened from XLSX this also drops the imported worksheet<oleObjects>anchors, so the remaining embedded parts are kept but no longer displayed on the sheets. -
registerNamedStyle
Registers a reusable named cell style (for example"Good"or"Title"). Apply it to cells withRange.applyNamedStyle(String). Names are case-sensitive. Registering an existing name replaces its definition for future use only; cells already styled with it keep their formatting. To restyle them too, useupdateNamedStyle(java.lang.String, io.keikai.axyra.sheets.style.CellStyle). -
namedStyleCount
public int namedStyleCount()Number of registered named cell styles. -
hasNamedStyle
Whether a named style is registered undername(case-sensitive). -
removeNamedStyle
Delete a named cell style. Cells styled with it revert to the default style — Excel's "Delete" on a custom cell style clears that formatting from its users. Returns whether the name existed. -
updateNamedStyle
Redefine a named cell style and PROPAGATE the change: every cell (and row/column default) currently styled with it is restyled — Excel's "Modify…" on a cell style. Returns whether the name existed. -
addName
Adds a workbook-scoped defined name, or replaces one.formulais the name's reference or formula, such as"Sheet1!$A$1:$C$10".Neither the name nor the formula is checked. A name replaces an existing one only when the spelling (case-sensitive) and the scope both match; the replacement moves to the end of
names(). Formulas resolve names ignoring case, so avoid two names that differ only in case. -
addName
Adds a defined name scoped toscope, or replaces one; the rules ofaddName(String, String)apply.- Throws:
IllegalArgumentException- ifscopebelongs to another workbook
-
removeName
Removes every defined name spelled exactlyname(case-sensitive), in every scope.- Returns:
- whether any name matched
-
customTableStyles
The workbook's CUSTOM table-style definitions (<tableStyles>+ their differential-format payloads) plus the default table/pivot style names, as one opaque JSON value object — ornullwhen the workbook defines none. A table whosetableStyleInfonames a custom style renders with Excel's default formatting when the definition is missing, so a faithful rebuild must carry this alongsidesetTableStyle. Pass the value tosetCustomTableStyles(String)on the destination workbook. -
setCustomTableStyles
Installs custom table-style definitions produced bycustomTableStyles(). It replaces every existing custom table style and both default style names.- Throws:
AxyraException- ifjsonis not a valuecustomTableStyles()produced
-
names
Every defined name, in definition order, with its scope. It reads each name with its own engine call.- Returns:
- a new list, a snapshot
-
findName
The first defined name spelled exactlyname(case-sensitive), in definition order and in any scope, ornullwhen none matches. It reads every defined name; callnames()once when looking up many. -
range
A range parsed from a sheet-qualified A1 reference — the spelling a defined name stores, e.g."Sheet1!$A$1:$C$10"or"'Q1 Data'!B2". Whole-column and whole-row bands ("Sheet1!$B:$B") expand to the grid's limits.- Throws:
IllegalArgumentException- if the reference names no sheet, names a sheet this workbook does not have, or is not a single rectangular area — a constant, a multi-area union, an external or 3-D reference
-
goalSeek
Finds the value for thechangingcell that makes thetargetcell equaltargetValue(Excel's Goal Seek). The changing cell must be a numeric input the target depends on.The search starts from 0 and 1, not from the cell's current value, and stops after 100 steps. On success the changing cell keeps the solution. On failure it gets its original content back. It works under manual calculation too.
- Returns:
- the solution, or
Double.NaNif the search does not converge or the target is not numeric - Throws:
IllegalArgumentException- if either cell belongs to another workbook
-
protect
public void protect(boolean lockStructure) Sets or clears the workbook structure lock, without a password; the window lock is cleared. Excel then refuses to add, delete, rename or move sheets. This API does not enforce the lock:createSheet(java.lang.String)and the other sheet methods still work. For a password useprotectStructure(String). -
protect
public void protect(boolean lockStructure, boolean lockWindows) Sets or clears the workbook structure and window locks, without a password. The locks are saved for Excel to enforce; this API does not enforce them. -
unprotect
public void unprotect()Clears both workbook locks without checking a password. UseunprotectStructure(String)to require the password. -
isStructureLocked
public boolean isStructureLocked()Whether the workbook structure is locked. -
protectStructure
Lock the workbook structure (ECMA-376 §18.2.29lockStructure) with a password (ISO Write Protection hash, [MS-OFFCRYPTO] §2.4.2.2).nullor empty locks without a password. -
protectStructure
Locks the workbook structure and optionally the windows (§18.2.29), with a password as forprotectStructure(String). The lock is saved for Excel to enforce; this API does not enforce it. -
unprotectStructure
Clear the workbook protection after verifyingpasswordagainst the stored hash. Returnstruewhen the workbook ends up unprotected — including when it was not protected or carries no password;false(protection kept) on a mismatch. -
isStructureProtected
public boolean isStructureProtected()Whether the workbook structure is protected (alias ofisStructureLocked()). -
isWindowsLocked
public boolean isWindowsLocked()Whether the workbook windows are locked (§18.2.29lockWindows). -
setWriteProtection
Write-protect the workbook with a modify password (<fileSharing>— ECMA-376 Part 1 §18.2.12): Excel prompts for the password on open and offers read-only otherwise. The password is stored as an ISO Write Protection hash ([MS-OFFCRYPTO] §2.4.2.2) — this is a tamper deterrent, not encryption; usesaveEncrypted(Path, String)for an open password. -
setWriteProtection
Write-protect the workbook:passwordgates editing (null = none),userNamerecords who reserved the file, andreadOnlyRecommendedshows the open-read-only prompt. An entirely empty request removes the protection. -
removeWriteProtection
public void removeWriteProtection()Removes the write protection and the read-only recommendation, without checking a password. -
isWriteProtected
public boolean isWriteProtected()Whether a modify password is stored. A read-only recommendation without a password answersfalse; seewriteProtection(). -
writeProtection
The write-protection state, ornullwhen the workbook carries no<fileSharing>element. A snapshot. -
verifyWritePassword
Verifiespasswordagainst the stored modify-password hash;falsewhen the workbook is not write-protected. -
close
public void close()Frees the native workbook and its registered user-defined functions. Calling it again does nothing. After close, every method of this workbook and of itsSheet,RangeandCellviews throwsIllegalStateException. Unsaved changes are lost.- Specified by:
closein interfaceAutoCloseable
-