/**
* Presentation for Fast Feather Track on ApacheconEU 2008
- *
- * @author Yegor Kozlov
*/
@SuppressWarnings("java:S1192")
public final class ApacheconEU08 {
/**
* A XLS -> CSV processor, that uses the MissingRecordAware
* EventModel code to ensure it outputs all columns and rows.
- * @author Nick Burch
*/
@SuppressWarnings({"java:S106","java:S4823"})
public class XLS2CSVmra implements HSSFListener {
/**
* Shows how various alignment options work.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class Alignment {
public static void main(String[] args) throws IOException {
/**
* Illustrates how to create cell values.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class CreateCells {
public static void main(String[] args) throws IOException {
* are not strictly necessary. If the inputs to the listInCell() and
* multilLevelListInCell() methods are constructed to include the bullet
* character or the item numbers then these methods alone may be sufficient.
- *
- * @author Mark Beardsley [msb at apache.org]
*/
@SuppressWarnings({"java:S106","java:S4823"})
public class InCellLists {
/**
* Demonstrates the use of the EscherGraphics2d library.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class OfficeDrawingWithGraphics {
public static void main( String[] args ) throws IOException {
/**
* This example demonstrates opening a workbook, modifying it and writing
* the results back out.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class ReadWriteWorkbook {
public static void main(String[] args) throws IOException {
/**
* Sets the zoom magnication for a sheet.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class ZoomSheet
{
* grow in size of the column is made wider or the row higher but it will shrink
* if the columns width or rows height are reduced.
*
- * @author Mark Beardsley [msb at apache.org] and Mark Southern [southern at scripps.edu]
* @version 1.00 5th August 2009.
* 2.00 26th February 2010.
* Ported to make use of the the SS usermodel classes.
* either how far the image should be inset from the top or the left hand
* edge of the cell.
*
- * @author Mark Beardsley [msb at apache.org]
* @version 1.00 5th August 2009.
*/
public class ClientAnchorDetail {
* size measurements into pixels and/or millimetres. The class also contains
* various constants that are required in other calculations.
*
- * @author xio[darjino@hotmail.com]
* @version 1.01 30th July 2009.
* Added by Mark Beardsley [msb at apache.org].
* Additional constants.
* A business plan demo
* Usage:
* BusinessPlan -xls|xlsx
- *
- * @author Yegor Kozlov
*/
@SuppressWarnings({"java:S106","java:S4823","java:S1192"})
public final class BusinessPlan {
* Usage:
* CalendarDemo -xls|xlsx <year>
* </pre>
- *
- * @author Yegor Kozlov
*/
@SuppressWarnings({"java:S106","java:S4823","java:S1192"})
public final class CalendarDemo {
* better to include the name of the sheet when calling the setRefersToFormula()
* method.
*
- * @author Mark Beardsley [msb at apache.org]
* @version 1.00 30th March 2012
*/
public class LinkedDropDownLists {
*
* Usage:
* LoanCalculator -xls|xlsx
- *
- * @author Yegor Kozlov
*/
@SuppressWarnings({"java:S106","java:S4823","java:S1192"})
public final class LoanCalculator {
* A weekly timesheet created using Apache POI.
* Usage:
* TimesheetDemo -xls|xlsx
- *
- * @author Yegor Kozlov
*/
@SuppressWarnings({"java:S106","java:S4823","java:S1192"})
public final class TimesheetDemo {
* class has to be modified to produce files to suit a specific application
* or requirement.
* </p>
- * @author Mark B
+ *
* @version 1.00 9th April 2010
* 1.10 13th April 2010 - Added support for processing all Excel
* workbooks in a folder along with the ability
/**
* A simple user-defined function to calculate principal and interest.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class CalculateMortgage implements FreeRefFunction {
/**
* Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases
*
- * @throws EvaluationException (#NUM!) if <tt>result</tt> is <tt>NaN</> or <tt>Infinity</tt>
+ * @throws EvaluationException (#NUM!) if {@code result} is {@code NaN} or {@code Infinity}
*/
private void checkValue(double result) throws EvaluationException {
if (Double.isNaN(result) || Double.isInfinite(result)) {
* formats. If you are writing such code, you can add a method to this
* interface, and then implement it for both HSSF and XSSF workbooks, letting
* the driving code stay independent of format.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public interface HtmlHelper {
/**
/**
* Creates a new examples to HTML for the given workbook. If the path ends
- * with "<tt>.xlsx</tt>" an {@link XSSFWorkbook} will be used; otherwise
+ * with "{@code .xlsx}" an {@link XSSFWorkbook} will be used; otherwise
* this will use an {@link HSSFWorkbook}.
*
* @param path The file that has the workbook.
/**
* Implementation of {@link HtmlHelper} for XSSF files.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public class XSSFHtmlHelper implements HtmlHelper {
@Override
/**
* Demonstrates a workaround you can use to generate large workbooks and avoid OutOfMemory exception.
- *
+ * <p>
* Note - You probably <em>don't want to use this approach any more</em>! POI
* now includes the SXSSF which handles all of this for you, you should
* be using that instead! This code remains mostly for historical interest.
* <p>
- * See <a "https://poi.apache.org/spreadsheet/how-to.html#sxssf">
- * https://poi.apache.org/spreadsheet/how-to.html#sxssf</a>.
- * <p>
* If you really want to use this approach, which is also the one that SXSSF
* does for you, it works as follows:
+ * <ol>
+ * <li>create a template workbook, create sheets and global objects such as cell styles, number formats, etc.</li>
+ * <li>create an application that streams data in a text file</li>
+ * <li>Substitute the sheet in the template with the generated data</li>
+ * </ol>
*
- * 1. create a template workbook, create sheets and global objects such as cell styles, number formats, etc.
- * 2. create an application that streams data in a text file
- * 3. Substitute the sheet in the template with the generated data
- *
- * <p>
* Since 3.8 POI provides a low-memory footprint SXSSF API, which implements
* ths "BigGridDemo" strategy. SXSSF is an API-compatible streaming extension
* of XSSF to be used when very large spreadsheets have to be produced, and
* access to the rows that are within a sliding window, while XSSF gives access
* to all rows in the document. Older rows that are no longer in the window
* become inaccessible, as they are written to the disk.
- * </p>
- * See <a "https://poi.apache.org/spreadsheet/how-to.html#sxssf">
- * https://poi.apache.org/spreadsheet/how-to.html#sxssf</a>.
+ *
+ * @see <a href="https://poi.apache.org/spreadsheet/how-to.html#sxssf">SXSSF (Streaming Usermodel API)</a>.
*/
public final class BigGridDemo {
private static final String XML_ENCODING = "UTF-8";
* Usage:
* CalendarDemo <year>
* </pre>
- *
- * @author Yegor Kozlov
*/
public class CalendarDemo {
* Excel comment is a kind of a text shape,
* so inserting a comment is very similar to placing a text box in a worksheet
* </p>
- *
- * @author Yegor Kozlov
*/
public class CellComments {
public static void main(String[] args) throws IOException {
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
-/**
- *
- * @author Richard Ngo
- *
- */
public class SimpleDocumentWithHeader {
public static void main(String[] args) throws IOException {
* that not all referenced wordprocessingml classes are defined in the
* poi-ooxml-lite jar. If this is the case, you'll need to use the
* poi-ooxml-full jar library.
- *
- * @author gisella bronzetti (original)
- * @author Gregg Morris (styled table)
*/
public class SimpleTable {
import java.io.IOException;
/**
- * @author aviks
* Wrap a java.io.OutputStream around a Ruby IO object
*/
* by a WorkbookUtil instance. The evaluate() method of the WorkbookUtil
* class returns an EvaluationResult which encapsulates the results and
* information from the evaluation.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
-
- *
*/
public class ExcelAntEvaluateCell extends Task {
* <code>IExcelAntWorkbookHandler</code> interface. After writing the
* class you should package it and it's dependencies into a jar file to
* add as library in your Ant build file.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class ExcelAntHandlerTask extends Task {
import org.apache.tools.ant.taskdefs.Typedef;
-/**
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
- */
public class ExcelAntPrecision extends Typedef {
-
+
private double value ;
-
+
public void setValue( double precision ) {
value = precision ;
}
-
+
public double getValue() {
return value ;
}
import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil;
import org.apache.tools.ant.Task;
-/**
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
- */
public abstract class ExcelAntSet extends Task {
-
+
protected String cellStr ;
-
+
protected ExcelAntWorkbookUtil wbUtil ;
-
+
public void setCell( String cellName ) {
cellStr = cellName ;
}
-
+
public String getCell() {
return cellStr ;
}
-
-
+
+
public void setWorkbookUtil( ExcelAntWorkbookUtil wb ) {
wbUtil = wb ;
}
/**
* Class for use in an Ant build script that sets the value of an Excel
* sheet cell using the cell id ('Sheet Name'!cellId).
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class ExcelAntSetDoubleCell extends ExcelAntSet {
private double cellValue;
-
+
public ExcelAntSetDoubleCell() {}
-
+
/**
* Set the value of the specified cell as the double passed in.
* @param value The double-value that should be set when this task is executed.
public double getCellValue() {
return cellValue;
}
-
+
@Override
public void execute() throws BuildException {
wbUtil.setDoubleValue(cellStr, cellValue ) ;
-
+
log( "set cell " + cellStr + " to value " + cellValue + " as double.", Project.MSG_DEBUG ) ;
}
}
/**
* Class for use in an Ant build script that sets the formula of an Excel
* sheet cell using the cell id ('Sheet Name'!cellId).
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class ExcelAntSetFormulaCell extends ExcelAntSet {
-
-
+
+
private String cellValue ;
-
+
public ExcelAntSetFormulaCell() {}
-
+
public void setValue( String value ) {
cellValue = value ;
}
protected String getCellValue() {
return cellValue;
}
-
+
@Override
public void execute() throws BuildException {
-
+
wbUtil.setFormulaValue( cellStr, cellValue ) ;
-
+
log( "set cell " + cellStr + " to formula " + cellValue, Project.MSG_DEBUG ) ;
}
}
/**
* Class for use in an Ant build script that sets the value of an Excel
* sheet cell using the cell id ('Sheet Name'!cellId).
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class ExcelAntSetStringCell extends ExcelAntSet {
private String stringValue ;
public String getCellValue() {
return stringValue;
}
-
+
@Override
public void execute() throws BuildException {
wbUtil.setStringValue(cellStr, stringValue ) ;
-
+
log( "set cell " + cellStr + " to value " + stringValue + " as String.", Project.MSG_DEBUG ) ;
}
}
* This class represents a single test. In order for the test any and all
* ExcelAntEvaluateCell evaluations must pass. Therefore it is recommended
* that you use only 1 evaluator but you can use more if you choose.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
@SuppressWarnings("unused")
public class ExcelAntTest extends Task{
/**
* This class encapsulates the Strings necessary to create the User Defined
* Function instances that will be passed to POI's Evaluator instance.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class ExcelAntUserDefinedFunction extends Typedef {
/**
- * In Excel there are many ways to handle manipulating a workbook based
+ * In Excel there are many ways to handle manipulating a workbook based
* on some arbitrary user action (onChange, etc). You use this interface
* to create classes that will handle the workbook in whatever manner is needed
* that cannot be handled by POI.
* does some calculations and updates other cells based on that change. In
* ExcelAnt you would set the value of the cell then write your own handler
* then call that from your Ant task after the set task.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public interface IExcelAntWorkbookHandler {
public void setWorkbook( Workbook workbook ) ;
-
+
public void execute() ;
}
/**
* A simple class that encapsulates information about a cell evaluation
* from POI.
- *
- * @author Jon Svede (jon [at] loquatic [dot] com)
- * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
- *
*/
public class ExcelAntEvaluationResult {
-
+
/**
* This boolean flag is used to determine if the evaluation completed
- * without error. This alone doesn't ensure that the evaluation was
+ * without error. This alone doesn't ensure that the evaluation was
* successful.
*/
private boolean evaluationCompletedWithError ;
-
+
/**
* This boolean flag is used to determine if the result was within
* the specified precision.
*/
private boolean didPass ;
-
+
/**
* This is the actual value returned from the evaluation.
*/
private double returnValue ;
-
+
/**
* Any error message String values that need to be returned.
*/
private String errorMessage ;
-
+
/**
* Stores the absolute value of the delta for this evaluation.
*/
private double actualDelta ;
-
+
/**
* This stores the fully qualified cell name (sheetName!cellId).
*/
private String cellName ;
-
-
+
+
public ExcelAntEvaluationResult(boolean completedWithError,
- boolean passed,
- double retValue,
- String errMessage,
+ boolean passed,
+ double retValue,
+ String errMessage,
double delta,
String cellId) {
public String getErrorMessage() {
return errorMessage;
}
-
+
public boolean didTestPass() {
return didPass ;
}
-
+
public boolean evaluationCompleteWithError() {
return evaluationCompletedWithError ;
}
-
+
public double getDelta() {
return actualDelta ;
}
-
+
public String getCellName() {
return cellName ;
}
+ ", returnValue=" + returnValue + ", errorMessage="
+ errorMessage + ", actualDelta=" + actualDelta + ", cellName="
+ cellName + "]";
- }
+ }
}
/**
* A general utility class that abstracts the POI details of loading the
* workbook, accessing and updating cells.
- *
- * @author Jon Svede (jon [at] loquatic [dot] com)
- * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
- *
*/
public class ExcelAntWorkbookUtil extends Typedef {
/**
* This is a factory class maps file names to WorkbookUtil instances. This
* helps ExcelAnt be more efficient when being run many times in an Ant build.
- *
- * @author Jon Svede (jon [at] loquatic [dot] com)
- * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
- *
*/
public final class ExcelAntWorkbookUtilFactory {
/**
* A simple user-defined function to calculate principal and interest.
- *
- * Used by {@link org.apache.poi.ss.excelant.util.TestExcelAntWorkbookUtil}.
- *
- * @author Jon Svede ( jon [at] loquatic [dot] com )
- * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
- *
*/
public class CalculateMortgageFunction implements FreeRefFunction {
/**
* Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases
*
- * @throws EvaluationException (#NUM!) if <tt>result</tt> is <tt>NaN</> or <tt>Infinity</tt>
+ * @throws EvaluationException (#NUM!) if {@code result} is {@code NaN} or {@code Infinity}
*/
private void checkValue(double result) throws EvaluationException {
if (Double.isNaN(result) || Double.isInfinite(result)) {
/**
* A helper class to allow testing of protected methods and constructors.
- *
- * @author jsvede
- *
*/
public class ExcelAntWorkbookUtilTestHelper extends ExcelAntWorkbookUtil {
return super.getEvaluator(excelFileName);
}
-
+
}
destinationDirectory = file("../build/dist/maven/${project.archivesBaseName}")
}
+javadoc {
+ failOnError = true
+ maxMemory = "1024M"
+ doFirst {
+ options {
+ if (JavaVersion.current().isJava9Compatible()) {
+ addBooleanOption('html5', true)
+ }
+ links 'https://xmlbeans.apache.org/docs/5.0.0/'
+ use = true
+ splitIndex = true
+ source = "1.8"
+ }
+ }
+}
+
task sourceJar(type: Jar) {
classifier 'sources'
from sourceSets.main.allJava
/**
* Indicates a generic OOXML error.
- *
- * @author Yegor Kozlov
*/
-@SuppressWarnings("serial")
public final class POIXMLException extends RuntimeException{
/**
- * Create a new <code>POIXMLException</code> with no
+ * Create a new {@code POIXMLException} with no
* detail mesage.
*/
public POIXMLException() {
}
/**
- * Create a new <code>POIXMLException</code> with
- * the <code>String</code> specified as an error message.
+ * Create a new {@code POIXMLException} with
+ * the {@code String} specified as an error message.
*
* @param msg The error message for the exception.
*/
}
/**
- * Create a new <code>POIXMLException</code> with
- * the <code>String</code> specified as an error message and the cause.
+ * Create a new {@code POIXMLException} with
+ * the {@code String} specified as an error message and the cause.
*
* @param msg The error message for the exception.
* @param cause the cause (which is saved for later retrieval by the
- * {@link #getCause()} method). (A <tt>null</tt> value is
+ * {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
}
/**
- * Create a new <code>POIXMLException</code> with
+ * Create a new {@code POIXMLException} with
* the specified cause.
*
* @param cause the cause (which is saved for later retrieval by the
- * {@link #getCause()} method). (A <tt>null</tt> value is
+ * {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
}
/**
- * This type seems to be interpreted as percent value when the trailing percent sign is missing.<br/>
+ * This type seems to be interpreted as percent value when the trailing percent sign is missing.<p>
* sample snippet from settings.xml
- * <pre>
- * <w:zoom w:percent="50" />
- * <pre>
+ * <pre>{@code
+ * <w:zoom w:percent="50" />
+ * }</pre>
*
* @return the percent scaled by 1000, so 100% = 100000
*/
}
/**
- * This type seems to be interpreted as percent value when the trailing percent sign is missing.<br/>
+ * This type seems to be interpreted as percent value when the trailing percent sign is missing.<p>
* sample snippet from settings.xml
- * <pre>
- * <w:textscale w:w="50" />
- * <pre>
+ * <pre>{@code
+ * <w:textscale w:w="50" />
+ * }</pre>
*
* @return the percent scaled by 1000, so 100% = 100000
*/
private static long parseLengthInner(org.apache.xmlbeans.XmlAnySimpleType coordUnion, double noUnitEmuFactor) {
String strVal = coordUnion.getStringValue().toLowerCase(Locale.ROOT);
double digVal = Double.parseDouble(strVal.replaceAll("(mm|cm|in|pt|pc|pi)", ""));
- long emu = 0;
+ long emu;
// http://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/
if (strVal.endsWith("mm")) {
emu = (long)(((digVal/10f)/2.54f)*EMU_PER_INCH);
* set as Runtime in order not to force the user to manage the exception in a
* try/catch).
*
- * @author Julien Chable
* @version 1.0
*/
@SuppressWarnings("serial")
/**
* Specifies the location where the X.509 certificate that is used in signing is stored.
- *
- * @author Julien Chable
*/
public enum CertificateEmbeddingOption {
/** The certificate is embedded in its own PackagePart. */
/**
* Open Packaging Convention content types (see Annex F : Standard Namespaces
* and Content Types).
- *
- * @author CDubettier define some constants, Julien Chable
*/
public final class ContentTypes {
*
* @param partName
* Part name of the part to retrieve.
- * @return The part with the specified name, else <code>null</code>.
+ * @return The part with the specified name, else {@code null}.
*/
public PackagePart getPart(PackagePartName partName) {
throwExceptionIfWriteOnly();
* part, then delete all relationships in the source part.
*
* @param part
- * The part to remove. If <code>null</code>, skip the action.
+ * The part to remove. If {@code null}, skip the action.
* @see #removePart(PackagePartName)
*/
public void removePart(PackagePart part) {
* @param relationshipType
* Type of relationship.
* @return The newly created and added relationship
- * @see RelationshipSource#addExternalRelationship(String,
- * String)
*/
@Override
public PackageRelationship addExternalRelationship(String target,
}
}
- /**
- * @see RelationshipSource#getRelationship(String)
- */
@Override
public PackageRelationship getRelationship(String id) {
return this.relationships.getRelationshipByID(id);
}
- /**
- * @see RelationshipSource#hasRelationships()
- */
@Override
public boolean hasRelationships() {
return (relationships.size() > 0);
}
- /**
- * @see RelationshipSource#isRelationshipExists(PackageRelationship)
- */
@Override
public boolean isRelationshipExists(PackageRelationship rel) {
for (PackageRelationship r : relationships) {
throws InvalidFormatException;
/**
- * Replace a content type in this package.
- *
- * <p>
- * A typical scneario to call this method is to rename a template file to the main format, e.g.
- * ".dotx" to ".docx"
- * ".dotm" to ".docm"
- * ".xltx" to ".xlsx"
- * ".xltm" to ".xlsm"
- * ".potx" to ".pptx"
- * ".potm" to ".pptm"
- * </p>
+ * Replace a content type in this package.<p>
+ * A typical scneario to call this method is to rename a template file to the main format, e.g.
+ * <ul>
+ * <li>".dotx" to ".docx"</li>
+ * <li>".dotm" to ".docm"</li>
+ * <li>".xltx" to ".xlsx"</li>
+ * <li>".xltm" to ".xlsm"</li>
+ * <li>".potx" to ".pptx"</li>
+ * <li>".potm" to ".pptm"</li>
+ * </ul>
* For example, a code converting a .xlsm macro workbook to .xlsx would look as follows:
- * <p>
- * <pre><code>
+ * <pre>{@code
*
- * OPCPackage pkg = OPCPackage.open(new FileInputStream("macro-workbook.xlsm"));
- * pkg.replaceContentType(
- * "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
- * "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
+ * OPCPackage pkg = OPCPackage.open(new FileInputStream("macro-workbook.xlsm"));
+ * pkg.replaceContentType(
+ * "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
+ * "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
*
- * FileOutputStream out = new FileOutputStream("workbook.xlsx");
- * pkg.save(out);
- * out.close();
+ * FileOutputStream out = new FileOutputStream("workbook.xlsx");
+ * pkg.save(out);
+ * out.close();
*
- * </code></pre>
- * </p>
+ * }</pre>
*
* @param oldContentType the content type to be replaced
* @param newContentType the replacement
/**
* Specifies package access.
- *
- * @author Julien Chable
* @version 1.0
*/
public enum PackageAccess {
/**
* Open Packaging Convention namespaces URI.
*
- * @author Julien Chable
* @version 1.0
*/
public interface PackageNamespaces {
* @param relationshipType
* Type of relationship.
* @return The newly created and added relationship
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String,
- * java.lang.String)
*/
+ @Override
public PackageRelationship addExternalRelationship(String target,
String relationshipType) {
return addExternalRelationship(target, relationshipType, null);
* @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String,
* java.lang.String)
*/
+ @Override
public PackageRelationship addExternalRelationship(String target,
String relationshipType, String id) {
if (target == null) {
* @param relationshipType
* Type of relationship.
* @return The newly created and added relationship
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#addRelationship(org.apache.poi.openxml4j.opc.PackagePartName,
- * org.apache.poi.openxml4j.opc.TargetMode, java.lang.String)
*/
+ @Override
public PackageRelationship addRelationship(PackagePartName targetPartName,
TargetMode targetMode, String relationshipType) {
return addRelationship(targetPartName, targetMode, relationshipType,
* invalid nested relations are created.
* @throws IllegalArgumentException if targetPartName, targetMode
* or relationshipType are passed as null
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#addRelationship(org.apache.poi.openxml4j.opc.PackagePartName,
- * org.apache.poi.openxml4j.opc.TargetMode, java.lang.String, java.lang.String)
*/
+ @Override
public PackageRelationship addRelationship(PackagePartName targetPartName,
TargetMode targetMode, String relationshipType, String id) {
_container.throwExceptionIfReadOnly();
targetMode, relationshipType, id);
}
- /**
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#clearRelationships()
- */
+ @Override
public void clearRelationships() {
if (_relationships != null) {
_relationships.clear();
*
* @param id
* The ID identified the part to delete.
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#removeRelationship(java.lang.String)
*/
+ @Override
public void removeRelationship(String id) {
this._container.throwExceptionIfReadOnly();
if (this._relationships != null)
* @return This part's relationships.
* @throws InvalidOperationException
* Throws if the package is open en write only mode.
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationships()
*/
+ @Override
public PackageRelationshipCollection getRelationships()
throws InvalidFormatException {
return getRelationshipsCore(null);
* @param id
* ID of the package relationship to retrieve.
* @return The package relationship
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationship(java.lang.String)
*/
+ @Override
public PackageRelationship getRelationship(String id) {
return this._relationships.getRelationshipByID(id);
}
* If an error occurs while parsing the part.
* @throws InvalidOperationException
* If the package is open in write only mode.
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationshipsByType(java.lang.String)
*/
+ @Override
public PackageRelationshipCollection getRelationshipsByType(
String relationshipType) throws InvalidFormatException {
_container.throwExceptionIfWriteOnly();
*
* @return <b>true</b> if the part have at least one relationship else
* <b>false</b>.
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#hasRelationships()
*/
+ @Override
public boolean hasRelationships() {
return (!this._isRelationshipPart && (_relationships != null && _relationships
.size() > 0));
* The relationship to check.
* @return <b>true</b> if the specified relationship exists in this part,
* else returns <b>false</b>
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#isRelationshipExists(org.apache.poi.openxml4j.opc.PackageRelationship)
*/
+ @Override
public boolean isRelationshipExists(PackageRelationship rel) {
return rel != null && _relationships.getRelationshipByID(rel.getId()) != null;
}
* Get the input stream of this part to read its content.
*
* @return The input stream of the content of this part, else
- * <code>null</code>.
+ * {@code null}.
*
* @throws IOException If creating the input-stream fails.
*/
/**
* Represents the core properties of an OPC package.
- *
- * @author Julien Chable
+ *
* @version 1.0
* @see org.apache.poi.openxml4j.opc.OPCPackage
*/
/**
* A part relationship.
- *
- * @author Julien Chable
* @version 1.0
*/
public final class PackageRelationship {
/**
* Represents a collection of PackageRelationship elements that are owned by a
* given PackagePart or the Package.
- *
- * @author Julien Chable, CDubettier
- * @version 0.1
*/
public final class PackageRelationshipCollection implements Iterable<PackageRelationship> {
/**
* Helper for part and pack URI.
*
- * @author Julien Chable, CDubet, Kim Ung
* @version 0.1
*/
public final class PackagingURIHelper {
* Type of relationship.
* @return The newly created and added relationship
*/
- public abstract PackageRelationship addRelationship(
+ PackageRelationship addRelationship(
PackagePartName targetPartName, TargetMode targetMode,
String relationshipType);
* @param id
* Relationship unique id.
* @return The newly created and added relationship
- *
- * @throws InvalidFormatException
- * If the URI point to a relationship part URI.
*/
- public abstract PackageRelationship addRelationship(
+ PackageRelationship addRelationship(
PackagePartName targetPartName, TargetMode targetMode,
String relationshipType, String id);
* @param target External target of the relationship
* @param relationshipType Type of relationship.
* @return The newly created and added relationship
- * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, java.lang.String)
*/
- public PackageRelationship addExternalRelationship(String target, String relationshipType);
+ PackageRelationship addExternalRelationship(String target, String relationshipType);
/**
* Adds an external relationship to a part
* @return The newly created and added relationship
* @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, java.lang.String)
*/
- public PackageRelationship addExternalRelationship(String target, String relationshipType, String id);
+ PackageRelationship addExternalRelationship(String target, String relationshipType, String id);
/**
* Delete all the relationships attached to this.
*/
- public abstract void clearRelationships();
+ void clearRelationships();
/**
* Delete the relationship specified by its id.
* @param id
* The ID identified the part to delete.
*/
- public abstract void removeRelationship(String id);
+ void removeRelationship(String id);
/**
* Retrieve all the relationships attached to this.
*
* @return This part's relationships.
- * @throws OpenXML4JException
*/
- public abstract PackageRelationshipCollection getRelationships()
- throws InvalidFormatException, OpenXML4JException;
+ PackageRelationshipCollection getRelationships() throws OpenXML4JException;
/**
* Retrieves a package relationship from its id.
* ID of the package relationship to retrieve.
* @return The package relationship
*/
- public abstract PackageRelationship getRelationship(String id);
+ PackageRelationship getRelationship(String id);
/**
* Retrieve all relationships attached to this part which have the specified
* @throws InvalidOperationException
* If the package is open in write only mode.
*/
- public abstract PackageRelationshipCollection getRelationshipsByType(
- String relationshipType) throws InvalidFormatException,
- IllegalArgumentException, OpenXML4JException;
+ PackageRelationshipCollection getRelationshipsByType(String relationshipType)
+ throws IllegalArgumentException, OpenXML4JException;
/**
* Knows if the part have any relationships.
* @return <b>true</b> if the part have at least one relationship else
* <b>false</b>.
*/
- public abstract boolean hasRelationships();
+ boolean hasRelationships();
/**
* Checks if the specified relationship is part of this package part.
* @return <b>true</b> if the specified relationship exists in this part,
* else returns <b>false</b>
*/
- public abstract boolean isRelationshipExists(PackageRelationship rel);
+ boolean isRelationshipExists(PackageRelationship rel);
}
package org.apache.poi.openxml4j.opc;
/**
- * Specifies whether the target of a PackageRelationship is inside or outside a
- * Package.
+ * Specifies whether the target of a PackageRelationship is inside or outside a Package.
*
- * @author Julien Chable
* @version 1.0
*/
public enum TargetMode {
/**
* Zip implementation of a PackagePart.
*
- * @author Julien Chable
* @version 1.0
* @see PackagePart
*/
* retrieving a part from a package; format designers shall specify only such
* content types for inclusion in the format.
* </p>
- * @author Julien Chable
- * @version 0.1
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">http://www.ietf.org/rfc/rfc2045.txt</a>
* @see <a href="http://www.ietf.org/rfc/rfc2616.txt">http://www.ietf.org/rfc/rfc2616.txt</a>
/**
* Manage package content types ([Content_Types].xml part).
- *
- * @author Julien Chable
*/
public abstract class ContentTypeManager {
/**
* Provide useful method to manage file.
- *
- * @author Julien Chable
* @version 0.1
*/
public final class FileHelper {
FileOutputStream fos = new FileOutputStream(out);
FileChannel sourceChannel = fis.getChannel();
FileChannel destinationChannel = fos.getChannel()) {
-
+
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
}
}
/**
* Memory version of a package part. Use to
- *
- * @author Julien Chable
+ *
* @version 1.0
*/
public final class MemoryPackagePart extends PackagePart {
/**
* Constructor.
- *
+ *
* @param pack
* The owner package.
* @param partName
/**
* Constructor.
- *
+ *
* @param pack
* The owner package.
* @param partName
} catch(IOException e) {
throw new InvalidFormatException(e.getMessage());
}
-
+
// Save it
data = baos.toByteArray();
-
+
// All done
return true;
}
/**
* Build an output stream for MemoryPackagePart.
- *
- * @author Julien Chable
*/
public final class MemoryPackagePartOutputStream extends OutputStream {
/**
* Represents the core properties part of a package.
- *
- * @author Julien Chable
*/
public final class PackagePropertiesPart extends PackagePart implements PackageProperties {
* marshaller is responsible to marshall a part in order to be save in a
* package.
*
- * @author Julien Chable
* @version 0.1
*/
public interface PartMarshaller {
* Classes implementing this interface are considered as part unmarshaller. A part
* unmarshaller is responsible to unmarshall a part in order to load it from a
* package.
- *
- * @author Julien Chable
- * @version 0.1
*/
public interface PartUnmarshaller {
/**
* Zip implementation of the ContentTypeManager.
*
- * @author Julien Chable
* @version 1.0
* @see ContentTypeManager
*/
/**
* Default marshaller that specified that the part is responsible to marshall its content.
*
- * @author Julien Chable
* @version 1.0
* @see PartMarshaller
*/
/**
* Package core properties marshaller specialized for zipped package.
- *
- * @author Julien Chable
*/
public final class ZipPackagePropertiesMarshaller extends PackagePropertiesMarshaller {
/**
* Package properties unmarshaller.
- *
- * @author Julien Chable
*/
public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
/**
* Context needed for the unmarshall process of a part. This class is immutable.
- *
- * @author Julien Chable
+ *
* @version 1.0
*/
public final class UnmarshallContext {
/**
* Constructor.
- *
+ *
* @param targetPackage
* Container.
* @param partName
/**
* Signature Facet implementation to create enveloped signatures.
- *
- * @author Frank Cornelis
*/
public class EnvelopedSignatureFacet implements SignatureFacet {
/**
* Signature Facet implementation that adds ds:KeyInfo to the XML signature.
- *
- * @author Frank Cornelis
*/
public class KeyInfoSignatureFacet implements SignatureFacet {
* Work-around for Office2010 to accept the XAdES-BES/EPES signature.
*
* xades:UnsignedProperties/xades:UnsignedSignatureProperties needs to be present.
- *
- * @author Frank Cornelis
*/
public class Office2010SignatureFacet implements SignatureFacet {
* This implementation has been tested against an implementation that
* participated multiple ETSI XAdES plugtests.
*
- * @author Frank Cornelis
* @see <a href="http://en.wikipedia.org/wiki/XAdES">XAdES</a>
*
*/
* This implementation has been tested against an implementation that
* participated multiple ETSI XAdES plugtests.
*
- * @author Frank Cornelis
* @see XAdESSignatureFacet
*/
public class XAdESXLSignatureFacet implements SignatureFacet {
/* ====================================================================
This product contains an ASLv2 licensed version of the OOXML signer
package from the eID Applet project
- http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
Copyright (C) 2008-2014 FedICT.
- ================================================================= */
+ ================================================================= */
package org.apache.poi.poifs.crypt.dsig.services;
/**
* Container class for PKI revocation data.
- *
- * @author Frank Cornelis
- *
*/
public class RevocationData {
/**
* Adds a CRL to this revocation data set.
- *
+ *
* @param encodedCrl
*/
public void addCRL(byte[] encodedCrl) {
/**
* Adds a CRL to this revocation data set.
- *
+ *
* @param crl
*/
public void addCRL(X509CRL crl) {
/**
* Adds an OCSP response to this revocation data set.
- *
+ *
* @param encodedOcsp
*/
public void addOCSP(byte[] encodedOcsp) {
/**
* Gives back a list of all CRLs.
- *
+ *
* @return a list of all CRLs
*/
public List<byte[]> getCRLs() {
/**
* Gives back a list of all OCSP responses.
- *
+ *
* @return a list of all OCSP response
*/
public List<byte[]> getOCSPs() {
/**
* Returns <code>true</code> if this revocation data set holds OCSP
* responses.
- *
+ *
* @return <code>true</code> if this revocation data set holds OCSP
* responses.
*/
/**
* Returns <code>true</code> if this revocation data set holds CRLs.
- *
+ *
* @return <code>true</code> if this revocation data set holds CRLs.
*/
public boolean hasCRLs() {
/**
* Returns <code>true</code> if this revocation data is not empty.
- *
+ *
* @return <code>true</code> if this revocation data is not empty.
*/
public boolean hasRevocationDataEntries() {
/* ====================================================================
This product contains an ASLv2 licensed version of the OOXML signer
package from the eID Applet project
- http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
Copyright (C) 2008-2014 FedICT.
- ================================================================= */
+ ================================================================= */
package org.apache.poi.poifs.crypt.dsig.services;
/**
* Interface for a service that retrieves revocation data about some given
* certificate chain.
- *
- * @author Frank Cornelis
- *
*/
public interface RevocationDataService {
/**
* Gives back the revocation data corresponding with the given certificate
* chain.
- *
+ *
* @param certificateChain the certificate chain
* @return the revocation data corresponding with the given certificate chain.
*/
/* ====================================================================
This product contains an ASLv2 licensed version of the OOXML signer
package from the eID Applet project
- http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
Copyright (C) 2008-2014 FedICT.
- ================================================================= */
+ ================================================================= */
package org.apache.poi.poifs.crypt.dsig.services;
/**
* Interface for the signature policy service.
- *
- * @author Frank Cornelis
- *
*/
public interface SignaturePolicyService {
/**
* Gives back the signature policy identifier URI.
- *
+ *
* @return the signature policy identifier URI.
*/
String getSignaturePolicyIdentifier();
/**
* Gives back the short description of the signature policy or
* <code>null</code> if a description is not available.
- *
+ *
* @return the description, or <code>null</code>.
*/
String getSignaturePolicyDescription();
* Gives back the download URL where the signature policy document can be
* found. Can be <code>null</code> in case such a download location does not
* exist.
- *
+ *
* @return the download URL, or <code>null</code>.
*/
String getSignaturePolicyDownloadUrl();
/**
* Gives back the signature policy document.
- *
+ *
* @return the bytes of the signature policy document.
*/
byte[] getSignaturePolicyDocument();
/**
* A TSP time-stamp service implementation.
- *
- * @author Frank Cornelis
- *
*/
public class TSPTimeStampService implements TimeStampService {
/**
* Interface for a time-stamp service.
- *
- * @author Frank Cornelis
*/
public interface TimeStampService {
/* ====================================================================
This product contains an ASLv2 licensed version of the OOXML signer
package from the eID Applet project
- http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
Copyright (C) 2008-2014 FedICT.
- ================================================================= */
+ ================================================================= */
package org.apache.poi.poifs.crypt.dsig.services;
/**
* Interface for trust validator of a TSP.
- *
- * @author Frank Cornelis
- *
*/
public interface TimeStampServiceValidator {
/**
* Validates the given certificate chain.
- *
+ *
* @param certificateChain
* @param revocationData
* the optional data container that should be filled with
* Taken (with permission) from https://gist.github.com/msteiger/4509119,
* including the fixes that are discussed in the comments
*
- * @author Martin Steiger
- *
* @see <a href="https://stackoverflow.com/questions/14258206/">Gradient paints not working in Apache Batik's svggen</a>
* @see <a href="https://issues.apache.org/jira/browse/BATIK-1032">BATIK-1032</a>
*/
/**
* Used internally to navigate the PresentationML text style hierarchy and fetch properties
- *
- * @author Yegor Kozlov
*/
@Internal
public abstract class PropertyFetcher<T> {
/**
* Date: 11/5/11
- *
- * @author Yegor Kozlov
*/
public enum SlideLayout {
/**
/**
* Represents a shape with a preset geometry.
- *
- * @author Yegor Kozlov
*/
@Beta
public class XSLFAutoShape extends XSLFTextShape implements AutoShape<XSLFShape, XSLFTextParagraph> {
/**
* Specifies a connection shape.
- *
- * @author Yegor Kozlov
*/
@Beta
public class XSLFConnectorShape extends XSLFSimpleShape
/**
* Represents a group shape that consists of many shapes grouped together.
- *
- * @author Yegor Kozlov
*/
@Beta
public class XSLFGroupShape extends XSLFShape
* their attached text bodies. Then the notesStyles element specifies the
* formatting for the text within each of these shapes.
* </p>
- *
- * @author Yegor Kozlov
*/
@Beta
public class XSLFNotesMaster extends XSLFSheet
/**
* Represents a shadow of a shape. For now supports only outer shadows.
- *
- * @author Yegor Kozlov
*/
public class XSLFShadow extends XSLFShape implements Shadow<XSLFShape,XSLFTextParagraph> {
@Beta
public abstract class XSLFSheet extends POIXMLDocumentPart
implements XSLFShapeContainer, Sheet<XSLFShape,XSLFTextParagraph> {
- private static Logger LOG = LogManager.getLogger(XSLFSheet.class);
+ private static final Logger LOG = LogManager.getLogger(XSLFSheet.class);
private XSLFDrawing _drawing;
private List<XSLFShape> _shapes;
* it is unchanged.
*
* @param xShape shape to be removed from this sheet, if present
- * @return <tt>true</tt> if this sheet contained the specified element
+ * @return {@code true} if this sheet contained the specified element
* @throws IllegalArgumentException if the type of the specified shape
* is incompatible with this sheet (optional)
*/
* Append content to this sheet.
*
* @param src the source sheet
- * @return modified <code>this</code>.
+ * @return modified {@code this}.
*/
@SuppressWarnings("unused")
public XSLFSheet appendContent(XSLFSheet src){
/**
* @return theme (shared styles) associated with this theme.
- * By default returns <code>null</code> which means that this sheet is theme-less.
+ * By default returns {@code null} which means that this sheet is theme-less.
* Sheets that support the notion of themes (slides, masters, layouts, etc.) should override this
* method and return the corresponding package part.
*/
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShapeNonVisual;
-/**
- * @author Yegor Kozlov
- */
@Beta
public class XSLFTextBox extends XSLFAutoShape implements TextBox<XSLFShape, XSLFTextParagraph> {
return WORKSHEET_RELS;
}
+ @Override
Iterator<XSSFSheetRef> createSheetIteratorFromWB(PackagePart wb) throws IOException {
SheetRefLoader sheetRefLoader = new SheetRefLoader(wb.getInputStream());
sheetRefLoader.parse();
/**
* Creates a new XSSFReader, for the given package
*
- * @param pkg an <code>OPCPackage</code> representing a spreasheet file
+ * @param pkg an {@code OPCPackage} representing a spreasheet file
* @param allowStrictOoxmlFiles whether to try to handle Strict OOXML format files
*/
public XSSFReader(OPCPackage pkg, boolean allowStrictOoxmlFiles) throws IOException, OpenXML4JException {
XSSFSheetRef xssfSheetRef;
/**
- * Iterator over CTSheet objects, returns sheets in <tt>logical</tt> order.
+ * Iterator over CTSheet objects, returns sheets in {@code logical} order.
* We can't rely on the Ooxml4J's relationship iterator because it returns objects in physical order,
* i.e. as they are stored in the underlying package
*/
}
/**
- * Returns <tt>true</tt> if the iteration has more elements.
+ * Returns {@code true} if the iteration has more elements.
*
- * @return <tt>true</tt> if the iterator has more elements.
+ * @return {@code true} if the iterator has more elements.
*/
@Override
public boolean hasNext() {
protected CommentsTable parseComments(PackagePart commentsPart) throws IOException {
return new CommentsTable(commentsPart);
}
-
+
/**
* Returns the shapes associated with this sheet,
* an empty list or null if there is an exception
/**
* The cells in a workbook can be calculated in different orders depending on various optimizations and
* dependencies. The calculation chain object specifies the order in which the cells in a workbook were last calculated.
- *
- * @author Yegor Kozlov
*/
public class CalculationChain extends POIXMLDocumentPart {
private CTCalcChain chain;
super(part);
readFrom(part.getInputStream());
}
-
+
public void readFrom(InputStream is) throws IOException {
try {
CalcChainDocument doc = CalcChainDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
/**
* Remove a formula reference from the calculation chain
- *
+ *
* @param sheetId the sheet Id of a sheet the formula belongs to.
* @param ref A1 style reference to the cell containing the formula.
*/
import org.openxmlformats.schemas.spreadsheetml.x2006.main.MapInfoDocument;
/**
- *
+ *
* This class implements the Custom XML Mapping Part (Open Office XML Part 1:
* chapter 12.3.6)
- *
+ *
* An instance of this part type contains a schema for an XML file, and
* information on the behavior that is used when allowing this custom XML schema
* to be mapped into the spreadsheet.
- *
- * @author Roberto Manicardi
*/
public class MapInfo extends POIXMLDocumentPart {
private CTMapInfo mapInfo;
-
+
private Map<Integer, XSSFMap> maps ;
public MapInfo() {
public MapInfo(PackagePart part) throws IOException {
super(part);
readFrom(part.getInputStream());
- }
-
+ }
+
public void readFrom(InputStream is) throws IOException {
try {
MapInfoDocument doc = MapInfoDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
throw new IOException(e.getLocalizedMessage());
}
}
-
+
/**
* Returns the parent XSSFWorkbook
*
public XSSFWorkbook getWorkbook() {
return (XSSFWorkbook)getParent();
}
-
+
/**
- *
+ *
* @return the internal data object
*/
public CTMapInfo getCTMapInfo(){
return mapInfo;
-
+
}
/**
}
return xmlSchema;
}
-
-
+
+
public XSSFMap getXSSFMapById(int id){
return maps.get(id);
}
-
+
public XSSFMap getXSSFMapByName(String name){
-
+
XSSFMap matchedMap = null;
-
+
for(XSSFMap map :maps.values()){
if(map.getCtMap().getName()!=null && map.getCtMap().getName().equals(name)){
matchedMap = map;
}
- }
-
+ }
+
return matchedMap;
}
-
+
/**
- *
+ *
* @return all the mappings configured in this document
*/
public Collection<XSSFMap> getAllXSSFMaps(){
/**
- *
+ *
* This class implements the Single Cell Tables Part (Open Office XML Part 4:
* chapter 3.5.2)
- *
- *
- * @author Roberto Manicardi
*/
public class SingleXmlCells extends POIXMLDocumentPart {
-
-
+
+
private CTSingleXmlCells singleXMLCells;
public SingleXmlCells() {
throw new IOException(e.getLocalizedMessage());
}
}
-
+
public XSSFSheet getXSSFSheet(){
return (XSSFSheet) getParent();
}
writeTo(out);
out.close();
}
-
+
public CTSingleXmlCells getCTSingleXMLCells(){
return singleXMLCells;
}
-
+
/**
- *
+ *
* @return all the SimpleXmlCell contained in this SingleXmlCells element
*/
public List<XSSFSingleXmlCell> getAllSimpleXmlCell(){
List<XSSFSingleXmlCell> list = new Vector<>();
-
+
for(CTSingleXmlCell singleXmlCell: singleXMLCells.getSingleXmlCellArray()){
list.add(new XSSFSingleXmlCell(singleXmlCell,this));
- }
+ }
return list;
}
}
* Drop in replacement for `java.util.ZipOutputStream`.
*
* For more information see https://github.com/rzymek/opczip
- *
- * @author Krzysztof Rzymkowski
*/
class OpcOutputStream extends DeflaterOutputStream {
/**
* Excel compatible Zip64 implementation.
* For more information see https://github.com/rzymek/opczip
- *
- * @author Krzysztof Rzymkowski
*/
class Zip64Impl {
private static final long PK0102 = 0x02014b50L;
}
}
+ @Override
@NotImplemented
public int getExternalSheetIndex(String workbookName, String sheetName) {
throw new RuntimeException("not implemented yet");
* This is meant to be used on documents whose structure is essentially static at the point formulas are evaluated.
*
* @param name the data table name (case-insensitive)
- * @return The Data table in the workbook named <tt>name</tt>, or <tt>null</tt> if no table is named <tt>name</tt>.
+ * @return The Data table in the workbook named {@code name}, or {@code null} if no table is named {@code name}.
* @since 3.15 beta 2
*/
@Override
_fpBook = fpBook;
}
+ @Override
public Ptg[] getNameDefinition() {
return FormulaParser.parse(_nameRecord.getRefersToFormula(), _fpBook, FormulaType.NAMEDRANGE, _nameRecord.getSheetIndex());
}
+ @Override
public String getNameText() {
return _nameRecord.getNameName();
}
+ @Override
public boolean hasFormula() {
// TODO - no idea if this is right
CTDefinedName ctn = _nameRecord.getCTName();
return !ctn.getFunction() && strVal != null && strVal.length() > 0;
}
+ @Override
public boolean isFunctionName() {
return _nameRecord.isFunctionName();
}
+ @Override
public boolean isRange() {
return hasFormula(); // TODO - is this right?
}
+ @Override
public NamePtg createPtg() {
return new NamePtg(_index);
}
/**
* Represents autofiltering for the specified worksheet.
- *
- * @author Yegor Kozlov
*/
public final class XSSFAutoFilter implements AutoFilter {
private XSSFSheet _sheet;
* High level representation of Sheet Parts that are of type 'chartsheet'.
* <p>
* Chart sheet is a special kind of Sheet that contains only chart and no data.
- * </p>
- *
- * @author Yegor Kozlov
*/
public class XSSFChartSheet extends XSSFSheet {
protected XSSFChartSheet(PackagePart part) {
super(part);
}
-
+
+ @Override
protected void read(InputStream is) throws IOException {
//initialize the supeclass with a blank worksheet
super.read(new ByteArrayInputStream(BLANK_WORKSHEET));
protected CTDrawing getCTDrawing() {
return chartsheet.getDrawing();
}
-
+
@Override
protected CTLegacyDrawing getCTLegacyDrawing() {
return chartsheet.getLegacyDrawing();
}
-
+
@Override
protected void write(OutputStream out) throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
-/**
- * @author Yegor Kozlov
- */
public final class XSSFChildAnchor extends XSSFAnchor {
private CTTransform2D t2d;
* @return null if color is null, new instance otherwise
*/
public static XSSFColor from(CTColor color, IndexedColorMap map) {
- //noinspection deprecation
return color == null ? null : new XSSFColor(color, map);
}
* @param colorMap The IndexedColorMap to use instead of the default one
*/
public XSSFColor(IndexedColorMap colorMap) {
- //noinspection deprecation
this(CTColor.Factory.newInstance(), colorMap);
}
* @param colorMap The IndexedColorMap to use instead of the default one
*/
public XSSFColor(byte[] rgb, IndexedColorMap colorMap) {
- //noinspection deprecation
this(CTColor.Factory.newInstance(), colorMap);
ctColor.setRgb(rgb);
}
* @param colorMap The IndexedColorMap to use instead of the default one
*/
public XSSFColor(IndexedColors indexedColor, IndexedColorMap colorMap) {
- //noinspection deprecation
this(CTColor.Factory.newInstance(), colorMap);
ctColor.setIndexed(indexedColor.index);
}
return ctColor.getRgb();
}
+ @Override
protected byte[] getIndexedRGB() {
if (isIndexed()) {
if (indexedColorMap != null) return indexedColorMap.getRGB(getIndex());
}
/**
- * Index into the <clrScheme> collection, referencing a particular <sysClr> or
- * <srgbClr> value expressed in the Theme part.
+ * Index into the {@code clrScheme} collection, referencing a particular {@code sysClr} or
+ * {@code srgbClr} value expressed in the Theme part.
*/
@Override
public int getTheme() {
}
/**
- * Index into the <clrScheme> collection, referencing a particular <sysClr> or
- * <srgbClr> value expressed in the Theme part.
+ * Index into the {@code clrScheme} collection, referencing a particular {@code sysClr} or
+ * {@code srgbClr} value expressed in the Theme part.
* @param theme index
*/
public void setTheme(int theme) {
}
/**
- * Checked type cast <tt>color</tt> to an XSSFColor.
+ * Checked type cast {@code color} to an XSSFColor.
*
* @param color the color to type cast
* @return the type casted color
import java.util.ArrayList;
import java.util.Collections;
-/**
- * @author Yegor Kozlov
- */
public class XSSFConditionalFormatting implements ConditionalFormatting {
private final CTConditionalFormatting _cf;
private final XSSFSheet _sh;
}
/**
- * @return array of <tt>CellRangeAddress</tt>s. Never <code>null</code>
+ * @return array of {@code CellRangeAddress}s. Never {@code null}
*/
@Override
public CellRangeAddress[] getFormattingRanges() {
/**
* A connection shape drawing element. A connection shape is a line, etc.
* that connects two other shapes in this drawing.
- *
- * @author Yegor Kozlov
*/
public final class XSSFConnector extends XSSFShape {
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator.Enum;
-/**
- * @author <a href="rjankiraman@emptoris.com">Radhakrishnan J</a>
- *
- */
public class XSSFDataValidation implements DataValidation {
private static final int MAX_TEXT_LENGTH = 255;
this.ctDataValidation = ctDataValidation;
this.regions = regions;
}
-
+
CTDataValidation getCtDataValidation() {
return ctDataValidation;
}
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator.Enum;
-/**
- * @author <a href="rjankiraman@emptoris.com">Radhakrishnan J</a>
- *
- */
public class XSSFDataValidationConstraint implements DataValidationConstraint {
/**
* Excel validation constraints with static lists are delimited with optional whitespace and the Windows List Separator,
}
this.validationType = ValidationType.LIST;
setExplicitListValues(explicitListOfValues);
-
+
validate();
}
-
+
public XSSFDataValidationConstraint(int validationType, String formula1) {
super();
setFormula1(formula1);
setFormula2(formula2);
this.validationType = validationType;
this.operator = operator;
-
+
validate();
-
+
//FIXME: Need to confirm if this is not a formula.
- // empirical testing shows Excel saves explicit lists surrounded by double quotes,
+ // empirical testing shows Excel saves explicit lists surrounded by double quotes,
// range formula expressions can't start with quotes (I think - anyone have a creative counter example?)
if ( ValidationType.LIST == validationType
&& this.formula1 != null
*/
public void setExplicitListValues(String[] explicitListValues) {
this.explicitListOfValues = explicitListValues;
-
+
// for OOXML we need to set formula1 to the quoted csv list of values (doesn't appear documented, but that's where Excel puts its lists)
// further, Excel has no escaping for commas in explicit lists, so we don't need to worry about that.
if ( explicitListOfValues!=null && explicitListOfValues.length > 0 ) {
builder.append(string);
}
builder.append(QUOTE);
- setFormula1(builder.toString());
+ setFormula1(builder.toString());
}
}
if (validationType==ValidationType.ANY) {
return;
}
-
+
if (validationType==ValidationType.LIST ) {
if (isFormulaEmpty(formula1)) {
throw new IllegalArgumentException("A valid formula or a list of values must be specified for list validation.");
if( isFormulaEmpty(formula1) ) {
throw new IllegalArgumentException("Formula is not specified. Formula is required for all validation types except explicit list validation.");
}
-
+
if( validationType!= ValidationType.FORMULA ) {
if (operator==-1) {
throw new IllegalArgumentException("This validation type requires an operator to be specified.");
}
}
-
+
public String prettyPrint() {
StringBuilder builder = new StringBuilder();
STDataValidationType.Enum vt = XSSFDataValidation.validationTypeMappings.get(validationType);
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType;
-/**
- * @author <a href="rjankiraman@emptoris.com">Radhakrishnan J</a>
- *
- */
public class XSSFDataValidationHelper implements DataValidationHelper {
// Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works.
//private XSSFSheet xssfSheet;
-
-
+
+
public XSSFDataValidationHelper(XSSFSheet xssfSheet) {
super();
// Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works.
return new XSSFDataValidationConstraint(ValidationType.LIST, listFormula);
}
-
-
+
+
public DataValidationConstraint createNumericConstraint(int validationType, int operatorType, String formula1, String formula2) {
if( validationType==ValidationType.INTEGER) {
return createIntegerConstraint(operatorType, formula1, formula2);
switch(validationType) {
case DataValidationConstraint.ValidationType.LIST:
newDataValidation.setType(STDataValidationType.LIST);
- newDataValidation.setFormula1(constraint.getFormula1());
+ newDataValidation.setFormula1(constraint.getFormula1());
break;
- case DataValidationConstraint.ValidationType.ANY:
- newDataValidation.setType(STDataValidationType.NONE);
+ case DataValidationConstraint.ValidationType.ANY:
+ newDataValidation.setType(STDataValidationType.NONE);
break;
case DataValidationConstraint.ValidationType.TEXT_LENGTH:
newDataValidation.setType(STDataValidationType.TEXT_LENGTH);
- break;
+ break;
case DataValidationConstraint.ValidationType.DATE:
newDataValidation.setType(STDataValidationType.DATE);
- break;
+ break;
case DataValidationConstraint.ValidationType.INTEGER:
newDataValidation.setType(STDataValidationType.WHOLE);
- break;
+ break;
case DataValidationConstraint.ValidationType.DECIMAL:
newDataValidation.setType(STDataValidationType.DECIMAL);
- break;
+ break;
case DataValidationConstraint.ValidationType.TIME:
newDataValidation.setType(STDataValidationType.TIME);
break;
newDataValidation.setType(STDataValidationType.CUSTOM);
break;
default:
- newDataValidation.setType(STDataValidationType.NONE);
+ newDataValidation.setType(STDataValidationType.NONE);
}
-
+
if (validationType!=ValidationType.ANY && validationType!=ValidationType.LIST) {
STDataValidationOperator.Enum op = XSSFDataValidation.operatorTypeMappings.get(constraint.getOperator());
if(op != null) {
newDataValidation.setFormula2(constraint.getFormula2());
}
}
-
+
CellRangeAddress[] cellRangeAddresses = cellRangeAddressList.getCellRangeAddresses();
List<String> sqref = new ArrayList<>();
for (int i = 0; i < cellRangeAddresses.length; i++) {
newDataValidation.setSqref(sqref);
newDataValidation.setAllowBlank(true);
newDataValidation.setErrorStyle(STDataValidationErrorStyle.STOP);
-
+
return new XSSFDataValidation(dataValidationConstraint,cellRangeAddressList,newDataValidation);
}
}
this.worksheet = CTWorksheet.Factory.newInstance();
}
+ @Override
public XSSFRow createRow(int rowNum) {
return null;
}
/**
* Represents a font used in a workbook.
- *
- * @author Gisella Bronzetti
*/
public class XSSFFont implements Font {
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues;
-/**
- * @author Yegor Kozlov
- */
public class XSSFFontFormatting implements FontFormatting {
private IndexedColorMap _colorMap;
private CTFont _font;
/**
* Represents DrawingML GraphicalObjectFrame.
- *
- * @author Roman Kashitsyn
*/
public final class XSSFGraphicFrame extends XSSFShape {
* <p>
* This element contains all of the properties related to the XML map,
* and the behaviors expected during data refresh operations.
- *
- * @author Roberto Manicardi
*/
-
-
public class XSSFMap {
private CTMap ctMap;
private MapInfo mapInfo;
* name2.setRefersToFormula("Sheet1!$B$3");
*
* </blockquote></pre>
- *
- * @author Nick Burch
- * @author Yegor Kozlov
*/
public final class XSSFName implements Name {
-
+
/**
* A built-in defined name that specifies the workbook's print area
*/
XSSFName cf = (XSSFName) o;
return _ctName.toString().equals(cf.getCTName().toString());
}
-
+
/**
* https://support.office.com/en-us/article/Define-and-use-names-in-formulas-4D0F13AC-53B7-422E-AFD2-ABD7FF379C64#bmsyntax_rules_for_names
- *
+ *
* Valid characters:
* First character: { letter | underscore | backslash }
* Remaining characters: { letter | number | period | underscore }
- *
+ *
* Cell shorthand: cannot be { "C" | "c" | "R" | "r" }
- *
+ *
* Cell references disallowed: cannot be a cell reference $A$1 or R1C1
- *
+ *
* Spaces are not valid (follows from valid characters above)
- *
+ *
* Name length: (XSSF-specific?) 255 characters maximum
- *
+ *
* Case sensitivity: all names are case-insensitive
- *
+ *
* Uniqueness: must be unique (for names with the same scope)
*
* @param name
*/
private static void validateName(String name) {
-
+
if (name.length() == 0) {
throw new IllegalArgumentException("Name cannot be blank");
}
if (name.equalsIgnoreCase("R") || name.equalsIgnoreCase("C")) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be special shorthand R or C");
}
-
+
// is first character valid?
char c = name.charAt(0);
String allowedSymbols = "_\\";
if (!characterIsValid) {
throw new IllegalArgumentException("Invalid name: '"+name+"': first character must be underscore or a letter");
}
-
+
// are all other characters valid?
allowedSymbols = "_.\\"; //backslashes needed for unicode escape
for (final char ch : name.toCharArray()) {
throw new IllegalArgumentException("Invalid name: '"+name+"': name must be letter, digit, period, or underscore");
}
}
-
+
// Is the name a valid $A$1 cell reference
// Because $, :, and ! are disallowed characters, A1-style references become just a letter-number combination
if (name.matches("[A-Za-z]+\\d+")) {
String col = name.replaceAll("\\d", "");
String row = name.replaceAll("[A-Za-z]", "");
-
+
try {
if (CellReference.cellReferenceIsWithinRange(col, row, SpreadsheetVersion.EXCEL2007)) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be $A$1-style cell reference");
// therefore name passes the not-a-cell-reference criteria
}
}
-
+
// Is the name a valid R1C1 cell reference?
if (name.matches("[Rr]\\d+[Cc]\\d+")) {
throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be R1C1-style cell reference");
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType;
-/**
- * @author Yegor Kozlov
- */
public class XSSFPatternFormatting implements PatternFormatting {
IndexedColorMap _colorMap;
CTFill _fill;
ptrn.setBgColor(color);
}
}
-
+
public void setFillForegroundColor(Color fg) {
XSSFColor xcolor = XSSFColor.toXSSFColor(fg);
if (xcolor == null) setFillForegroundColor((CTColor)null);
/**
* Represents a picture shape in a SpreadsheetML drawing.
- *
- * @author Yegor Kozlov
*/
public final class XSSFPicture extends XSSFShape implements Picture {
private static final Logger LOG = LogManager.getLogger(XSSFPicture.class);
* Kept for backwards-compatibility, use {@link Font#TWIPS_PER_POINT} instead.
* @deprecated POI 5.0.0
*/
+ @Deprecated
public static final int TWIPS_PER_POINT = Font.TWIPS_PER_POINT;
//TODO make the two variable below private!
* @param region to merge
* @param validate whether to validate merged region
* @return 0-based index of this region
- * @throws IllegalArgumentException if region contains fewer than 2 cells (this check is inexpensive and is performed regardless of <tt>validate</tt>)
+ * @throws IllegalArgumentException if region contains fewer than 2 cells (this check is inexpensive and is performed regardless of {@code validate})
* @throws IllegalStateException if region intersects with a multi-cell array formula
* @throws IllegalStateException if region intersects with an existing region on this sheet
*/
*
* @param autoCreate if true, then a new VML drawing part is created
*
- * @return the VML drawing of <code>null</code> if the drawing was not found and autoCreate=false
+ * @return the VML drawing of {@code null} if the drawing was not found and autoCreate=false
*/
protected XSSFVMLDrawing getVMLDrawing(boolean autoCreate) {
XSSFVMLDrawing drawing = null;
* Vertical page break information used for print layout view, page layout view, drawing print breaks
* in normal view, and for printing the worksheet.
*
- * @return column indexes of all the vertical page breaks, never <code>null</code>
+ * @return column indexes of all the vertical page breaks, never {@code null}
*/
@Override
public int[] getColumnBreaks() {
/**
* Flag indicating whether the Fit to Page print option is enabled.
*
- * @return <code>true</code>
+ * @return {@code true}
*/
@Override
public boolean getFitToPage() {
* Also sets some attributes on the {@link CTSheetProtection} that correspond to
* the default values used by Excel
*
- * @param password to set for protection. Pass <code>null</code> to remove protection
+ * @param password to set for protection. Pass {@code null} to remove protection
*/
@Override
public void protectSheet(String password) {
* defined you get a null. This is to say row 4 represents the fifth row on a sheet.
*
* @param rownum row to get
- * @return <code>XSSFRow</code> representing the rownumber or <code>null</code> if its not defined on the sheet
+ * @return {@code XSSFRow} representing the rownumber or {@code null} if its not defined on the sheet
*/
@Override
public XSSFRow getRow(int rownum) {
* Horizontal page break information used for print layout view, page layout view, drawing print breaks in normal
* view, and for printing the worksheet.
*
- * @return row indexes of all the horizontal page breaks, never <code>null</code>
+ * @return row indexes of all the horizontal page breaks, never {@code null}
*/
@Override
public int[] getRowBreaks() {
* When false a summary row is inserted above the detailed data being summarized and a new outline level
* is established on that row.
* </p>
- * @return <code>true</code> if row summaries appear below detail in the outline
+ * @return {@code true} if row summaries appear below detail in the outline
*/
@Override
public boolean getRowSumsBelow() {
* When false a summary row is inserted above the detailed data being summarized and a new outline level
* is established on that row.
* </p>
- * @param value <code>true</code> if row summaries appear below detail in the outline
+ * @param value {@code true} if row summaries appear below detail in the outline
*/
@Override
public void setRowSumsBelow(boolean value) {
* When false a summary column is inserted to the left of the detailed data being
* summarized and a new outline level is established on that column.
* </p>
- * @return <code>true</code> if col summaries appear right of the detail in the outline
+ * @return {@code true} if col summaries appear right of the detail in the outline
*/
@Override
public boolean getRowSumsRight() {
* When false a summary column is inserted to the left of the detailed data being
* summarized and a new outline level is established on that column.
* </p>
- * @param value <code>true</code> if col summaries appear right of the detail in the outline
+ * @param value {@code true} if col summaries appear right of the detail in the outline
*/
@Override
public void setRowSumsRight(boolean value) {
* Get the hidden state for a given column.
*
* @param columnIndex - the column to set (0-based)
- * @return hidden - <code>false</code> if the column is visible
+ * @return hidden - {@code false} if the column is visible
*/
@Override
public boolean isColumnHidden(int columnIndex) {
/**
* Gets the flag indicating whether this sheet should display formulas.
*
- * @return <code>true</code> if this sheet should display formulas.
+ * @return {@code true} if this sheet should display formulas.
*/
@Override
public boolean isDisplayFormulas() {
* Gets the flag indicating whether this sheet displays the lines
* between rows and columns to make editing and reading easier.
*
- * @return <code>true</code> (default) if this sheet displays gridlines.
+ * @return {@code true} (default) if this sheet displays gridlines.
* @see #isPrintGridlines() to check if printing of gridlines is turned on or off
*/
@Override
* To turn printing of gridlines use {@link #setPrintGridlines(boolean)}
*
*
- * @param show <code>true</code> if this sheet should display gridlines.
+ * @param show {@code true} if this sheet should display gridlines.
* @see #setPrintGridlines(boolean)
*/
@Override
* Column heading are the letters or numbers that appear above the columns of the sheet
* </p>
*
- * @return <code>true</code> (default) if this sheet should display row and column headings.
+ * @return {@code true} (default) if this sheet should display row and column headings.
*/
@Override
public boolean isDisplayRowColHeadings() {
* Column heading are the letters or numbers that appear above the columns of the sheet
* </p>
*
- * @param show <code>true</code> if this sheet should display row and column headings.
+ * @param show {@code true} if this sheet should display row and column headings.
*/
@Override
public void setDisplayRowColHeadings(boolean show) {
* Tests if there is a page break at the indicated row
*
* @param row index of the row to test
- * @return <code>true</code> if there is a page break at the indicated row
+ * @return {@code true} if there is a page break at the indicated row
*/
@Override
public boolean isRowBroken(int row) {
* Sets a page break at the indicated row
* Breaks occur above the specified row and left of the specified column inclusive.
*
- * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
- * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
+ * For example, {@code sheet.setColumnBreak(2);} breaks the sheet into two parts
+ * with columns A,B,C in the first and D,E,... in the second. Simuilar, {@code sheet.setRowBreak(2);}
* breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
* and rows starting with rownum=4 in the second.
*
/**
* Flag indicating whether the sheet displays Automatic Page Breaks.
*
- * @return <code>true</code> if the sheet displays Automatic Page Breaks.
+ * @return {@code true} if the sheet displays Automatic Page Breaks.
*/
@Override
public boolean getAutobreaks() {
/**
* Flag indicating whether the sheet displays Automatic Page Breaks.
*
- * @param value <code>true</code> if the sheet displays Automatic Page Breaks.
+ * @param value {@code true} if the sheet displays Automatic Page Breaks.
*/
@Override
public void setAutobreaks(boolean value) {
* Sets a page break at the indicated column.
* Breaks occur above the specified row and left of the specified column inclusive.
*
- * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
- * with columns A,B,C in the first and D,E,... in the second. Simuilar, <code>sheet.setRowBreak(2);</code>
+ * For example, {@code sheet.setColumnBreak(2);} breaks the sheet into two parts
+ * with columns A,B,C in the first and D,E,... in the second. Simuilar, {@code sheet.setRowBreak(2);}
* breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
* and rows starting with rownum=4 in the second.
*
*
* <p>
* Character width is defined as the maximum digit width
- * of the numbers <code>0, 1, 2, ... 9</code> as rendered
+ * of the numbers {@code 0, 1, 2, ... 9} as rendered
* using the default font (first font in the workbook).
* <br>
* Unless you are using a very special font, the default character is '0' (zero),
* To compute the actual number of visible characters,
* Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):
* </p>
- * <code>
+ * {@code
* width = Truncate([{Number of Visible Characters} *
* {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
- * </code>
+ * }
* <p>Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).
- * If you set a column width to be eight characters wide, e.g. <code>setColumnWidth(columnIndex, 8*256)</code>,
+ * If you set a column width to be eight characters wide, e.g. {@code setColumnWidth(columnIndex, 8*256)},
* then the actual value of visible characters (the value shown in Excel) is derived from the following equation:
- * <code>
+ * {@code
Truncate([numChars*7+5]/7*256)/256 = 8;
- * </code>
+ * }
*
- * which gives <code>7.29</code>.
+ * which gives {@code 7.29}.
*
* @param columnIndex - the column to set (0-based)
* @param width - the width in units of 1/256th of a character width
* This value does not include margin padding or extra padding for gridlines. It is only the
* number of characters.
*
- * @param width the number of characters. Default value is <code>8</code>.
+ * @param width the number of characters. Default value is {@code 8}.
*/
@Override
public void setDefaultColumnWidth(int width) {
/**
* Sets the flag indicating whether this sheet should display formulas.
*
- * @param show <code>true</code> if this sheet should display formulas.
+ * @param show {@code true} if this sheet should display formulas.
*/
@Override
public void setDisplayFormulas(boolean show) {
/**
* Flag indicating whether the Fit to Page print option is enabled.
*
- * @param b <code>true</code> if the Fit to Page print option is enabled.
+ * @param b {@code true} if the Fit to Page print option is enabled.
*/
@Override
public void setFitToPage(boolean b) {
* </p>
* Note: multiple sheets can be selected, but only one sheet can be active at one time.
*
- * @return <code>true</code> if this sheet is selected
+ * @return {@code true} if this sheet is selected
*/
@Override
public boolean isSelected() {
* </p>
* Note: multiple sheets can be selected, but only one sheet can be active at one time.
*
- * @param value <code>true</code> if this sheet is selected
+ * @param value {@code true} if this sheet is selected
*/
@Override
public void setSelected(boolean value) {
}
/**
- * Return location of the active cell, e.g. <code>A1</code>.
+ * Return location of the active cell, e.g. {@code A1}.
*
* @return the location of the active cell.
*/
* Return a master shared formula by index
*
* @param sid shared group index
- * @return a CTCellFormula bean holding shared formula or <code>null</code> if not found
+ * @return a CTCellFormula bean holding shared formula or {@code null} if not found
*/
@Internal
public CTCellFormula getSharedFormula(int sid){
/**
* Get background color of the sheet tab.
- * Returns <tt>null</tt> if no sheet tab color is set.
+ * Returns {@code null} if no sheet tab color is set.
*
* @return the background color of the sheet tab
*/
* TODO - formulas containing cell references are currently not parsed properly
*
* @param comparisonOperation - a constant value from
- * <tt>{@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}</tt>: <p>
+ * {@code {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}}:
* <ul>
* <li>BETWEEN</li>
* <li>NOT_BETWEEN</li>
* <li>GE</li>
* <li>LE</li>
* </ul>
- * </p>
+ *
* @param formula1 - formula for the valued, compared with the cell
* @param formula2 - second formula (only used with
* {@link org.apache.poi.ss.usermodel.ComparisonOperator#BETWEEN}) and
* {@link org.apache.poi.ss.usermodel.ComparisonOperator#NOT_BETWEEN} operations)
*/
+ @Override
public XSSFConditionalFormattingRule createConditionalFormattingRule(
byte comparisonOperation,
String formula1,
return rule;
}
+ @Override
public XSSFConditionalFormattingRule createConditionalFormattingRule(
byte comparisonOperation,
String formula) {
*
* @param formula - formula for the valued, compared with the cell
*/
+ @Override
public XSSFConditionalFormattingRule createConditionalFormattingRule(String formula) {
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
CTCfRule cfRule = rule.getCTCfRule();
/**
* Create a Databar conditional formatting rule.
- * <p>The thresholds and colour for it will be created, but will be
- * empty and require configuring with
+ * <p>The thresholds and colour for it will be created, but will be
+ * empty and require configuring with
* {@link XSSFConditionalFormattingRule#getDataBarFormatting()}
* then
* {@link XSSFDataBarFormatting#getMinThreshold()}
- * and
+ * and
* {@link XSSFDataBarFormatting#getMaxThreshold()}
*/
public XSSFConditionalFormattingRule createConditionalFormattingRule(XSSFColor color) {
// All done!
return rule;
}
+ @Override
public XSSFConditionalFormattingRule createConditionalFormattingRule(ExtendedColor color) {
return createConditionalFormattingRule((XSSFColor)color);
}
* A factory method allowing the creation of conditional formatting
* rules using an Icon Set / Multi-State formatting.
* The thresholds for it will be created, but will be empty
- * and require configuring with
+ * and require configuring with
* {@link XSSFConditionalFormattingRule#getMultiStateFormatting()}
* then
* {@link XSSFIconMultiStateFormatting#getThresholds()}
*/
+ @Override
public XSSFConditionalFormattingRule createConditionalFormattingRule(IconSet iconSet) {
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
/**
* Create a Color Scale / Color Gradient conditional formatting rule.
- * <p>The thresholds and colours for it will be created, but will be
- * empty and require configuring with
+ * <p>The thresholds and colours for it will be created, but will be
+ * empty and require configuring with
* {@link XSSFConditionalFormattingRule#getColorScaleFormatting()}
* then
* {@link XSSFColorScaleFormatting#getThresholds()}
* and
* {@link XSSFColorScaleFormatting#getColors()}
*/
+ @Override
public XSSFConditionalFormattingRule createConditionalFormattingColorScaleRule() {
XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet);
return rule;
}
+ @Override
public int addConditionalFormatting(CellRangeAddress[] regions, ConditionalFormattingRule[] cfRules) {
if (regions == null) {
throw new IllegalArgumentException("regions must not be null");
return _sheet.getCTWorksheet().sizeOfConditionalFormattingArray() - 1;
}
+ @Override
public int addConditionalFormatting(CellRangeAddress[] regions,
ConditionalFormattingRule rule1)
{
});
}
+ @Override
public int addConditionalFormatting(CellRangeAddress[] regions,
ConditionalFormattingRule rule1, ConditionalFormattingRule rule2)
{
* @param cf HSSFConditionalFormatting object
* @return index of the new Conditional Formatting object
*/
+ @Override
public int addConditionalFormatting( ConditionalFormatting cf ) {
XSSFConditionalFormatting xcf = (XSSFConditionalFormatting)cf;
CTWorksheet sh = _sheet.getCTWorksheet();
* of the Conditional Formatting object to fetch
* @return Conditional Formatting object
*/
+ @Override
public XSSFConditionalFormatting getConditionalFormattingAt(int index) {
checkIndex(index);
CTConditionalFormatting cf = _sheet.getCTWorksheet().getConditionalFormattingArray(index);
/**
* @return number of Conditional Formatting objects of the sheet
*/
+ @Override
public int getNumConditionalFormattings() {
return _sheet.getCTWorksheet().sizeOfConditionalFormattingArray();
}
* removes a Conditional Formatting object by index
* @param index of a Conditional Formatting object to remove
*/
+ @Override
public void removeConditionalFormatting(int index) {
checkIndex(index);
_sheet.getCTWorksheet().removeConditionalFormatting(index);
import org.openxmlformats.schemas.spreadsheetml.x2006.main.TableDocument;
/**
- *
+ *
* This class implements the Table Part (Open Office XML Part 4: chapter 3.5.1)
- *
+ *
* Columns of this table may contains mappings to a subtree of an XML. The root
* element of this subtree can occur multiple times (one for each row of the
* table). The child nodes of the root element can be only attributes or
* elements with maxOccurs=1 property set.
- *
- *
- * @author Roberto Manicardi
*/
public class XSSFTable extends POIXMLDocumentPart implements Table {
private transient List<XSSFTableColumn> tableColumns;
private transient HashMap<String, Integer> columnMap;
private transient CellReference startCellReference;
- private transient CellReference endCellReference;
- private transient String commonXPath;
+ private transient CellReference endCellReference;
+ private transient String commonXPath;
private transient String name;
private transient String styleName;
ctTable = CTTable.Factory.newInstance();
}
- /**
+ /**
* @param part The part used to initialize the table
* @throws IOException If reading data from the part fails.
* @since POI 3.14-Beta1
super(part);
readFrom(part.getInputStream());
}
-
+
/**
* Read table XML from an {@link InputStream}
* @param is The stream which provides the XML data for the table.
throw new IOException(e.getLocalizedMessage());
}
}
-
+
/**
* @return owning sheet
*/
writeTo(out);
out.close();
}
-
+
/**
* get the underlying CTTable XML bean
* @return underlying OOXML object
public CTTable getCTTable() {
return ctTable;
}
-
+
/**
* Checks if this Table element contains even a single mapping to the map identified by id
* @param id the XSSFMap ID
*/
public boolean mapsTo(long id){
List<XSSFXmlColumnPr> pointers = getXmlColumnPrs();
-
+
for (XSSFXmlColumnPr pointer: pointers) {
if (pointer.getMapId()==id) {
return true;
}
}
-
+
return false;
}
-
+
/**
- *
+ *
* Calculates the xpath of the root element for the table. This will be the common part
* of all the mapping's xpaths
* Note: this function caches the result for performance. To flush the cache {@link #updateHeaders()} must be called.
- *
+ *
* @return the xpath of the table's root element
*/
public String getCommonXpath() {
String[] tokens = xpath.split("/");
if (commonTokens.length==0) {
commonTokens = tokens;
-
+
} else {
final int maxLength = Math.min(commonTokens.length, tokens.length);
-
+
for (int i =0; i<maxLength; i++) {
if (!commonTokens[i].equals(tokens[i])) {
List<String> subCommonTokens = Arrays.asList(commonTokens).subList(0, i);
-
+
String[] container = {};
-
+
commonTokens = subCommonTokens.toArray(container);
break;
}
commonTokens[0] = "";
commonXPath = StringUtil.join(commonTokens, "/");
}
-
+
return commonXPath;
}
}
return xmlColumnPrs;
}
-
+
/**
* Add a new column to the right end of the table.
- *
+ *
* @param columnName
* the unique name of the column, must not be {@code null}
* @return the created table column
public XSSFTableColumn createColumn(String columnName) {
return createColumn(columnName, getColumnCount());
}
-
+
/**
* Adds a new column to the table.
- *
+ *
* @param columnName
* the unique name of the column, or {@code null} for a generated name
* @param columnIndex
* @since 4.0.0
*/
public XSSFTableColumn createColumn(String columnName, int columnIndex) {
-
+
int columnCount = getColumnCount();
if(columnIndex < 0 || columnIndex > columnCount) {
throw new IllegalArgumentException("Column index out of bounds");
}
-
+
// Ensure we have Table Columns
CTTableColumns columns = ctTable.getTableColumns();
if (columns == null) {
columns = ctTable.addNewTableColumns();
}
-
- // check if name is unique and calculate unique column id
- long nextColumnId = 0;
+
+ // check if name is unique and calculate unique column id
+ long nextColumnId = 0;
for (XSSFTableColumn tableColumn : getColumns()) {
if (columnName != null && columnName.equalsIgnoreCase(tableColumn.getName())) {
throw new IllegalArgumentException("Column '" + columnName
}
// Bug #62740, the logic was just re-using the existing max ID, not incrementing beyond it.
nextColumnId++;
-
+
// Add the new Column
CTTableColumn column = columns.insertNewTableColumn(columnIndex);
columns.setCount(columns.sizeOfTableColumnArray());
-
+
column.setId(nextColumnId);
if(columnName != null) {
- column.setName(columnName);
+ column.setName(columnName);
} else {
column.setName("Column " + nextColumnId);
}
-
+
if (ctTable.getRef() != null) {
// calculate new area
int newColumnCount = columnCount + 1;
setCellRef(newTableArea);
}
-
+
updateHeaders();
-
+
return getColumns().get(columnIndex);
}
-
+
/**
* Remove a column from the table.
*
updateHeaders();
}
}
-
+
/**
* Remove a column from the table.
*
if (columnIndex < 0 || columnIndex > getColumnCount() - 1) {
throw new IllegalArgumentException("Column index out of bounds");
}
-
+
if(getColumnCount() == 1) {
throw new IllegalArgumentException("Table must have at least one column");
}
-
+
CTTableColumns tableColumns = ctTable.getTableColumns();
tableColumns.removeTableColumn(columnIndex);
tableColumns.setCount(tableColumns.getTableColumnList().size());
updateReferences();
updateHeaders();
}
-
+
/**
* @return the name of the Table, if set
*/
}
return name;
}
-
+
/**
* Changes the name of the Table
* @param newName The name of the table.
}
return styleName;
}
-
+
/**
* Changes the name of the Table
* @param newStyleName The name of the style.
ctTable.getTableStyleInfo().setName(newStyleName);
styleName = newStyleName;
}
-
+
/**
* @return the display name of the Table, if set
*/
*
* Does not track updates to underlying changes to CTTable To synchronize
* with changes to the underlying CTTable, call {@link #updateReferences()}.
- *
+ *
* @return the area of the table
* @see "Open Office XML Part 4: chapter 3.5.1.2, attribute ref"
* @since 3.17 beta 1
SpreadsheetVersion.EXCEL2007
);
}
-
+
/**
* Set the area reference for the cells which this table covers. The area
* includes includes header rows and totals rows. Automatically synchronizes
* any changes by calling {@link #updateHeaders()}.
- *
+ *
* Note: The area's width should be identical to the amount of columns in
* the table or the table may be invalid. All header rows, totals rows and
* at least one data row must fit inside the area. Updating the area with
* this method does not create or remove any columns and does not change any
* cell values.
- *
+ *
* @see "Open Office XML Part 4: chapter 3.5.1.2, attribute ref"
* @since 3.17 beta 1
*/
public void setCellReferences(AreaReference refs) {
setCellRef(refs);
}
-
+
@Internal
protected void setCellRef(AreaReference refs) {
-
+
// Strip the sheet name,
// CTWorksheet.getTableParts defines in which sheet the table is
String ref = refs.formatAsString();
if (ref.indexOf('!') != -1) {
ref = ref.substring(ref.indexOf('!')+1);
}
-
+
// Update
ctTable.setRef(ref);
if (ctTable.isSetAutoFilter()) {
}
ctTable.getAutoFilter().setRef(filterRef);
}
-
+
// Have everything recomputed
updateReferences();
updateHeaders();
}
-
+
/**
* Set the area reference for the cells which this table covers. The area
* includes includes header rows and totals rows.
- *
+ *
* Updating the area with this method will create new column as necessary to
* the right side of the table but will not modify any cell values.
- *
+ *
* @param tableArea
* the new area of the table
* @throws IllegalArgumentException
if (tableArea == null) {
throw new IllegalArgumentException("AreaReference must not be null");
}
-
+
String areaSheetName = tableArea.getFirstCell().getSheetName();
if (areaSheetName != null && !areaSheetName.equals(getXSSFSheet().getSheetName())) {
// TODO to move a table from one sheet to another
throw new IllegalArgumentException(
"The AreaReference must not reference a different sheet");
}
-
+
int rowCount = (tableArea.getLastCell().getRow() - tableArea.getFirstCell().getRow()) + 1;
int minimumRowCount = 1 + getHeaderRowCount() + getTotalsRowCount();
if (rowCount < minimumRowCount) {
updateHeaders();
}
-
+
/**
* Get the area that this table covers.
*
return null;
}
}
-
+
/**
* @return The reference for the cell in the top-left part of the table
- * (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref)
+ * (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref)
*
* Does not track updates to underlying changes to CTTable
* To synchronize with changes to the underlying CTTable,
}
return startCellReference;
}
-
+
/**
* @return The reference for the cell in the bottom-right part of the table
* (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref)
}
}
-
+
/**
* Clears the cached values set by {@link #getStartCellReference()}
* and {@link #getEndCellReference()}.
endCellReference = null;
}
-
+
/**
* Get the total number of rows in this table, including all
* {@linkplain #getHeaderRowCount() header rows} and all
* {@linkplain #getTotalsRowCount() totals rows}. (Note: in this version
* autofiltering is ignored)
- *
+ *
* Returns <code>0</code> if the start or end cell references are not set.
- *
+ *
* Does not track updates to underlying changes to CTTable To synchronize
* with changes to the underlying CTTable, call {@link #updateReferences()}.
- *
+ *
* @return the total number of rows
*/
public int getRowCount() {
CellReference from = getStartCellReference();
CellReference to = getEndCellReference();
-
+
int rowCount = 0;
if (from!=null && to!=null) {
rowCount = to.getRow() - from.getRow() + 1;
}
return rowCount;
}
-
+
/**
* Get the number of data rows in this table. This does not include any
* header rows or totals rows.
- *
+ *
* Returns <code>0</code> if the start or end cell references are not set.
- *
+ *
* Does not track updates to underlying changes to CTTable To synchronize
* with changes to the underlying CTTable, call {@link #updateReferences()}.
- *
+ *
* @return the number of data rows
* @since 4.0.0
*/
/**
* Set the number of rows in the data area of the table. This does not
* affect any header rows or totals rows.
- *
+ *
* If the new row count is less than the current row count, superfluous rows
* will be cleared. If the new row count is greater than the current row
* count, cells below the table will be overwritten by the table.
- *
+ *
* To resize the table without overwriting cells, use
* {@link #setArea(AreaReference)} instead.
*
* Synchronize table headers with cell values in the parent sheet.
* Headers <em>must</em> be in sync, otherwise Excel will display a
* "Found unreadable content" message on startup.
- *
+ *
* If calling both {@link #updateReferences()} and
* this method, {@link #updateReferences()}
* should be called first.
- *
+ *
* Note that a Table <em>must</em> have a header. To reproduce
* the equivalent of inserting a table in Excel without Headers,
- * manually add cells with values of "Column1", "Column2" etc first.
+ * manually add cells with values of "Column1", "Column2" etc first.
*/
public void updateHeaders() {
XSSFSheet sheet = (XSSFSheet)getParent();
// FIXME: replace with org.apache.commons.collections.map.CaseInsensitiveMap
final int count = getColumnCount();
columnMap = new HashMap<>(count * 3 / 2);
-
+
int i = 0;
for (XSSFTableColumn column : getColumns()) {
String columnName = column.getName();
public boolean isHasTotalsRow() {
return ctTable.getTotalsRowShown();
}
-
+
/**
* @return 0 for no totals rows, 1 for totals row shown.
* Values > 1 are not currently used by Excel up through 2016, and the OOXML spec
public int getHeaderRowCount() {
return (int) ctTable.getHeaderRowCount();
}
-
+
/**
* @since 3.15 beta 2
*/
public int getEndRowIndex() {
return getEndCellReference().getRow();
}
-
+
/**
* @since 3.17 beta 1
*/
}
return false;
}
-
+
/**
* Remove relations
*/
/**
* A table column of an {@link XSSFTable}. Use {@link XSSFTable#createColumn} to
* create new table columns.
- *
- * @author Leonard Kappe
+ *
* @since 4.0.0
*/
public class XSSFTableColumn {
/**
* Get the identifier of this column, which is is unique per table.
- *
+ *
* @return the column id
* @since 4.0.0
*/
/**
* Set the identifier of this column, which must be unique per table.
- *
+ *
* It is up to the caller to enforce the uniqueness of the id.
- *
+ *
* @param columnId the column id
* @since 4.0.0
*/
/**
* Get the name of the column, which is is unique per table.
- *
+ *
* @return the column name
* @since 4.0.0
*/
/**
* Get the name of the column, which is is unique per table.
- *
+ *
* @param columnName the column name
* @since 4.0.0
*/
/**
* Represents a text box in a SpreadsheetML drawing.
- *
- * @author Yegor Kozlov
*/
public final class XSSFTextBox extends XSSFSimpleShape {
}
/**
- * Constructs a XSSFWorkbook object given a OpenXML4J <code>Package</code> object,
+ * Constructs a XSSFWorkbook object given a OpenXML4J {@code Package} object,
* see <a href="https://poi.apache.org/oxml4j/">https://poi.apache.org/oxml4j/</a>.
*
* <p>Once you have finished working with the Workbook, you should close the package
* <p>Creating a XSSFWorkbook from a file-backed OPC Package has a lower memory
* footprint than an InputStream backed one.
*
- * @param pkg the OpenXML4J <code>OPC Package</code> object.
+ * @param pkg the OpenXML4J {@code OPC Package} object.
*/
public XSSFWorkbook(OPCPackage pkg) throws IOException {
super(pkg);
*
* <p>Using an {@link InputStream} requires more memory than using a File, so
* if a {@link File} is available then you should instead do something like
- * <pre><code>
+ * <pre>{@code
* OPCPackage pkg = OPCPackage.open(path);
* XSSFWorkbook wb = new XSSFWorkbook(pkg);
* // work with the wb object
* ......
* pkg.close(); // gracefully closes the underlying zip file
- * </code></pre>
+ * }</pre>
*/
public XSSFWorkbook(InputStream is) throws IOException {
this(PackageHelper.open(is));
* POI's SpreadsheetAPI silently truncates the input argument to 31 characters.
* Example:
*
- * <pre><code>
+ * <pre>{@code
* Sheet sheet = workbook.createSheet("My very long sheet name which is longer than 31 chars"); // will be truncated
* assert 31 == sheet.getSheetName().length();
* assert "My very long sheet name which i" == sheet.getSheetName();
- * </code></pre>
+ * }</pre>
* </p>
*
* Except the 31-character constraint, Excel applies some other rules:
/**
* Finds a font that matches the one with the supplied attributes
*
- * @return the font with the matched attributes or <code>null</code>
+ * @return the font with the matched attributes or {@code null}
*/
@Override
public XSSFFont findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
* {@link #getNames(String name)} returns all named ranges with the given name.
*
* @param name named range name
- * @return XSSFName with the given name. <code>null</code> is returned no named range could be found.
+ * @return XSSFName with the given name.
+ * {@code null} is returned no named range could be found.
*/
@Override
public XSSFName getName(String name) {
* Gets the named range index by name. No longer public and only used in tests.
*
* @param name named range name
- * @return named range index. <code>-1</code> is returned if no named ranges could be found.
+ * @return named range index. {@code -1} is returned if no named ranges could be found.
*
* @deprecated 3.16. New projects should avoid accessing named ranges by index.
* Use {@link #getName(String)} instead.
* Get sheet with the given name (case insensitive match)
*
* @param name of the sheet
- * @return XSSFSheet with the name provided or <code>null</code> if it does not exist
+ * @return XSSFSheet with the name provided or {@code null} if it does not exist
*/
@Override
public XSSFSheet getSheet(String name) {
* Returns the index of the sheet by his name (case insensitive match)
*
* @param name the sheet name
- * @return index of the sheet (0 based) or <tt>-1</tt> if not found
+ * @return index of the sheet (0 based) or {@code -1} if not found
*/
@Override
public int getSheetIndex(String name) {
* Returns the index of the given sheet
*
* @param sheet the sheet to look up
- * @return index of the sheet (0 based). <tt>-1</tt> if not found
+ * @return index of the sheet (0 based). {@code -1} if not found
*/
@Override
public int getSheetIndex(Sheet sheet) {
* The calculation chain object specifies the order in which the cells in a workbook were last calculated
* </p>
*
- * @return the <code>CalculationChain</code> object or <code>null</code> if not defined
+ * @return the {@code CalculationChain} object or {@code null} if not defined
*/
@Internal
public CalculationChain getCalculationChain() {
* External Links in a formula would be '[1]Foo' which corresponds to
* entry 0 in this list.</p>
- * @return the <code>ExternalLinksTable</code> list, which may be empty
+ * @return the {@code ExternalLinksTable} list, which may be empty
*/
@Internal
public List<ExternalLinksTable> getExternalLinksTable() {
* Returns the data table with the given name (case insensitive).
*
* @param name the data table name (case-insensitive)
- * @return The Data table in the workbook named <tt>name</tt>, or <tt>null</tt> if no table is named <tt>name</tt>.
+ * @return The Data table in the workbook named {@code name}, or {@code null} if no table is named {@code name}.
* @since 3.15 beta 2
*/
public XSSFTable getTable(String name) {
/**
* Utility to update formulas and named ranges when a sheet name was changed
- *
- * @author Yegor Kozlov
*/
public final class XSSFFormulaUtils {
private final XSSFWorkbook _wb;
*
* This class is a wrapper around the CTSingleXmlCell (Open Office XML Part 4:
* chapter 3.5.2.1)
- *
-
- *
- * @author Roberto Manicardi
- *
*/
public class XSSFSingleXmlCell {
*
* This class is a wrapper around the CTXmlColumnPr (Open Office XML Part 4:
* chapter 3.5.1.7)
- *
- *
- * @author Roberto Manicardi
*/
public class XSSFXmlColumnPr {
/**
* Decorator class for XWPFParagraph allowing to add comments
* found in paragraph to its text
- *
- * @author Yury Batrakov (batrakov at gmail.com)
*/
public class XWPFCommentsDecorator extends XWPFParagraphDecorator {
private StringBuilder commentText;
package org.apache.poi.xwpf.usermodel;
-/**
- * <p>
- * 9 Jan 2010
- * </p>
- * <p>
- * // TODO insert Javadoc here!
- * </p>
- *
- * @author epp
- */
public enum BodyElementType {
CONTENTCONTROL,
PARAGRAPH,
* element
* </li>
* </ul>
- *
- * @author Gisella Bronzetti
*/
public enum Borders {
* Specifies the set of possible restart locations which may be used as to
* determine the next available line when a break's type attribute has a value
* of textWrapping.
- *
- * @author Gisella Bronzetti
*/
public enum BreakClear {
* document.
* The break type determines the next location where text shall be
* placed after this manual break is applied to the text contents
- *
- * @author Gisella Bronzetti
*/
public enum BreakType {
/**
* 9 Jan 2010
- *
- * @author Philipp Epp
*/
public interface IBodyElement {
IBody getBody();
/**
* Specifies the logic which shall be used to calculate the line spacing of the
* parent object when it is displayed in the document.
- *
- * @author Gisella Bronzetti
*/
public enum LineSpacingRule {
/**
* Specifies all types of alignment which are available to be applied to objects in a
* WordprocessingML document
- *
- * @author Yegor Kozlov
*/
public enum ParagraphAlignment {
//YK: TODO document each alignment option
/**
* Specifies all types of vertical alignment which are available to be applied to of all text
* on each line displayed within a paragraph.
- *
- * @author Gisella Bronzetti
*/
public enum TextAlignment {
/**
/**
* Specifies the types of patterns which may be used to create the underline
* applied beneath the text in a run.
- *
- * @author Gisella Bronzetti
*/
public enum UnderlinePatterns {
* relation to the default appearance of the run's text. This allows the text to
* be repositioned as subscript or superscript without altering the font size of
* the run properties.
- *
- * @author Gisella Bronzetti
*/
public enum VerticalAlign {
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
-/**
- * @author Philipp Epp
- */
public class XWPFAbstractNum {
protected XWPFNumbering numbering;
private CTAbstractNum ctAbstractNum;
/**
* Sketch of XWPF hyperlink class
- *
- * @author Yury Batrakov (batrakov at gmail.com)
*/
public class XWPFHyperlink {
String id, url;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument;
-/**
- * @author Philipp Epp
- */
public class XWPFNumbering extends POIXMLDocumentPart {
protected List<XWPFAbstractNum> abstractNums = new ArrayList<>();
protected List<XWPFNum> nums = new ArrayList<>();
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
-/**
- * @author Philipp Epp
- */
public class XWPFPicture {
private CTPicture ctPic;
}
return null;
}
-
+
/**
* Returns the width of the picture (in points).
*
public double getWidth() {
return Units.toPoints(ctPic.getSpPr().getXfrm().getExt().getCx());
}
-
+
/**
- * Returns the depth of the picture (in points).
+ * Returns the depth of the picture (in points).
*
* @since POI 4.1.1
*/
/**
* Raw picture data, normally attached to a WordprocessingML Drawing.
* As a rule, pictures are stored in the /word/media/ part of a WordprocessingML package.
- *
- * @author Philipp Epp
*/
public class XWPFPictureData extends POIXMLDocumentPart {
* Construct XWPFPictureData from a package part
*
* @param part the package part holding the drawing data,
- *
+ *
* @since POI 3.14-Beta1
*/
public XWPFPictureData(PackagePart part) {
super(part);
}
-
+
@Override
protected void onDocumentRead() throws IOException {
super.onDocumentRead();
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-/**
- * @author Yegor Kozlov
- */
public final class XWPFRelation extends POIXMLRelation {
/**
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType;
-/**
- * @author Philipp Epp
- */
public class XWPFStyle {
protected XWPFStyles styles;
/**
* Test TestFileHelper class.
- *
- * @author Julien Chable
*/
public final class TestFileHelper {
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()).
withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)).
build();
- assertFalse(diff.hasDifferences(), fileName+": "+diff.toString());
+ assertFalse(diff.hasDifferences(), fileName+": "+ diff);
} else {
// not xml, may be an image or other binary format
Assertions.assertEquals(contain1.size(), contain2.size(), fileName + " does not have the same size in both zip:");
}
/**
- * Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt>
+ * Asserts that two files are equal. Throws an {@code AssertionFailedError}
* if they are not.
- * <p>
- *
*/
public static void assertEquals(File expected, File actual) {
assertNotNull(expected);
*
* Part name equivalence is determined by comparing part names as
* case-insensitive ASCII strings. [M1.12]
- *
- * @author Julien Chable
*/
public final class TestOPCCompliancePartName {
CommitableWorkbook(OPCPackage pkg) throws IOException {
super(pkg);
}
+ @Override
public void commit() throws IOException {
super.commit();
}
/**
* Test {@link FormulaParser}'s handling of row numbers at the edge of the
* HSSF/XSSF ranges.
- *
- * @author David North
*/
class TestFormulaParser {
/**
* Tests XSSFFormulaEvaluator for its handling of cell formula circular references.
- *
- * @author Josh Micich
*/
public final class TestXSSFCircularReferences extends BaseTestCircularReferences {
public TestXSSFCircularReferences() {
import org.apache.poi.ss.usermodel.BaseTestBorderStyle;
import org.apache.poi.xssf.XSSFITestDataProvider;
-/**
- * @author Yegor Kozlov
- */
public final class TestXSSFBorderStyle extends BaseTestBorderStyle {
public TestXSSFBorderStyle() {
import java.io.IOException;
import java.io.InputStream;
-/**
- * @author Yegor Kozlov
- */
public class XSLFTestDataSamples {
public static XMLSlideShow openSampleDocument(String sampleName) {
} catch (IOException e) {
throw new RuntimeException(e);
}
-
+
InputStream bais;
bais = new ByteArrayInputStream(baos.toByteArray());
try {
throw new RuntimeException(e);
}
}
-
+
}
}
/**
* test common properties for sheets (slides, masters, layouts, etc.)
- *
- * @author Yegor Kozlov
*/
class TestXSLFSheet {
import org.apache.poi.xslf.XSLFTestDataSamples;
import org.junit.jupiter.api.Test;
-/**
- * @author Yegor Kozlov
- */
class TestXSLFSlide {
@Test
import org.apache.poi.xslf.XSLFTestDataSamples;
import org.junit.jupiter.api.Test;
-/**
- * @author Yegor Kozlov
- */
class TestXSLFSlideShow {
@Test
void testCreateSlide() throws IOException {
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
-/**
- * @author Yegor Kozlov
- */
class TestXSLFTextBox {
@Test
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
-/**
- * @author Yegor Kozlov
- */
class TestXSLFTextRun {
@Test
/**
* test reading properties from a multi-theme and multi-master document
- *
- * @author Yegor Kozlov
*/
class TestXSLFTheme {
@Test
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-/**
- * @author Yegor Kozlov
- */
public final class SXSSFITestDataProvider implements ITestDataProvider {
public static final SXSSFITestDataProvider instance = new SXSSFITestDataProvider();
// an instance of all SXSSFWorkbooks opened by this TestDataProvider,
- // so that the temporary files created can be disposed up by cleanup()
+ // so that the temporary files created can be disposed up by cleanup()
private final Collection<SXSSFWorkbook> instances = new ArrayList<>();
private SXSSFITestDataProvider() {
instances.add(wb);
return wb;
}
-
+
//************ SXSSF-specific methods ***************//
@Override
public SXSSFWorkbook createWorkbook(int rowAccessWindowSize) {
instances.add(wb);
return wb;
}
-
+
@Override
public void trackAllColumnsForAutosizing(Sheet sheet) {
((SXSSFSheet)sheet).trackAllColumnsForAutoSizing();
}
//************ End SXSSF-specific methods ***************//
-
+
@Override
public FormulaEvaluator createFormulaEvaluator(Workbook wb) {
return new XSSFFormulaEvaluator(((SXSSFWorkbook) wb).getXSSFWorkbook());
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-/**
- * @author Yegor Kozlov
- */
public final class XSSFITestDataProvider implements ITestDataProvider {
public static final XSSFITestDataProvider instance = new XSSFITestDataProvider();
public XSSFWorkbook createWorkbook() {
return new XSSFWorkbook();
}
-
+
//************ SXSSF-specific methods ***************//
@Override
public XSSFWorkbook createWorkbook(int rowAccessWindowSize) {
return createWorkbook();
}
-
+
@Override
public void trackAllColumnsForAutosizing(Sheet sheet) {}
//************ End SXSSF-specific methods ***************//
-
+
@Override
public FormulaEvaluator createFormulaEvaluator(Workbook wb) {
return new XSSFFormulaEvaluator((XSSFWorkbook) wb);
/**
* Centralises logic for finding/opening sample files in the test-data/spreadsheet folder.
- *
- * @author Josh Micich
*/
public class XSSFTestDataSamples {
/**
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
-/**
- * @author Roberto Manicardi
- */
public final class TestXSSFExportToXML {
@Test
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMapInfo;
import org.w3c.dom.Node;
-/**
- * @author Roberto Manicardi
- */
public final class TestMapInfo {
@Test
void testMapInfoExists() throws IOException {
/**
* Test setting hyperlinks in SXSSF
- *
- * @author Yegor Kozlov
*/
class TestSXSSFHyperlink extends BaseTestHyperlink {
import org.apache.poi.xssf.SXSSFITestDataProvider;
import org.apache.poi.xssf.streaming.SXSSFSheet;
-/**
- * @author Yegor Kozlov
- */
public final class TestSXSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn {
public TestSXSSFSheetAutosizeColumn(){
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
/**
- * @author centic
- *
* This testcase contains tests for bugs that are yet to be fixed. Therefore,
* the standard ant test target does not run these tests. Run this testcase with
* the single-test target. The names of the tests usually correspond to the
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.jupiter.api.Test;
-/**
- * @author Yegor Kozlov
- */
public final class TestXSSFPictureData {
@Test
void testRead() throws IOException {
* The author of this has added {@link CoreProperties#getKeywords()} and
* {@link CoreProperties#setKeywords(String)} and this test is supposed to test
* them.
- *
- * @author Antoni Mylka
*/
public final class TestAllExtendedProperties {
@Test
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
-/**
- * @author Yegor Kozlov
- */
public class XWPFTestDataSamples {
public static XWPFDocument openSampleDocument(String sampleName) throws IOException {
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-/**
- * @author Paolo Mottadelli
- */
public final class TestXWPFHeadings {
private static final String HEADING1 = "Heading1";
/**
* The superclass of all HDGF exceptions
- *
- * @author Yegor Kozlov
*/
public final class HDGFException extends RuntimeException {
* This class provides a way to view the contents of a powerpoint file.
* It will use the recored layer to grok the contents of the file, and
* will print out what it finds.
- *
- * @author Nick Burch
*/
public final class SlideShowRecordDumper {
static final String tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
-
+
private boolean optVerbose;
private boolean optEscher;
private HSLFSlideShowImpl doc;
ps.println(ind+ child);
prevChild = child;
}
-
+
}
-
+
private void printEscherContainerRecord( EscherContainerRecord ecr, int indent ) {
String ind = tabs.substring(0, indent);
ps.println(ind + ecr.getClass().getName() + " (" + ecr.getRecordName() + "):");
ps.println(ind + " isContainer: " + ecr.isContainerRecord());
ps.println(ind + " options: 0x" + HexDump.toHex( ecr.getOptions() ));
ps.println(ind + " recordId: 0x" + HexDump.toHex( ecr.getRecordId() ));
-
+
ps.println(ind + " numchildren: " + ecr.getChildCount());
ps.println(ind + " children: ");
int count = 0;
/**
* This exception is thrown when we try to open a PowerPoint file, and
* something is fundamentally broken about it.
- *
- * @author Nick Burch
*/
-
public final class CorruptPowerPointFileException extends IllegalStateException
{
public CorruptPowerPointFileException(String s) {
super(s);
}
-
+
public CorruptPowerPointFileException(String s, Throwable t) {
super(s,t);
}
/**
* A generic exception that can be thrown by HSLF classes
- *
- * @author Yegor Kozlov
*/
public final class HSLFException extends RuntimeException {
/**
* Represents a movie in a PowerPoint document.
- *
- * @author Yegor Kozlov
*/
public final class MovieShape extends HSLFPictureShape {
public static final int DEFAULT_MOVIE_THUMBNAIL = -1;
/**
* A simple closed polygon shape
- *
- * @author Yegor Kozlov
*/
public final class Polygon extends HSLFAutoShape {
/**
/**
* Definition for the common paragraph text property bitset.
- *
- * @author Yegor Kozlov
*/
public final class ParagraphFlagsTextProp extends BitMaskTextProp {
public static final int BULLET_IDX = 0;
* this means the default values will be used: statNumber=1 and sheme=ANM_ArabicPeriod
* @see <a href="http://social.msdn.microsoft.com/Forums/mr-IN/os_binaryfile/thread/650888db-fabd-4b95-88dc-f0455f6e2d28">
* http://social.msdn.microsoft.com/Forums/mr-IN/os_binaryfile/thread/650888db-fabd-4b95-88dc-f0455f6e2d28</a>
- *
- * @author Alex Nikiforov [mailto:anikif@gmail.com]
- *
*/
public class TextPFException9 implements GenericRecord {
/**
* A container record that specifies information about animation information for a shape.
- *
- * @author Yegor Kozlov
*/
public final class AnimationInfo extends RecordContainer {
private byte[] _header;
/**
* An atom record that specifies the animation information for a shape.
- *
- * @author Yegor Kozlov
*/
public final class AnimationInfoAtom extends RecordAtom {
* disk this is, but not much else.
* Anything done using this should quite quickly be transitioned to its
* own proper record class!
- *
- * @author Nick Burch
*/
public final class BinaryTagDataBlob extends PositionDependentRecordContainer
* A CString (type 4026). Holds a unicode string, and the first two bytes
* of the record header normally encode the count. Typically attached to
* some complex sequence of records, eg Commetns.
- *
- * @author Nick Burch
*/
public final class CString extends RecordAtom {
* colours of bits of text, that makes up a given colour scheme.
* Slides (presumably) link to a given colour scheme atom, and that
* defines the colours to be used
- *
- * @author Nick Burch
*/
public final class ColorSchemeAtom extends RecordAtom {
private byte[] _header;
/**
* This class represents a comment on a slide, in the format used by
* PPT 2000/XP/etc. (PPT 97 uses plain Escher Text Boxes for comments)
- * @author Nick Burch
*/
public final class Comment2000 extends RecordContainer {
private byte[] _header;
/**
* An atomic record containing information about a comment.
- *
- * @author Daniel Noll
*/
public final class Comment2000Atom extends RecordAtom
/**
* Master container for Document. There is one of these for every
* slideshow, and it holds lots of definitions, and some summaries.
- *
- * @author Nick Burch
*/
public final class Document extends PositionDependentRecordContainer
/**
* A Document Encryption Atom (type 12052). Holds information
* on the Encryption of a Document
- *
- * @author Nick Burch
*/
public final class DocumentEncryptionAtom extends PositionDependentRecordAtom {
private static final long _type = RecordTypes.DocumentEncryptionAtom.typeID;
* disk this is, but not much else.
* Anything done using this should quite quickly be transitioned to its
* own proper record class!
- *
- * @author Nick Burch
*/
public final class DummyPositionSensitiveRecordWithChildren extends PositionDependentRecordContainer
* If we come across a record we know has children of (potential)
* interest, but where the record itself is boring, we create one
* of these. It allows us to get at the children, but not much else
- *
- * @author Nick Burch
*/
public final class DummyRecordWithChildren extends RecordContainer
/**
* Environment, which contains lots of settings for the document.
- *
- * @author Nick Burch
*/
public final class Environment extends PositionDependentRecordContainer
* Note: when asked to write out, will simply put any child records correctly
* into the Escher layer. A call to the escher layer to write out (by the
* parent PPDrawing) will do the actual write out
- *
- * @author Nick Burch
*/
public final class EscherTextboxWrapper extends RecordContainer {
private EscherTextboxRecord _escherRecord;
/**
* A container record that specifies information about a movie stored externally.
- *
- * @author Yegor Kozlov
*/
public final class ExAviMovie extends ExMCIMovie {
* A ProgID is a string that uniquely identifies a given object.
* 5. CString (4026), Instance ClipboardName (3) that appears in the paste special dialog.
* 6. MetaFile( 4033), optional
- * </p>
- *
- *
- * @author Yegor kozlov
*/
public final class ExControl extends ExEmbed {
/**
* An atom record that specifies an ActiveX control.
- *
- * @author Yegor Kozlov
*/
public final class ExControlAtom extends RecordAtom {
* 5 bool1 noSizeToServerB Set if don't need to send the dimension to the embedded object
* 6 Bool1 isTable Set if the object is a Word table
* -->
- *
- * @author Daniel Noll
*/
public class ExEmbedAtom extends RecordAtom {
/**
* This class represents the data of a link in the document.
- * @author Nick Burch
*/
public class ExHyperlink extends RecordContainer {
private static final long _type = RecordTypes.ExHyperlink.typeID;
/**
* Tne atom that holds metadata on a specific Link in the document.
* (The actual link is held in a sibling CString record)
- *
- * @author Nick Burch
*/
public final class ExHyperlinkAtom extends RecordAtom {
/**
* A container record that specifies information about a movie stored externally.
- *
- * @author Yegor Kozlov
*/
public class ExMCIMovie extends RecordContainer { // TODO - instantiable superclass
private byte[] _header;
/**
* An atom record that specifies information about external audio or video data.
- *
- * @author Yegor Kozlov
*/
public final class ExMediaAtom extends RecordAtom
{
import org.apache.poi.util.LittleEndian;
/**
- * This class holds the links to exernal objects referenced
- * from the document.
- * @author Nick Burch
+ * This class holds the links to exernal objects referenced from the document.
*/
public class ExObjList extends RecordContainer {
private byte[] _header;
/**
* Tne atom that holds the seed info used by a ExObjList
- *
- * @author Nick Burch
*/
public class ExObjListAtom extends RecordAtom
/**
* A container record that specifies information about external video data.
- *
- * @author Yegor Kozlov
*/
public final class ExVideoContainer extends RecordContainer {
private byte[] _header;
* It keeps all the information needed to define the attributes of a font,
* such as height, width, etc. For more information, consult the
* Windows API Programmer's reference.
- *
- * @author Yegor Kozlov
*/
public final class FontEntityAtom extends RecordAtom {
/**
* An atom record that specifies options for displaying headers and footers
* on a presentation slide or notes slide.
- *
- * @author Yegor Kozlov
*/
public final class HeadersFootersAtom extends RecordAtom {
/**
* A container record that specifies information about the footers on a presentation slide.
* <p>
- * It contains:<br>
+ * It contains:
+ * <ul>
* <li> 1. {@link HeadersFootersAtom}
* <li> 2. {@link CString }, Instance UserDate (0), optional: Stores the user's date.
* This is the date that the user wants in the footers, instead of today's date.
* <li> 3. {@link CString }, Instance Header (1), optional: Stores the Header's contents.
* <li> 4. {@link CString }, Instance Footer (2), optional: Stores the Footer's contents.
- * </p>
- *
- * @author Yegor Kozlov
+ * </ul>
*/
public final class HeadersFootersContainer extends RecordContainer {
* This class represents the metadata of a link in a slide/notes/etc.
* It normally just holds a InteractiveInfoAtom, with the metadata
* in it.
- * @author Nick Burch
*/
public class InteractiveInfo extends RecordContainer {
private byte[] _header;
/**
* Tne atom that holds metadata on Links in the document.
* (The actual link is held Document.ExObjList.ExHyperlink)
- *
- * @author Nick Burch
- * @author Yegor Kozlov
*/
public class InteractiveInfoAtom extends RecordAtom {
/**
* Master slide
- *
- * @author Yegor Kozlov
*/
public final class MainMaster extends SheetContainer {
private byte[] _header;
/**
* Master container for Notes. There is one of these for every page of
* notes, and they have certain specific children
- *
- * @author Nick Burch
*/
public final class Notes extends SheetContainer
/**
* A Notes Atom (type 1009). Holds information on the parent Notes, such
* as what slide it is tied to
- *
- * @author Nick Burch
*/
public final class NotesAtom extends RecordAtom
* in a SlideListWithText containter. Sometimes slide texts are not contained
* within the slide container to be able to delay loading a slide and still display
* the title and body text in outline view.
- * </p>
- *
- * @author Yegor Kozlov
*/
public final class OutlineTextRefAtom extends RecordAtom {
/**
* Interface to define how a record can indicate it cares about what its
* parent is, and how it wants to be told which record is its parent.
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public interface ParentAwareRecord {
public org.apache.poi.hslf.record.RecordContainer getParentRecord();
/**
* A record that can be referenced in PersistPtr storage.
- *
- * @author Yegor Kozlov
*/
public interface PersistRecord {
* need to be pinged with their current location. When written out, they
* need to be given their new location, and offered the list of records
* which have changed their location.
- *
- * @author Nick Burch
*/
public interface PositionDependentRecord
* This abstract class represents a record in the PowerPoint document.
* Record classes should extend with RecordContainer or RecordAtom, which
* extend this in turn.
- *
- * @author Nick Burch
*/
public abstract class Record implements GenericRecord
/**
* Abstract class which all atom records will extend.
- *
- * @author Nick Burch
*/
public abstract class RecordAtom extends Record
/**
* An atom record that specifies that a shape is a header or footer placeholder shape
- *
- * @since PowerPoint 2007
- * @author Yegor Kozlov
*/
public final class RoundTripHFPlaceholder12 extends RecordAtom {
/**
/**
* Master container for Slides. There is one of these for every slide,
* and they have certain specific children
- *
- * @author Nick Burch
*/
public final class Slide extends SheetContainer
*
* For now, we scan through looking for interesting bits, then creating
* the helpful Sheet from model for them
- *
- * @author Nick Burch
*/
// For now, pretend to be an atom
/**
* A container holding information about a sound. It contains:
- * <p>
+ * <ul>
* <li>1. CString (4026), Instance 0: Name of sound (e.g. "crash")
* <li>2. CString (4026), Instance 1: Type of sound (e.g. ".wav")
* <li>3. CString (4026), Instance 2: Reference id of sound in sound collection
* <li>4. CString (4026), Instance 3, optional: Built-in id of sound, for sounds we ship. This is the id that?s in the reg file.
* <li>5. SoundData (2023), optional
- * </p>
- *
- * @author Yegor Kozlov
+ * </ul>
*/
public final class Sound extends RecordContainer {
/**
/**
* Is a container for all sound related atoms and containers. It contains:
- *<li>1. SoundCollAtom (2021)
- *<li>2. Sound (2022), for each sound, if any
- *
- * @author Yegor Kozlov
+ * <ul>
+ * <li>1. SoundCollAtom (2021)</li>
+ * <li>2. Sound (2022), for each sound, if any</li>
+ * </ul>
*/
public final class SoundCollection extends RecordContainer {
/**
/**
* Storage for embedded sounds.
- *
- * @author Yegor Kozlov
*/
public final class SoundData extends RecordAtom {
/**
* The special info runs contained in this text.
* Special info runs consist of character properties which don?t follow styles.
- *
- * @author Yegor Kozlov
*/
public final class TextSpecInfoAtom extends RecordAtom {
/**
* Tne atom that holds starting and ending character positions of a hyperlink
- *
- * @author Yegor Kozlov
*/
public final class TxInteractiveInfoAtom extends RecordAtom {
* If we come across a record we don't know about, we create one of
* these. It allows us to keep track of what it contains, so we can
* write it back out to disk unchanged
- *
- * @author Nick Burch
*/
@SuppressWarnings("unused")
/**
* Background shape
- *
- * @author Yegor Kozlov
*/
public final class HSLFBackground extends HSLFShape implements Background<HSLFShape,HSLFTextParagraph> {
/**
* Represents a line in a PowerPoint drawing
- *
- * @author Yegor Kozlov
*/
public final class HSLFLine extends HSLFTextShape implements Line<HSLFShape,HSLFTextParagraph> {
public HSLFLine(EscherContainerRecord escherRecord, ShapeContainer<HSLFShape,HSLFTextParagraph> parent){
@Override
protected EscherContainerRecord createSpContainer(boolean isChild){
EscherContainerRecord ecr = super.createSpContainer(isChild);
-
+
setShapeType(ShapeType.LINE);
EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID);
return ecr;
}
-
+
// /**
// * Sets the orientation of the line, if inverse is false, then line goes
-// * from top-left to bottom-right, otherwise use inverse equals true
+// * from top-left to bottom-right, otherwise use inverse equals true
// *
// * @param inverse the orientation of the line
// */
// public void setInverse(boolean inverse) {
// setShapeType(inverse ? ShapeType.LINE_INV : ShapeType.LINE);
// }
-//
+//
// /**
// * Gets the orientation of the line, if inverse is false, then line goes
-// * from top-left to bottom-right, otherwise inverse equals true
+// * from top-left to bottom-right, otherwise inverse equals true
// *
// * @return inverse the orientation of the line
// */
* This class represents a slide's notes in a PowerPoint Document. It
* allows access to the text within, and the layout. For now, it only
* does the text side of things though
- *
- * @author Nick Burch
*/
public final class HSLFNotes extends HSLFSheet implements Notes<HSLFShape,HSLFTextParagraph> {
/**
* Return <code>null</code> - Notes Masters are not yet supported
*/
+ @Override
public HSLFMasterSheet getMasterSheet() {
return null;
}
/**
* Represents a Placeholder in PowerPoint.
- *
- * @author Yegor Kozlov
*/
public final class HSLFPlaceholder extends HSLFTextBox {
@Override
protected EscherContainerRecord createSpContainer(boolean isChild){
EscherContainerRecord ecr = super.createSpContainer(isChild);
-
+
setPlaceholder(Placeholder.BODY);
return ecr;
/**
* This class defines the common format of "Sheets" in a powerpoint
* document. Such sheets could be Slides, Notes, Master etc
- *
- * @author Nick Burch
- * @author Yegor Kozlov
*/
public abstract class HSLFSheet implements HSLFShapeContainer, Sheet<HSLFShape,HSLFTextParagraph> {
/**
- * The <code>SlideShow</code> we belong to
+ * The {@code SlideShow} we belong to
*/
private HSLFSlideShow _slideShow;
* for notes it is org.apache.poi.hslf.record.Notes,
* for slide masters it is org.apache.poi.hslf.record.SlideMaster, etc.
*/
- private SheetContainer _container;
+ private final SheetContainer _container;
- private int _sheetNo;
+ private final int _sheetNo;
public HSLFSheet(SheetContainer container, int sheetNo) {
_container = container;
if (_slideShow != null) {
throw new HSLFException("Can't change existing slideshow reference");
}
-
+
_slideShow = ss;
List<List<HSLFTextParagraph>> trs = getTextParagraphs();
if (trs == null) {
EscherContainerRecord sp = (EscherContainerRecord)r;
HSLFShape sh = HSLFShapeFactory.createShape(sp, null);
sh.setSheet(this);
-
+
if (sh instanceof HSLFSimpleShape) {
HSLFHyperlink link = HSLFHyperlink.find(sh);
if (link != null) {
((HSLFSimpleShape)sh).setHyperlink(link);
}
}
-
+
shapeList.add(sh);
}
* Removes the specified shape from this sheet.
*
* @param shape shape to be removed from this sheet, if present.
- * @return <tt>true</tt> if the shape was deleted.
+ * @return {@code true} if the shape was deleted.
*/
@Override
public boolean removeShape(HSLFShape shape) {
/**
* Subclasses should call this method and update the array of text runs
* when a text shape is added
- *
- * @param shape
*/
protected void onAddTextShape(HSLFTextShape shape) {
}
* Return placeholder by text type
*
* @param type type of text, See {@link org.apache.poi.hslf.record.TextHeaderAtom}
- * @return <code>TextShape</code> or <code>null</code>
+ * @return {@code TextShape} or {@code null}
*/
public HSLFTextShape getPlaceholderByTextType(int type){
for (HSLFShape shape : getShapes()) {
}
/**
- * Return programmable tag associated with this sheet, e.g. <code>___PPT12</code>.
+ * Return programmable tag associated with this sheet, e.g. {@code ___PPT12}.
*
* @return programmable tag associated with this sheet.
*/
addShape(s);
return s;
}
-
+
/**
* Header / Footer settings for this slide.
*
import org.apache.poi.hslf.record.Comment2000;
import org.apache.poi.hslf.record.EscherTextboxWrapper;
import org.apache.poi.hslf.record.HeadersFootersContainer;
-import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.RecordContainer;
import org.apache.poi.hslf.record.RecordTypes;
import org.apache.poi.hslf.record.SSSlideInfoAtom;
* This class represents a slide in a PowerPoint Document. It allows
* access to the text within, and the layout. For now, it only does
* the text side of things though
- *
- * @author Nick Burch
- * @author Yegor Kozlov
*/
public final class HSLFSlide extends HSLFSheet implements Slide<HSLFShape,HSLFTextParagraph> {
* Called by SlideShow ater a new slide is created.
* <p>
* For Slide we need to do the following:
- * <li> set id of the drawing group.
- * <li> set shapeId for the container descriptor and background
- * </p>
+ * <ul>
+ * <li> set id of the drawing group.</li>
+ * <li> set shapeId for the container descriptor and background</li>
+ * </ul>
*/
@Override
public void onCreate(){
}
/**
- * Create a <code>TextBox</code> object that represents the slide's title.
+ * Create a {@code TextBox} object that represents the slide's title.
*
- * @return <code>TextBox</code> object that represents the slide's title.
+ * @return {@code TextBox} object that represents the slide's title.
*/
public HSLFTextBox addTitle() {
HSLFPlaceholder pl = new HSLFPlaceholder();
/**
* <p>
- * The title is a run of text of type <code>TextHeaderAtom.CENTER_TITLE_TYPE</code> or
- * <code>TextHeaderAtom.TITLE_TYPE</code>
+ * The title is a run of text of type {@code TextHeaderAtom.CENTER_TITLE_TYPE} or
+ * {@code TextHeaderAtom.TITLE_TYPE}
* </p>
*
* @see TextHeaderAtom
}
/**
- * @return set of records inside <code>SlideListWithtext</code> container
+ * @return set of records inside {@code SlideListWithtext} container
* which hold text data for this slide (typically for placeholders).
*/
protected SlideAtomsSet getSlideAtomsSet() { return _atomSet; }
/**
* Sets whether this slide follows master background
*
- * @param flag <code>true</code> if the slide follows master,
- * <code>false</code> otherwise
+ * @param flag {@code true} if the slide follows master,
+ * {@code false} otherwise
*/
@Override
public void setFollowMasterBackground(boolean flag){
/**
* Whether this slide follows master sheet background
*
- * @return <code>true</code> if the slide follows master background,
- * <code>false</code> otherwise
+ * @return {@code true} if the slide follows master background,
+ * {@code false} otherwise
*/
@Override
public boolean getFollowMasterBackground(){
/**
* Sets whether this slide draws master sheet objects
*
- * @param flag <code>true</code> if the slide draws master sheet objects,
- * <code>false</code> otherwise
+ * @param flag {@code true} if the slide draws master sheet objects,
+ * {@code false} otherwise
*/
@Override
public void setFollowMasterObjects(boolean flag){
/**
* Whether this slide follows master color scheme
*
- * @return <code>true</code> if the slide follows master color scheme,
- * <code>false</code> otherwise
+ * @return {@code true} if the slide follows master color scheme,
+ * {@code false} otherwise
*/
public boolean getFollowMasterScheme(){
SlideAtom sa = getSlideRecord().getSlideAtom();
/**
* Sets whether this slide draws master color scheme
*
- * @param flag <code>true</code> if the slide draws master color scheme,
- * <code>false</code> otherwise
+ * @param flag {@code true} if the slide draws master color scheme,
+ * {@code false} otherwise
*/
public void setFollowMasterScheme(boolean flag){
SlideAtom sa = getSlideRecord().getSlideAtom();
/**
* Whether this slide draws master sheet objects
*
- * @return <code>true</code> if the slide draws master sheet objects,
- * <code>false</code> otherwise
+ * @return {@code true} if the slide draws master sheet objects,
+ * {@code false} otherwise
*/
@Override
public boolean getFollowMasterObjects(){
* PPT 2003 files. Doesn't work for PPT 97
* ones, as they do their comments oddly.
*/
+ @Override
public List<HSLFComment> getComments() {
final List<HSLFComment> comments = new ArrayList<>();
// If there are any, they're in
*
* @return Header / Footer settings for this slide
*/
+ @Override
public HeadersFooters getHeadersFooters(){
return new HeadersFooters(this, HeadersFootersContainer.SlideHeadersFootersContainer);
}
Drawable draw = drawFact.getDrawable(this);
draw.draw(graphics);
}
-
+
@Override
public boolean getFollowMasterColourScheme() {
return false;
@Override
public void setFollowMasterColourScheme(boolean follow) {
}
-
+
@Override
public boolean getFollowMasterGraphics() {
return getFollowMasterObjects();
* SlideMaster determines the graphics, layout, and formatting for all the slides in a given presentation.
* It stores information about default font styles, placeholder sizes and positions,
* background design, and color schemes.
- *
- * @author Yegor Kozlov
*/
public final class HSLFSlideMaster extends HSLFMasterSheet {
private final List<List<HSLFTextParagraph>> _paragraphs = new ArrayList<>();
* If {@code name = "*"} return the current collection, otherwise if the name is not found
* in the current selection of txtype/level/name, first try lower levels then try parent types,
* if it wasn't found there return {@code null}.
- *
+ *
* @param txtype the {@link TextHeaderAtom} type
* @param level the indent level of the paragraph, if the level is not defined for the found
* collection, the highest existing level will be used
- * @param name the property name,
+ * @param name the property name,
* @param isCharacter if {@code true} use character styles, otherwise use paragraph styles
*/
@Override
/**
* A class that represents sound data embedded in a slide show.
- *
- * @author Yegor Kozlov
*/
public final class HSLFSoundData {
/**
/**
* Represents a table in a PowerPoint presentation
- *
- * @author Yegor Kozlov
*/
public final class HSLFTable extends HSLFGroupShape
implements HSLFShapeContainer, TableShape<HSLFShape,HSLFTextParagraph> {
if (htc.isEmpty()) {
throw new IllegalStateException("HSLFTable without HSLFTableCells");
}
-
+
SortedSet<Double> colSet = new TreeSet<>();
SortedSet<Double> rowSet = new TreeSet<>();
-
+
// #1 pass - determine cols and rows
for (HSLFTableCell sh : htc) {
Rectangle2D anchor = sh.getAnchor();
rowSet.add(anchor.getY());
}
cells = new HSLFTableCell[rowSet.size()][colSet.size()];
-
+
List<Double> colLst = new ArrayList<>(colSet);
List<Double> rowLst = new ArrayList<>(rowSet);
-
+
// #2 pass - assign shape to table cells
for (HSLFTableCell sh : htc) {
Rectangle2D anchor = sh.getAnchor();
int col = colLst.indexOf(anchor.getX());
assert(row != -1 && col != -1);
cells[row][col] = sh;
-
+
// determine gridSpan / rowSpan
int gridSpan = calcSpan(colLst, anchor.getWidth(), col);
int rowSpan = calcSpan(rowLst, anchor.getHeight(), row);
-
+
sh.setGridSpan(gridSpan);
sh.setRowSpan(rowSpan);
- }
+ }
}
private int calcSpan(List<Double> spaces, double totalSpace, int idx) {
}
return span;
}
-
+
static class LineRect {
final HSLFLine l;
final double lx1, lx2, ly1, ly2;
if (row < 0 || row >= cells.length) {
throw new IllegalArgumentException("Row index '"+row+"' is not within range [0-"+(cells.length-1)+"]");
}
-
+
return cells[row][0].getAnchor().getHeight();
}
-
+
@Override
public void setRowHeight(int row, final double height) {
if (row < 0 || row >= cells.length) {
double currentHeight = Units.masterToPoints(LittleEndian.getInt(masterBytes, 0));
LittleEndian.putInt(masterBytes, 0, Units.pointsToMaster(height));
p.setElement(row, masterBytes);
-
+
// move the cells
double dy = height - currentHeight;
for (int i = row; i < cells.length; i++) {
if (col < 0 || col >= cells[0].length) {
throw new IllegalArgumentException("Column index '"+col+"' is not within range [0-"+(cells[0].length-1)+"]");
}
-
+
// TODO: check for merged cols
return cells[0][col].getAnchor().getWidth();
}
* <p>
* Contains the text in a text frame as well as the properties and methods
* that control alignment and anchoring of the text.
- * </p>
- *
- * @author Yegor Kozlov
*/
public class HSLFTextBox extends HSLFTextShape implements TextBox<HSLFShape,HSLFTextParagraph> {
/**
* Common class for {@link ExcelToFoConverter} and {@link ExcelToHtmlConverter}
*
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
* @see AbstractWordConverter
*/
@Beta
/**
* Generates name for output as column header in case
- * <tt>{@link #isOutputColumnHeaders()} == true</tt>
+ * {@link #isOutputColumnHeaders()}{@code == true}
*
* @param columnIndex
* 0-based column index
/**
* Generates name for output as row number in case
- * <tt>{@link #isOutputRowNumbers()} == true</tt>
+ * {@link #isOutputRowNumbers()}{@code == true}
*/
protected String getRowName( HSSFRow row )
{
* @param mergedRanges map of sheet merged ranges built with
* {@link #buildMergedRangesMap(Sheet)}
* @return {@link CellRangeAddress} from map if cell with specified row and
- * column numbers contained in found range, <tt>null</tt> otherwise
+ * column numbers contained in found range, {@code null} otherwise
*/
public static CellRangeAddress getMergedRange(
CellRangeAddress[][] mergedRanges, int rowNumber, int columnNumber) {
}
/**
- * Returns <tt>false</tt> if cell style by itself (without text, i.e.
- * borders, fill, etc.) worth a mention, <tt>true</tt> otherwise
+ * Returns {@code false} if cell style by itself (without text, i.e.
+ * borders, fill, etc.) worth a mention, {@code true} otherwise
*
- * @return <tt>false</tt> if cell style by itself (without text, i.e.
- * borders, fill, etc.) worth a mention, <tt>true</tt> otherwise
+ * @return {@code false} if cell style by itself (without text, i.e.
+ * borders, fill, etc.) worth a mention, {@code true} otherwise
*/
protected boolean isEmptyStyle(CellStyle cellStyle) {
return cellStyle == null || (
/**
* Creates COLGROUP element with width specified for all columns. (Except
- * first if <tt>{@link #isOutputRowNumbers()}==true</tt>)
+ * first if {@link #isOutputRowNumbers()}{@code ==true})
*
* @return table width in inches
*/
/**
* Process single sheet (as specified by 0-based sheet index)
*
- * @return <tt>true</tt> if result were added to FO document, <tt>false</tt>
+ * @return {@code true} if result were added to FO document, {@code false}
* otherwise
*/
protected boolean processSheet(HSSFWorkbook workbook, int sheetIndex) {
private static final Logger LOG = LogManager.getLogger(ExcelToHtmlConverter.class);
/**
- * Java main() interface to interact with {@link ExcelToHtmlConverter}
+ * Java main() interface to interact with ExcelToHtmlConverter
*
* <p>
* Usage: ExcelToHtmlConverter infile outfile
return cssClassPrefixTable;
}
+ @Override
public Document getDocument() {
return htmlDocumentFacade.getDocument();
}
protected String getStyleClassName(HSSFWorkbook workbook,
HSSFCellStyle cellStyle) {
- final Short cellStyleKey = Short.valueOf(cellStyle.getIndex());
+ final Short cellStyleKey = cellStyle.getIndex();
String knownClass = excelStyleToClass.get(cellStyleKey);
if (knownClass != null) {
/**
* Creates COLGROUP element with width specified for all columns. (Except
- * first if <tt>{@link #isOutputRowNumbers()}==true</tt>)
+ * first if {@link #isOutputRowNumbers()}{@code ==true})
*/
protected void processColumnWidths(HSSFSheet sheet, int maxSheetColumns,
Element table) {
/**
* Utility class to translate numbers in letters, usually for lists.
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Beta
public final class NumberFormatter {
return String.valueOf( num );
}
}
-
+
private static String toLetters(int number) {
if ( number <= 0 ) {
throw new IllegalArgumentException( "Unsupported number: " + number );
/**
* User-implemented pictures manager to store images on-disk
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Beta
public interface PicturesManager
* {@link PictureType#TIFF}, but rarely {@link PictureType#EMF} or
* {@link PictureType#WMF}. FO (Apache FOP) supports at least PNG and SVG
* types.
- *
+ *
* @param content
* picture content
* @param pictureType
* display height in inches (scaled). May be useful for rendering
* vector images (such as EMF or WMF)
* @return path to file that can be used as reference in HTML (img's src) of
- * XLS FO (fo:external-graphic's src) or <tt>null</tt> if image were
+ * XLS FO (fo:external-graphic's src) or {@code null} if image were
* not saved and should not be referenced from result HTML / FO.
*/
String savePicture( byte[] content, PictureType pictureType,
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
-/**
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
- */
@Beta
public class WordToFoConverter extends AbstractWordConverter
{
public class WordToHtmlConverter extends AbstractWordConverter
{
/**
- * Holds properties values, applied to current <tt>p</tt> element. Those
- * properties shall not be doubled in children <tt>span</tt> elements.
+ * Holds properties values, applied to current {@code p} element. Those
+ * properties shall not be doubled in children {@code span} elements.
*/
private static class BlockProperies
{
private Element notes;
/**
- * Creates new instance of {@link WordToHtmlConverter}. Can be used for
+ * Creates new instance of WordToHtmlConverter. Can be used for
* output several {@link HWPFDocument}s into single HTML document.
*
* @param document XML DOM Document used as HTML document
}
/**
- * Java main() interface to interact with {@link WordToHtmlConverter}<p>
+ * Java main() interface to interact with WordToHtmlConverter<p>
*
* Usage: WordToHtmlConverter infile outfile<p>
*
import org.apache.poi.util.Internal;
/**
- * <p>
* For iterating through our fields. Used during model classes autogeneration.
- * </p>
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
@Internal
public class FieldIterator
/**
* Used by developers to list out key information on a HWPF file. End users will
* probably never need to use this program.
- *
- * @author Nick Burch (nick at torchbox dot com)
- * @author Sergey Vladimirov (vlsergey at gmail dot com)
*/
@Beta
public final class HWPFLister {
/**
* Helper functions for the record transformations. Used during model classes
* autogeneration.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- * @author Andrew C. Oliver (acoliver at apache dot org)
*/
@Internal
public class RecordUtil
* This should only be used on the older files, for most uses you
* should call {@link WordExtractor} which deals properly
* with HWPF.
- *
- * @author Nick Burch
*/
public final class Word6Extractor implements POIOLE2TextExtractor {
private HWPFOldDocument doc;
*
* You should use either getParagraphText() or getText() unless you have a
* strong reason otherwise.
- *
- * @author Nick Burch
*/
public final class WordExtractor implements POIOLE2TextExtractor {
private final HWPFDocument doc;
/**
* This class holds all of the character formatting properties.
- *
- * @author Ryan Ackley
*/
@Internal
public class CHPBinTable
* CHP and PAP fkps also store the compressed styles(grpprl) that correspond to
* the offsets on the front of the fkp. The offset of the grpprls is determined
* differently for CHP fkps and PAP fkps.
- *
- * @author Ryan Ackley
*/
@Internal
public final class CHPFormattedDiskPage extends FormattedDiskPage
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Internal;
-/**
- * Comment me
- *
- * @author Ryan Ackley
- */
@Internal
public final class DocumentProperties extends DOPAbstractType
{
/**
* The FFData structure specifies form field data for a text box, check box, or
* drop-down list box.
- * <p>
- * Class and fields descriptions are quoted from [MS-DOC] -- v20121003 Word
- * (.doc) Binary File Format; Copyright (c) 2012 Microsoft Corporation; Release:
- * October 8, 2012
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
- *
- * @author Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word (.doc)
- * Binary File Format; Copyright (c) 2012 Microsoft Corporation;
- * Release: October 8, 2012
*/
@Internal
public class FFData
* <p>
* This class is internal. It content or properties may change without notice
* due to changes in our knowledge of internal Microsoft Word binary structures.
- *
- * @author Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word (.doc)
- * Binary File Format; Copyright (c) 2012 Microsoft Corporation;
- * Release: October 8, 2012
*/
@Internal
public class FFDataBase extends FFDataBaseAbstractType
/**
* File Shape Address structure
- *
- * @author Squeeself
*/
@Internal
public final class FSPA extends FSPAAbstractType
* FFN - Font Family Name. FFN is a data structure that stores the names of the Main
* Font and that of Alternate font as an array of characters. It has also a header
* that stores info about the whole structure and the fonts
- *
- * @author Praveen Mathew
*/
@Internal
public final class Ffn
* <p>
* Class and fields descriptions are quoted from Microsoft Office Word 97-2007
* Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format.
- *
- * @author Andrew C. Oliver; Sergey Vladimirov; according to Microsoft Office
- * Word 97-2007 Binary File Format Specification [*.doc] and [MS-DOC] -
- * v20110608 Word (.doc) Binary File Format
*/
@Internal
public class FibBase extends FibBaseAbstractType {
/**
* The FibRgLw97 structure is the third section of the FIB. This contains an
* array of 4-byte values.
- * <p>
- * Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- * Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc] and [MS-DOC] - v20110608 Word
- * (.doc) Binary File Format
*/
@Internal
-class FibRgLw95 extends FibRgLw95AbstractType implements FibRgLw
+class FibRgLw95 extends FibRgLw95AbstractType implements FibRgLw
{
public FibRgLw95()
* <p>
* Class and fields descriptions are quoted from Microsoft Office Word 97-2007
* Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc] and [MS-DOC] - v20110608 Word
- * (.doc) Binary File Format
*/
@Internal
public class FibRgLw97 extends FibRgLw97AbstractType implements FibRgLw
/**
* The FibRgW97 structure is a variable-length portion of the Fib.
- * <p>
- * Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- * Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format.
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc] and [MS-DOC] - v20110608 Word
- * (.doc) Binary File Format
*/
@Internal
public class FibRgW97 extends FibRgW97AbstractType
/**
* Class for the FLD structure.
- *
- * @author Cedric Bosdonnat <cbosdonnat@novell.com>
*/
@Internal
public final class FieldDescriptor extends FLDAbstractType
/**
* This class provides access to all the fields Plex.
- *
- * @author Cedric Bosdonnat <cbosdonnat@novell.com>
- *
*/
@Internal
public class FieldsTables
* Word files. The sttbfffn is an sttbf where each string is an FFN structure instead
* of pascal-style strings. An sttbf is a string Table stored in file. Thus sttbffn
* is like an Sttbf with an array of FFN structures that stores the font name strings
- *
- * @author Praveen Mathew
*/
@Internal
public final class FontTable
* CHP and PAP fkps also store the compressed styles(grpprl) that correspond to
* the offsets on the front of the fkp. The offset of the grpprls is determined
* differently for CHP fkps and PAP fkps.
- *
- * @author Ryan Ackley
*/
@Internal
public abstract class FormattedDiskPage {
* HTML incompatibilities of a list structure. The values specify possible
* incompatibilities between an LVL or LVLF and HTML lists. The values do not
* define list properties.
- * <p>
- * Class and fields descriptions are quoted from [MS-DOC] -- v20110315 Word
- * (.doc) Binary File Format specification
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
- *
- * @author Sergey Vladimirov; according to [MS-DOC] -- v20110315 Word (.doc)
- * Binary File Format specification
*/
@Internal
public class Grfhic extends GrfhicAbstractType
/**
* "The LFO structure specifies the LSTF element that corresponds to a list that
* contains a paragraph. An LFO can also specify formatting information that
- * overrides the LSTF element to which it corresponds." -- [MS-DOC] -- v20110315
- * Word (.doc) Binary File Format
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
+ * overrides the LSTF element to which it corresponds."
*/
@Internal
public class LFO extends LFOAbstractType
/**
* The LFOData structure contains the Main Document CP of the corresponding LFO,
* as well as an array of LVL override data.
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Internal
public class LFOData
* <p>
* Class and fields descriptions are quoted from Microsoft Office Word 97-2007
* Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc] and [MS-DOC] - v20110608 Word
- * (.doc) Binary File Format
*/
class LFOLVLBase extends LFOLVLBaseAbstractType
{
import org.apache.poi.hwpf.model.types.LSTFAbstractType;
/**
- * The LSTF structure contains formatting properties that apply to an entire
- * list.
- * <p>
- * Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- * Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc] and [MS-DOC] - v20110608 Word
- * (.doc) Binary File Format
+ * The LSTF structure contains formatting properties that apply to an entire list.
*/
class LSTF extends LSTFAbstractType
{
/**
* The LVLF structure contains formatting properties for an individual level in
* a list
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc] and [MS-DOC] - v20110608 Word
- * (.doc) Binary File Format
*/
@Internal
class LVLF extends LVLFAbstractType
limitations under the License.
==================================================================== */
-/**
- * Word document notes types (and their FIB field indices)
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com)
- */
package org.apache.poi.hwpf.model;
import org.apache.poi.util.Internal;
+/**
+ * Word document notes types (and their FIB field indices)
+ */
@Internal
public enum NoteType {
/** Ending note */
/**
* Holds information about document notes (footnotes or ending notes)
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com)
*/
@Internal
public class NotesTables
* Information about drawings in the document.
* <p>
* The {@code delay stream} referenced in {@code [MS-ODRAW]} is the {@code WordDocument} stream.
- *
- * @author Squeeself
*/
@Internal
public final class OfficeArtContent {
* CHP and PAP fkps also store the compressed styles(grpprl) that correspond to
* the offsets on the front of the fkp. The offset of the grpprls is determined
* differently for CHP fkps and PAP fkps.
- *
- * @author Ryan Ackley
*/
@Internal
public final class PAPFormattedDiskPage extends FormattedDiskPage {
/**
* The PICF structure specifies the type of a picture, as well as the size of
* the picture and information about its border.
- * <p>
- * Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- * Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Internal
public class PICF extends PICFAbstractType
* CharacterRun.isSpecial() returns true. The file location of the picture in the Word binary file is accessed
* via CharacterRun.getPicOffset(). The CharacterRun.getPicOffset() is a byte offset into the data stream.
* Beginning at the position recorded in picOffset, a header data structure, will be stored.
- *
- * @author Dmitry Romanov
*/
@Internal
public final class PicturesTable {
/**
* Structure describing the Plex for fields (contained plclfd* in the spec).
- *
- * @author Cedric Bosdonnat <cbosdonnat@novell.com>
*/
@Internal
public class PlexOfField
* <p>
* Documentation quoted from Page 424 of 621. [MS-DOC] -- v20110315 Word (.doc)
* Binary File Format
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public class PlfLfo
{
/**
* String table containing the names of authors of revision marks, e-mails and
* comments in this document.
- *
- * @author Ryan Lauck
*/
@Internal
public final class RevisionMarkAuthorTable {
/**
* Constructor to read the table from the table stream.
- *
+ *
* @param tableStream the table stream.
* @param offset the offset into the byte array.
* @param size the size of the table in the byte array.
/**
* Gets the entries. The returned list cannot be modified.
- *
+ *
* @return the list of entries.
*/
public List<String> getEntries() {
return Collections.unmodifiableList(Arrays.asList(entries));
}
-
+
/**
* Get an author by its index. Returns null if it does not exist.
- *
+ *
* @return the revision mark author
*/
public String getAuthor(int index) {
}
return auth;
}
-
+
/**
* Gets the number of entries.
- *
+ *
* @return the number of entries.
*/
public int getSize() {
/**
* Writes this table to the table stream.
- *
+ *
* @param tableStream the table stream to write to.
* @throws IOException if an error occurs while writing.
*/
/**
* A single entry in the {@link SavedByTable}.
- *
- * @author Daniel Noll
*/
@Internal
public final class SavedByEntry
/**
* String table containing the history of the last few revisions ("saves") of
* the document. Read-only for the time being.
- *
- * @author Daniel Noll
*/
@Internal
public final class SavedByTable
/**
* Constructor to read the table from the table stream.
- *
+ *
* @param tableStream
* the table stream.
* @param offset
/**
* Gets the entries. The returned list cannot be modified.
- *
+ *
* @return the list of entries.
*/
public List<SavedByEntry> getEntries()
/**
* Writes this table to the table stream.
- *
+ *
* @param tableStream
* the table stream to write to.
* @throws IOException
import java.util.Arrays;
import org.apache.logging.log4j.LogManager;
+import org.apache.poi.util.Internal;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.StringUtil;
* The STTB is a string table that is made up of a header that is followed by an
* array of elements. The cData value specifies the number of elements that are
* contained in the array.
- * <p>
- * Class and fields descriptions are quoted from [MS-DOC] -- v20121003 Word
- * (.doc) Binary File Format; Copyright (c) 2012 Microsoft Corporation; Release:
- * October 8, 2012
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
- *
- * @author Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word (.doc)
- * Binary File Format; Copyright (c) 2012 Microsoft Corporation;
- * Release: October 8, 2012
*/
+@Internal
public class Sttb
{
/**
* Utils class for storing and reading "STring TaBle stored in File"
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Internal
class SttbUtils
import static org.apache.logging.log4j.util.Unbox.box;
-/**
- * Comment me
- *
- * @author Ryan Ackley
- */
@Internal
public final class StyleDescription {
* <p>
* Fields documentation is quotes from Microsoft Office Word 97-2007 Binary File
* Format (.doc) Specification, page 36 of 210
- *
- * @author Ryan Ackley
*/
@Internal
public final class StyleSheet {
/**
* Document text parts that can have text pieces (CPs)
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Internal
public enum SubdocumentType {
* The piece table for matching up character positions to bits of text. This
* mostly works in bytes, but the TextPieces themselves work in characters. This
* does the icky convertion.
- *
- * @author Ryan Ackley
*/
@Internal
public class TextPieceTable implements CharIndexTranslator {
import org.apache.poi.util.LittleEndianConsts;
/**
- * The Xst structure is a string. The string is prepended by its length and is
- * not null-terminated.
- * <p>
- * Documentation quoted from Page 424 of 621. [MS-DOC] -- v20110315 Word (.doc)
- * Binary File Format
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
+ * The Xst structure is a string. The string is prepended by its length and is not null-terminated.
*/
public class Xst
{
/**
* Document Properties.
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/records/definitions.
- *
- * @author S. Ryan Ackley
*/
@Internal
public abstract class DOPAbstractType {
import org.apache.poi.util.LittleEndian;
/**
- * The FFData structure specifies form field data for a text
- box, check box, or drop-down list box. <p>Class and fields
- descriptions are quoted from [MS-DOC] -- v20121003 Word (.doc) Binary
- File Format; Copyright (c) 2012 Microsoft Corporation; Release:
- October 8, 2012
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word
- (.doc) Binary File Format; Copyright (c) 2012 Microsoft Corporation;
- Release: October 8, 2012
-
+ * The FFData structure specifies form field data for a text box, check box, or drop-down list box.
*/
@Internal
public abstract class FFDataBaseAbstractType
/**
* Field Descriptor (FLD).
- * <p>
- * Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- * Binary File Format
- *
- * NOTE: This source is automatically generated please do not modify this file.
- * Either subclass or remove the record in src/records/definitions.
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc]
*/
@Internal
public abstract class FLDAbstractType
/**
* Type of field boundary the FLD describes: 19 -- field begin mark, 20 --
* field separation mark; 21 -- field end mark
- *
+ *
* @return the ch field value.
*/
public byte getCh()
/**
* Reserved
- *
+ *
* @return the reserved field value.
*/
public byte getReserved()
/**
* Ignored for saved file
- *
+ *
* @return the fDiffer field value.
*/
public boolean isFDiffer()
/**
* ==1 when result still believes this field is an EMBED or LINK field
- *
+ *
* @return the fZombieEmbed field value.
*/
public boolean isFZombieEmbed()
/**
* ==1 when user has edited or formatted the result. == 0 otherwise
- *
+ *
* @return the fResultDirty field value.
*/
public boolean isFResultDirty()
/**
* ==1 when user has inserted text into or deleted text from the result
- *
+ *
* @return the fResultEdited field value.
*/
public boolean isFResultEdited()
/**
* ==1 when field is locked from recalculation
- *
+ *
* @return the fLocked field value.
*/
public boolean isFLocked()
/**
* ==1 whenever the result of the field is never to be shown
- *
+ *
* @return the fPrivateResult field value.
*/
public boolean isFPrivateResult()
/**
* ==1 when field is nested within another field
- *
+ *
* @return the fNested field value.
*/
public boolean isFNested()
/**
* ==1 when field has a field separator
- *
+ *
* @return the fHasSep field value.
*/
public boolean isFHasSep()
/**
* File Shape Address (FSPA).
- * <p>
- * Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- * Binary File Format
- *
- * <p>
- * NOTE: This source is automatically generated please do not modify this file.
- * Either subclass or remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
- *
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- * File Format Specification [*.doc]
*/
@Internal
public abstract class FSPAAbstractType
/**
* Sets the fBelowText field value.
- *
+ *
*/
@Internal
public void setFBelowText( boolean value )
}
/**
- *
+ *
* @return the fBelowText field value.
*/
@Internal
/**
* Sets the fAnchorLock field value.
- *
+ *
*/
@Internal
public void setFAnchorLock( boolean value )
}
/**
- *
+ *
* @return the fAnchorLock field value.
*/
@Internal
/**
* Base part of the File information Block (FibBase). Holds the core part of the FIB,
- from the first 32 bytes. <p>Class and fields descriptions are quoted from Microsoft
- Office Word 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File
- Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Andrew C. Oliver; Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary
- File Format Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * from the first 32 bytes.
*/
@Internal
public abstract class FibBaseAbstractType
/**
* The FibRgLw95 structure is the third section of the FIB for Word95.
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov
-
*/
@Internal
public abstract class FibRgLw95AbstractType
/**
* The FibRgLw97 structure is the third section of the FIB. This contains an array of
- 4-byte values. <p>Class and fields descriptions are quoted from Microsoft Office Word
- 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * 4-byte values.
*/
@Internal
public abstract class FibRgLw97AbstractType
import org.apache.poi.util.LittleEndian;
/**
- * The FibRgW97 structure is a variable-length portion of the Fib. <p>Class and
- fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and
- [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * The FibRgW97 structure is a variable-length portion of the Fib.
*/
@Internal
public abstract class FibRgW97AbstractType
/**
* The grfhic structure is a set of HTML incompatibility flags that specify the HTML
- incompatibilities of a list structure. The values specify possible incompatibilities between
- an LVL or LVLF and HTML lists. The values do not define list properties. <p>Class and
- fields descriptions are quoted from [MS-DOC] -- v20110315 Word (.doc) Binary File Format
- specification
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to [MS-DOC] -- v20110315 Word (.doc) Binary File Format
- specification
-
+ * incompatibilities of a list structure. The values specify possible incompatibilities between
+ * an LVL or LVLF and HTML lists. The values do not define list properties.
*/
@Internal
public abstract class GrfhicAbstractType
import org.apache.poi.util.LittleEndian;
/**
- * List Format Override (LFO). <p>Class and fields descriptions are quoted from
- [MS-DOC] --v20110315; Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to [MS-DOC] --v20110315; Word (.doc) Binary File Format;
- Copyright (c) Microsoft Corporation
-
+ * List Format Override (LFO).
*/
@Internal
public abstract class LFOAbstractType
import org.apache.poi.util.LittleEndian;
/**
- * The LFOLVL structure contains information that is used to override the formatting
- information of a corresponding LVL. <p>Class and fields descriptions are quoted from
- Microsoft Office Word 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary
- File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * The LFOLVL structure contains information that is used to override the formatting information of a corresponding LVL.
*/
@Internal
public abstract class LFOLVLBaseAbstractType
/**
* The LSTF structure contains formatting properties that apply to an entire list.
- <p>Class and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary
- File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
*/
@Internal
public abstract class LSTFAbstractType
import org.apache.poi.util.LittleEndian;
/**
- * The LVLF structure contains formatting properties for an individual level in a
- list. <p>Class and fields descriptions are quoted from Microsoft Office Word 97-2007
- Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * The LVLF structure contains formatting properties for an individual level in a list.
*/
@Internal
public abstract class LVLFAbstractType
/**
* The PICF structure specifies the type of a picture, as well as the size of the
- picture and information about its border. <p>Class and fields descriptions are quoted
- from Microsoft Office Word 97-2007
- Binary File Format and [MS-DOC] - v20110608 Word (.doc)
- Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * picture and information about its border.
*/
@Internal
public abstract class PICFAbstractType
import org.apache.poi.util.LittleEndian;
/**
- * The StdfBase structure specifies general information about a style. <p>Class
- and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and
- [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * The StdfBase structure specifies general information about a style.
*/
@Internal
public abstract class StdfBaseAbstractType
/**
* The StdfPost2000 structure specifies general information about a style.
- <p>Class and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary
- File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
*/
@Internal
public abstract class StdfPost2000AbstractType
import org.apache.poi.util.LittleEndian;
/**
- * The Stshif structure specifies general stylesheet information. <p>Class and
- fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and
- [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
- * <p>
- * NOTE: This source is automatically generated please do not modify this file. Either subclass or
- * remove the record in src/types/definitions.
- * <p>
- * This class is internal. It content or properties may change without notice
- * due to changes in our knowledge of internal Microsoft Word binary structures.
-
- * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format
- Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format
-
+ * The Stshif structure specifies general stylesheet information.
*/
@Internal
public abstract class StshifAbstractType
/**
* This class is used to iterate through a list of sprms from a Word 97/2000/XP
* document.
- * @author Ryan Ackley
* @version 1.0
*/
@Internal
/**
* User friendly interface to access information about document bookmarks
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com)
*/
public interface Bookmark
{
/**
* User-friendly interface to access document bookmarks
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public interface Bookmarks
{
/**
* Remove bookmark from document (but not the bookmark text)
- *
+ *
* @param index
* bookmark document index to be removed
*/
/**
* Implementation of user-friendly interface for document bookmarks
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com)
*/
public class BookmarksImpl implements Bookmarks
{
import org.apache.poi.hwpf.model.PlexOfField;
import org.apache.poi.util.Internal;
-/**
- * TODO: document me
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
- */
@Internal
class FieldImpl implements Field
{
/**
* User-friendly interface to access document {@link Field}s
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public interface Fields
{
/**
* Default implementation of {@link Field}
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Internal
public class FieldsImpl implements Fields
* conjunction with
* {@link org.apache.poi.hwpf.HWPFDocument#registerList(HWPFList) registerList}
* in {@link org.apache.poi.hwpf.HWPFDocument HWPFDocument}.
- *
+ *
* In Word, lists are not ranged entities, meaning you can't actually add one to
* the document. Lists only act as properties for list entries. Once you
* register a list, you can add list entries to a document that are a part of
* the list.
- *
+ *
* The only benefit of this that I see, is that you can add a list entry
* anywhere in the document and continue numbering from the previous list.
- *
- * @author Ryan Ackley
*/
public final class HWPFList
{
private StyleSheet _styleSheet;
/**
- *
+ *
* @param numbered
* true if the list should be numbered; false if it should be
* bulleted.
/**
* Sets the character properties of the list numbers.
- *
+ *
* @param level
* the level number that the properties should apply to.
* @param chp
/**
* Sets the paragraph properties for a particular level of the list.
- *
+ *
* @param level
* The level number.
* @param pap
/**
* User-friendly interface to access document notes information
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com)
*/
public interface Notes
{
/**
* Default implementation of {@link Notes} interface
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com)
*/
public class NotesImpl implements Notes
{
* <li>[MS-ODRAW] -- v20110608; Office Drawing Binary File Format; Copyright (c)
* 2011 Microsoft Corporation.
* </ul>
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public interface OfficeDrawing
{
- public enum HorizontalPositioning {
+ enum HorizontalPositioning {
/**
* The shape is horizontally offset by an absolute distance from the
RIGHT
}
- public enum HorizontalRelativeElement {
+ enum HorizontalRelativeElement {
CHAR, MARGIN, PAGE, TEXT
}
- public enum VerticalPositioning {
+ enum VerticalPositioning {
/**
* The shape is vertically offset by an absolute distance from the page
TOP
}
- public enum VerticalRelativeElement {
+ enum VerticalRelativeElement {
LINE, MARGIN, PAGE, TEXT
}
/**
* Returns the type of horizontal positioning to use for a shape
- *
+ *
* @return the type of horizontal positioning to use for a shape
*/
- public HorizontalPositioning getHorizontalPositioning();
+ HorizontalPositioning getHorizontalPositioning();
/**
* Specifies a page element relative to which a shape is horizontally
* positioned
- *
+ *
* @return a page element relative to which a shape is horizontally
* positioned
*/
- public HorizontalRelativeElement getHorizontalRelative();
+ HorizontalRelativeElement getHorizontalRelative();
/**
* Returns escher record that represent shape container (record type is
- * <tt>0xF004</tt>). Returned record has a child with record type
- * <tt>0xF00A</tt> and value of shape id equals to {@link #getShapeId()}.
- *
- * @return Returns office art shape container or <tt>null</tt> if not found
+ * {@code 0xF004}). Returned record has a child with record type
+ * {@code 0xF00A} and value of shape id equals to {@link #getShapeId()}.
+ *
+ * @return Returns office art shape container or {@code null} if not found
*/
- public EscherContainerRecord getOfficeArtSpContainer();
+ EscherContainerRecord getOfficeArtSpContainer();
/**
* Returns picture data if this shape has (single?) associated picture data
/**
* Specifies the type of vertical positioning to use for a shape
- *
+ *
* @return return the type of vertical positioning to use for a shape
*/
- public VerticalPositioning getVerticalPositioning();
+ VerticalPositioning getVerticalPositioning();
/**
* Specifies a page element relative to which a shape is vertically
* positioned
- *
+ *
* @return a page element relative to which a shape is vertically positioned
*/
- public VerticalRelativeElement getVerticalRelativeElement();
+ VerticalRelativeElement getVerticalRelativeElement();
}
/**
* User-friendly interface to access document part's office drawings
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public interface OfficeDrawings
{
{
return new OfficeDrawing()
{
+ @Override
public HorizontalPositioning getHorizontalPositioning()
{
int value = getTertiaryPropertyValue(EscherPropertyTypes.GROUPSHAPE__POSH );
return HorizontalPositioning.ABSOLUTE;
}
+ @Override
public HorizontalRelativeElement getHorizontalRelative()
{
int value = getTertiaryPropertyValue( EscherPropertyTypes.GROUPSHAPE__POSRELH );
return HorizontalRelativeElement.TEXT;
}
+ @Override
public EscherContainerRecord getOfficeArtSpContainer()
{
return getEscherShapeRecordContainer( getShapeId() );
}
+ @Override
public byte[] getPictureData()
{
EscherContainerRecord shapeDescription = getEscherShapeRecordContainer( getShapeId() );
return escherBlipRecord.getPicturedata();
}
+ @Override
public int getRectangleBottom()
{
return fspa.getYaBottom();
}
+ @Override
public int getRectangleLeft()
{
return fspa.getXaLeft();
}
+ @Override
public int getRectangleRight()
{
return fspa.getXaRight();
}
+ @Override
public int getRectangleTop()
{
return fspa.getYaTop();
}
+ @Override
public int getShapeId()
{
return fspa.getSpid();
return ( escherProperty == null ) ? -1 : escherProperty.getPropertyValue();
}
+ @Override
public VerticalPositioning getVerticalPositioning()
{
int value = getTertiaryPropertyValue( EscherPropertyTypes.GROUPSHAPE__POSV );
return VerticalPositioning.ABSOLUTE;
}
+ @Override
public VerticalRelativeElement getVerticalRelativeElement()
{
int value = getTertiaryPropertyValue( EscherPropertyTypes.GROUPSHAPE__POSV );
};
}
+ @Override
public OfficeDrawing getOfficeDrawingAt( int characterPosition )
{
final FSPA fspa = _fspaTable.getFspaFromCp( characterPosition );
return getOfficeDrawing( fspa );
}
+ @Override
public Collection<OfficeDrawing> getOfficeDrawings()
{
List<OfficeDrawing> result = new ArrayList<>();
}
/**
- * @return <tt>true</tt>, if table trailer paragraph (last in table row),
- * <tt>false</tt> otherwise
+ * @return {@code true}, if table trailer paragraph (last in table row),
+ * {@code false} otherwise
*/
public boolean isTableRowEnd()
{
}
/**
- * @return <tt>true</tt>, if the end of paragraph mark is really an end of
- * cell mark for a nested table cell, <tt>false</tt> otherwise
+ * @return {@code true}, if the end of paragraph mark is really an end of
+ * cell mark for a nested table cell, {@code false} otherwise
*/
public boolean isEmbeddedCellMark()
{
/**
* Picture types supported by MS Word format
- *
- * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
public enum PictureType
{
* @param newText
* The text to be replaced with
* @param addAfter
- * if <tt>true</tt> the text will be added at the end of current
+ * if {@code true} the text will be added at the end of current
* range, otherwise to the beginning
*/
public void replaceText( String newText, boolean addAfter )
* The replacement text (e.g., "Apache Software Foundation")
* @param pOffset
* The offset or index where the text to be replaced begins
- * (relative to/within this <code>Range</code>)
+ * (relative to/within this {@code Range})
*/
@Internal
public void replaceText(String pPlaceHolder, String pValue, int pOffset) {
/**
* Adjust the value of the various FIB character count fields, eg
- * <code>FIB.CCPText</code> after an insert or a delete...
+ * {@code FIB.CCPText} after an insert or a delete...
*
* Works on all CCP fields from this range onwards
*
public static InputStream openSampleFileStream(String sampleFileName) {
return _inst.openResourceAsStream(sampleFileName);
}
-
+
public static File getSampleFile(String sampleFileName) {
return _inst.getFile(sampleFileName);
}
-
+
public static byte[] getTestDataFileContent(String fileName) {
return _inst.readFile(fileName);
}
-
+
public static HSLFSlideShow getSlideShow(String fileName) throws IOException {
try (InputStream is = openSampleFileStream(fileName)) {
return new HSLFSlideShow(is);
}
/**
- * Writes a slideshow to a <tt>ByteArrayOutputStream</tt> and reads it back
- * from a <tt>ByteArrayInputStream</tt>.<p>
+ * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back
+ * from a {@code ByteArrayInputStream}.<p>
* Useful for verifying that the serialisation round trip
*/
public static HSLFSlideShowImpl writeOutAndReadBack(HSLFSlideShowImpl original) {
}
/**
- * Writes a slideshow to a <tt>ByteArrayOutputStream</tt> and reads it back
- * from a <tt>ByteArrayInputStream</tt>.<p>
+ * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back
+ * from a {@code ByteArrayInputStream}.<p>
* Useful for verifying that the serialisation round trip
*/
public static HSLFSlideShow writeOutAndReadBack(HSLFSlideShow original) {
/**
* Tests that HSLFSlideShow writes the powerpoint bit of data back out
* in a sane manner - i.e. records end up in the right place
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestReWriteSanity {
// HSLFSlideShow primed on the test data
* The Freeform shape is constructed from java.awt.GeneralPath.
* Check that the get/set path accessors are consistent.
* (TODO: verification of Bezier curves is more difficult due to rounding error. Figure out a test approach for that)
- *
- * @author Yegor Kozlov
*/
public final class TestFreeform {
/**
* Test setting text properties of newly added TextBoxes
- *
- * @author Yegor Kozlov
*/
public final class TestSetBoldItalic {
/**
import org.junit.jupiter.api.Test;
/**
- * Test common functionality of the <code>Sheet</code> object.
+ * Test common functionality of the {@code Sheet} object.
* For each ppt in the test directory check that all sheets are properly initialized
- *
- * @author Yegor Kozlov
*/
public final class TestSheet {
private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
/**
* Tests that changing a slide's idea of what notes sheet is its works right
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestSlideChangeNotes {
// SlideShow primed on the test data
/**
* Test adding new slides to a ppt.
*
- * Note - uses the same empty PPT file as the core "new Slideshow"
- * stuff does
- * @author Yegor Kozlov
+ * Note - uses the same empty PPT file as the core "new Slideshow" stuff does
*/
public final class TestSlides {
/**
* Tests that Comment2000 works properly.
* TODO: Test Comment200Atom within
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestComment2000 {
// From a real file
/**
* Tests that Comment2000Atom works properly.
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestComment2000Atom {
// From a real file
/**
* Tests that CurrentUserAtom works properly.
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestCurrentUserAtom {
private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
/**
* Tests that DocumentEncryptionAtom works properly.
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestDocumentEncryptionAtom {
// From a real file
/**
* Tests that {@link HeadersFootersAtom} works properly
- *
- * @author Yegor Kozlov
*/
public final class TestExVideoContainer {
/**
* Tests that StyleTextPropAtom works properly
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestStyleTextPropAtom {
/** From a real file: a paragraph with 4 different styles */
/**
* Tests TextSpecInfoAtom
- *
- * @author Yegor Kozlov
*/
public final class TestTextSpecInfoAtom {
/**
- * Test <code>Fill</code> object.
- *
- * @author Yegor Kozlov
+ * Test {@code Fill} object.
*/
public final class TestBackground {
private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
/**
* Test that checks numbered list functionality.
- *
- * @author Alex Nikiforov [mailto:anikif@gmail.com]
*/
public final class TestNumberedList {
private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
* if a paragraph has autonumber ()
* @see <a href="http://social.msdn.microsoft.com/Forums/mr-IN/os_binaryfile/thread/650888db-fabd-4b95-88dc-f0455f6e2d28">
* PPT: Missing TextAutoNumberScheme structure providing the style of the number bullets</a>
- *
- * @author Alex Nikiforov [mailto:anikif@gmail.com]
*/
public final class TestNumberedList3 {
private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
/**
* Test adding/reading pictures
- *
- * @author Yegor Kozlov
*/
public final class TestPictures {
private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
* Tests that the record setup done by SlideShow
* has worked correctly
* Note: most recent record stuff has its own test
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestRecordSetup {
// SlideShow primed on the test data
/**
* Tests that SystemTimeUtils works properly.
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestSystemTimeUtils {
// From real files
}
}
/**
- * Writes a spreadsheet to a <tt>ByteArrayOutputStream</tt> and reads it back
- * from a <tt>ByteArrayInputStream</tt>.<p>
+ * Writes a spreadsheet to a {@code ByteArrayOutputStream} and reads it back
+ * from a {@code ByteArrayInputStream}.<p>
* Useful for verifying that the serialisation round trip
*/
public static HWPFDocument writeOutAndReadBack(HWPFDocument original) {
/**
* Test the different routes to extracting text
- *
- * @author Nick Burch (nick at torchbox dot com)
*/
public final class TestDifferentRoutes {
private static final String[] p_text = new String[] {
/**
- * replaces the internal child list with the contents of the supplied <tt>childRecords</tt>
+ * replaces the internal child list with the contents of the supplied {@code childRecords}
*/
@Override
public void setChildRecords(List<EscherRecord> childRecords) {
/**
* This class stores the type and description of an escher property.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
public class EscherPropertyMetaData
{
* have a value of <code>-1 (true)</code> or <code>0 (false)</code>.
* Any other value would trigger this exception. It supports a nested
* "reason" throwable, i.e. an exception that caused this one to be
- * thrown.</p>
- *
- * @author Drew Varner(Drew.Varner atDomain sc.edu)
+ * thrown.
*/
public class IllegalPropertySetDataException extends HPSFRuntimeException
{
/**
* <p>Constructor</p>
- *
+ *
* @param msg The exception's message string
*/
public IllegalPropertySetDataException(final String msg)
/**
* <p>Constructor</p>
- *
+ *
* @param reason This exception's underlying reason
*/
public IllegalPropertySetDataException(final Throwable reason)
/**
* <p>Constructor</p>
- *
+ *
* @param msg The exception's message string
* @param reason This exception's underlying reason
*/
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-/**
- *
- * @author andy
- */
-
public class EFBiffViewer
{
String file;
/**
* FormulaViewer - finds formulas in a BIFF8 file and attempts to read them/display
* data from them. Only works if Formulas are enabled in "RecordFactory"
- * @author andy
- * @author Avik
*/
-
public class FormulaViewer
{
private String file;
public RecordCloner(List<Record> destList) {
_destList = destList;
}
+ @Override
public void visitRecord(Record r) {
_destList.add(r.copy());
}
import org.apache.poi.hssf.record.Record;
/**
- * Simplifies iteration over a sequence of <tt>Record</tt> objects.
+ * Simplifies iteration over a sequence of {@code Record} objects.
*/
public final class RecordStream {
}
/**
- * @return the {@link Class} of the next Record. <code>null</code> if this stream is exhausted.
+ * @return the {@link Class} of the next Record. {@code null} if this stream is exhausted.
*/
public Class<? extends Record> peekNextClass() {
if(!hasNext()) {
}
/**
- * @return the next Record. <code>null</code> if this stream is exhausted.
+ * @return the next Record. {@code null} if this stream is exhausted.
*/
public Record peekNextRecord() {
return (hasNext()) ? _list.get(_nextIndex) : null;
/**
* Also collects any loose MergeCellRecords and puts them in the supplied
* mergedCellsTable
- *
+ *
* @param rs the record stream
*/
public RowBlocksReader(RecordStream rs) {
/**
* Some unconventional apps place {@link MergeCellsRecord}s within the row block. They
* actually should be in the {@link MergedCellsTable} which is much later (see bug 45699).
- * @return any loose <tt>MergeCellsRecord</tt>s found
+ * @return any loose {@code MergeCellsRecord}s found
*/
public MergeCellsRecord[] getLooseMergedCells() {
return _mergedCellsRecords;
/**
* get the stack of the 2nd expression as a list
*
- * @return array of {@link Ptg}s, possibly <code>null</code>
+ * @return array of {@link Ptg}s, possibly {@code null}
*/
public Ptg[] getParsedExpression2() {
return Formula.getTokens(formula2);
}
/**
- * @param formula must not be <code>null</code>
+ * @param formula must not be {@code null}
* @return encoded size of the formula tokens (does not include 2 bytes for ushort length)
*/
protected static int getFormulaSize(Formula formula) {
*
* @param formula The formula to parse, excluding the leading equals sign.
* @param sheet The sheet that the formula is on.
- * @return <code>null</code> if <tt>formula</tt> was null.
+ * @return {@code null} if {@code formula} was null.
*/
public static Ptg[] parseFormula(String formula, HSSFSheet sheet) {
if(formula == null) {
* contain cell values. It allows the containing sheet to move through them and compare
* them.
*
- * @author Andrew C. Oliver (acoliver at apache dot org)
- * @author Jason Height (jheight at chariot dot net dot au)
- *
* @see org.apache.poi.hssf.record.Record
* @see org.apache.poi.hssf.record.RecordFactory
*/
}
/**
- * @return <code>null</code> if the double value encoded by <tt>valueLongBits</tt>
+ * @return {@code null} if the double value encoded by {@code valueLongBits}
* is a normal (non NaN) double value.
*/
public static FormulaSpecialCachedValue create(long valueLongBits) {
/**
* Handles the task of deserializing a SST string. The two main entry points are
- *
- * @author Glen Stampoultzis (glens at apache.org)
- * @author Jason Height (jheight at apache.org)
*/
class SSTDeserializer
{
/**
* This class handles serialization of SST records. It utilizes the record processor
* class write individual records. This has been refactored from the SSTRecord class.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
final class SSTSerializer {
return GenericRecordJsonWriter.marshal(this);
}
+ @Override
public void visitContainedRecords(RecordVisitor rv) {
rv.visitRecord(header);
for (CFRuleBase rule : rules) {
}
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
if (_recs.isEmpty()) {
return;
}
/**
* Inserts a column into the aggregate (at the position specified by
- * <code>idx</code>.
+ * {@code idx}.
*/
private void insertColumn(int idx, ColumnInfoRecord col) {
records.add(idx, col);
return records.size();
}
+ @Override
public void visitContainedRecords(RecordVisitor rv) {
int nItems = records.size();
if (nItems < 1) {
/**
* 'Collapsed' state is stored in a single column col info record immediately after the outline group
- * @param idx
* @return true, if the column is collapsed, false otherwise.
*/
private boolean isColumnGroupCollapsed(int idx) {
}
/**
- * Sets all non null fields into the <code>ci</code> parameter.
+ * Sets all non null fields into the {@code ci} parameter.
*/
private static void setColumnInfoFields(ColumnInfoRecord ci, Short xfStyle, Integer width,
Integer level, Boolean hidden, Boolean collapsed) {
}
/**
* merges two column info records (if they are adjacent and have the same formatting, etc)
- * @return <code>false</code> if the two column records could not be merged
+ * @return {@code false} if the two column records could not be merged
*/
private static boolean mergeColInfoRecords(ColumnInfoRecord ciA, ColumnInfoRecord ciB) {
if (ciA.isAdjacentBefore(ciB) && ciA.formatMatches(ciB)) {
* @param toColumnIx
* group to this column (inclusive)
* @param indent
- * if <code>true</code> the group will be indented by one
- * level, if <code>false</code> indenting will be decreased by
+ * if {@code true} the group will be indented by one
+ * level, if {@code false} indenting will be decreased by
* one level.
*/
public void groupColumnRange(int fromColumnIx, int toColumnIx, boolean indent) {
}
/**
- * Finds the <tt>ColumnInfoRecord</tt> which contains the specified columnIndex
+ * Finds the {@code ColumnInfoRecord} which contains the specified columnIndex
* @param columnIndex index of the column (not the index of the ColumnInfoRecord)
- * @return <code>null</code> if no column info found for the specified column
+ * @return {@code null} if no column info found for the specified column
*/
public ColumnInfoRecord findColumnInfo(int columnIndex) {
int nInfos = records.size();
}
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
for (CFRecordsAggregate subAgg : _cfHeaders) {
subAgg.visitContainedRecords(rv);
}
}
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
if (_recs.isEmpty()) {
return;
}
}
public void append(RecordBase r){
- _recs.add(r);
+ _recs.add(r);
}
}
_validationList = new ArrayList<>();
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
if (_validationList.isEmpty()) {
return;
}
return _formulaRecord.toString();
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
rv.visitRecord(_formulaRecord);
Record sharedFormulaRecord = _sharedValueManager.getRecordForFirstCell(this);
if (sharedFormulaRecord != null) {
}
}
+ @Override
public int getRecordSize() {
// a bit cheaper than the default impl
int nRegions = _mergedRegions.size();
+ CellRangeAddressList.getEncodedSize(nLeftoverMergedRegions);
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
int nRegions = _mergedRegions.size();
if (nRegions < 1) {
// no need to write a single empty MergeCellsRecord
import org.apache.poi.hssf.record.RecordBase;
/**
- * <tt>RecordAggregate</tt>s are groups of of BIFF <tt>Record</tt>s that are typically stored
+ * {@code RecordAggregate}s are groups of of BIFF {@code Record}s that are typically stored
* together and/or updated together. Workbook / Sheet records are typically stored in a sequential
* list, which does not provide much structure to coordinate updates.
*/
public abstract class RecordAggregate extends RecordBase {
/**
- * Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order
+ * Visit each of the atomic BIFF records contained in this RecordAggregate in the order
* that they should be written to file. Implementors may or may not return the actual
* {@link Record}s being used to manage POI's internal implementation. Callers should not
* assume either way, and therefore only attempt to modify those {@link Record}s after cloning
*/
public abstract void visitContainedRecords(RecordVisitor rv);
+ @Override
public final int serialize(int offset, byte[] data) {
SerializingRecordVisitor srv = new SerializingRecordVisitor(data, offset);
visitContainedRecords(srv);
return srv.countBytesWritten();
}
+ @Override
public int getRecordSize() {
RecordSizingVisitor rsv = new RecordSizingVisitor();
visitContainedRecords(rsv);
public interface RecordVisitor {
/**
* Implementors may call non-mutating methods on Record r.
- * @param r must not be <code>null</code>
+ * @param r must not be {@code null}
*/
void visitRecord(org.apache.poi.hssf.record.Record r);
}
public int countBytesWritten() {
return _countBytesWritten;
}
+ @Override
public void visitRecord(org.apache.poi.hssf.record.Record r) {
int currentOffset = _startOffset + _countBytesWritten;
_countBytesWritten += r.serialize(currentOffset, _data);
public int getTotalSize() {
return _totalSize;
}
+ @Override
public void visitRecord(org.apache.poi.hssf.record.Record r) {
_totalSize += r.getRecordSize();
}
_rv = rv;
_position = initialPosition;
}
+ @Override
public void visitRecord(org.apache.poi.hssf.record.Record r) {
_position += r.getRecordSize();
_rv.visitRecord(r);
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.formula.FormulaShifter;
-/**
- *
- * @author andy
- * @author Jason Height (jheight at chariot dot net dot au)
- */
public final class RowRecordsAggregate extends RecordAggregate {
private int _firstrow = -1;
private int _lastrow = -1;
* <li>{@link ArrayRecord}s</li>
* <li>{@link TableRecord}s</li>
* </ul>
- *
- * @author Josh Micich
- * @author Vladimirs Abramovs(Vladimirs.Abramovs at exigenservices.com) - handling of ArrayRecords
*/
public final class SharedValueManager {
}
/**
- * @return a new empty {@link SharedValueManager}.
+ * @return a new empty SharedValueManager.
*/
public static SharedValueManager createEmpty() {
// Note - must create distinct instances because they are assumed to be mutable.
/**
* @param firstCell as extracted from the {@link ExpPtg} from the cell's formula.
- * @return never <code>null</code>
+ * @return never {@code null}
*/
public SharedFormulaRecord linkSharedFormulaRecord(CellReference firstCell, FormulaRecordAggregate agg) {
SharedFormulaGroup result = findFormulaGroupForCell(firstCell);
* top left cell.
*
* @return the SHRFMLA, TABLE or ARRAY record for the formula cell, if it is the first cell of
- * a table or array region. <code>null</code> if the formula cell is not shared/array/table,
+ * a table or array region. {@code null} if the formula cell is not shared/array/table,
* or if the specified formula is not the the first in the group.
*/
public SharedValueRecordBase getRecordForFirstCell(FormulaRecordAggregate agg) {
}
/**
- * Converts all {@link FormulaRecord}s handled by <tt>sharedFormulaRecord</tt>
+ * Converts all {@link FormulaRecord}s handled by {@code sharedFormulaRecord}
* to plain unshared formulas
*/
public void unlink(SharedFormulaRecord sharedFormulaRecord) {
/**
* Removes the {@link ArrayRecord} for the cell group containing the specified cell.
* The caller should clear (set blank) all cells in the returned range.
- * @return the range of the array formula which was just removed. Never <code>null</code>.
+ * @return the range of the array formula which was just removed. Never {@code null}.
*/
public CellRangeAddress8Bit removeArrayFormula(int rowIndex, int columnIndex) {
for (ArrayRecord ar : _arrayRecords) {
}
/**
- * @return the shared ArrayRecord identified by (firstRow, firstColumn). never <code>null</code>.
+ * @return the shared ArrayRecord identified by (firstRow, firstColumn). never {@code null}.
*/
public ArrayRecord getArrayRecord(int firstRow, int firstColumn) {
for(ArrayRecord ar : _arrayRecords) {
/**
*
* Aggregate value records together. Things are easier to handle that way.
- *
- * @author andy
- * @author Glen Stampoultzis (glens at apache.org)
- * @author Jason Height (jheight at chariot dot net dot au)
*/
public final class ValueRecordsAggregate implements Iterable<CellValueRecordInterface> {
private static final int MAX_ROW_INDEX = 0XFFFF;
import org.apache.poi.hssf.record.ObjectProtectRecord;
import org.apache.poi.hssf.record.PasswordRecord;
import org.apache.poi.hssf.record.ProtectRecord;
-import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.ScenarioProtectRecord;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.util.RecordFormatException;
*
* See OOO excelfileformat.pdf sec 4.18.2 'Sheet Protection in a Workbook
* (BIFF5-BIFF8)'
- *
- * @author Josh Micich
*/
public final class WorksheetProtectionBlock extends RecordAggregate {
// Every one of these component records is optional
}
/**
- * @return <code>true</code> if the specified Record sid is one belonging to
+ * @return {@code true} if the specified Record sid is one belonging to
* the 'Page Settings Block'.
*/
public static boolean isComponentRecord(int sid) {
}
}
- public void visitContainedRecords(RecordVisitor rv) {
+ @Override
+ public void visitContainedRecords(RecordVisitor rv) {
// Replicates record order from Excel 2007, though this is not critical
visitIfPresent(_protectRecord, rv);
}
/**
- * This method reads {@link WorksheetProtectionBlock} records from the supplied RecordStream
+ * This method reads WorksheetProtectionBlock records from the supplied RecordStream
* until the first non-WorksheetProtectionBlock record is encountered. As each record is read,
* it is incorporated into this WorksheetProtectionBlock.
* <p>
* protect a spreadsheet with a password (not encrypted, just sets protect
* flags and the password.
*
- * @param password to set. Pass <code>null</code> to remove all protection
+ * @param password to set. Pass {@code null} to remove all protection
* @param shouldProtectObjects are protected
* @param shouldProtectScenarios are protected
*/
* Notes:
* <ul>
* <li>The value of the 'is16bitEncoded' flag is determined by the actual character data
- * of <tt>text</tt></li>
+ * of {@code text}</li>
* <li>The string options flag is never separated (by a {@link ContinueRecord}) from the
* first chunk of character data it refers to.</li>
* <li>The 'ushort length' field is assumed to have been explicitly written earlier. Hence,
* Notes:
* <ul>
* <li>The value of the 'is16bitEncoded' flag is determined by the actual character data
- * of <tt>text</tt></li>
+ * of {@code text}</li>
* <li>The string header fields are never separated (by a {@link ContinueRecord}) from the
* first chunk of character data (i.e. the first character is always encoded in the same
* record as the string header).</li>
}
} else {
while(true) {
- int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 1);
+ int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace());
for ( ; nWritableChars > 0; nWritableChars--) {
_ulrOutput.writeByte(text.charAt(i++));
}
}
}
+ @Override
public void write(byte[] b) {
writeContinueIfRequired(b.length);
_ulrOutput.write(b);
}
+ @Override
public void write(byte[] b, int offset, int len) {
int i=0;
while(true) {
- int nWritableChars = Math.min(len - i, _ulrOutput.getAvailableSpace() / 1);
+ int nWritableChars = Math.min(len - i, _ulrOutput.getAvailableSpace());
for ( ; nWritableChars > 0; nWritableChars--) {
_ulrOutput.writeByte(b[offset + i++]);
}
}
}
+ @Override
public void writeByte(int v) {
writeContinueIfRequired(1);
_ulrOutput.writeByte(v);
}
+ @Override
public void writeDouble(double v) {
writeContinueIfRequired(8);
_ulrOutput.writeDouble(v);
}
+ @Override
public void writeInt(int v) {
writeContinueIfRequired(4);
_ulrOutput.writeInt(v);
}
+ @Override
public void writeLong(long v) {
writeContinueIfRequired(8);
_ulrOutput.writeLong(v);
}
+ @Override
public void writeShort(int v) {
writeContinueIfRequired(2);
_ulrOutput.writeShort(v);
*/
private static final LittleEndianOutput NOPOutput = new DelayableLittleEndianOutput() {
+ @Override
public LittleEndianOutput createDelayedOutput(int size) {
return this;
}
+ @Override
public void write(byte[] b) {
// does nothing
}
+ @Override
public void write(byte[] b, int offset, int len) {
// does nothing
}
+ @Override
public void writeByte(int v) {
// does nothing
}
+ @Override
public void writeDouble(double v) {
// does nothing
}
+ @Override
public void writeInt(int v) {
// does nothing
}
+ @Override
public void writeLong(long v) {
// does nothing
}
+ @Override
public void writeShort(int v) {
// does nothing
}
//arbitrarily selected; may need to increase
private static final int MAX_RECORD_LENGTH = 100_000;
- private ChunkedCipherInputStream ccis;
+ private final ChunkedCipherInputStream ccis;
private final byte[] buffer = new byte[LittleEndianConsts.LONG_SIZE];
private boolean shouldSkipEncryptionOnCurrentRecord;
Decryptor dec = info.getDecryptor();
dec.setChunkSize(RC4_REKEYING_INTERVAL);
ccis = (ChunkedCipherInputStream)dec.getDataStream(stream, Integer.MAX_VALUE, 0);
-
+
if (initialOffset > 0) {
ccis.readFully(initialBuf);
}
public int readUByte() {
return readByte() & 0xFF;
}
-
+
@Override
public byte readByte() {
if (shouldSkipEncryptionOnCurrentRecord) {
public int readUShort() {
return readShort() & 0xFFFF;
}
-
+
@Override
public short readShort() {
if (shouldSkipEncryptionOnCurrentRecord) {
public long getPosition() {
return ccis.getPos();
}
-
+
/**
* TODO: Additionally, the lbPlyPos (position_of_BOF) field of the BoundSheet8 record MUST NOT be encrypted.
*
- * @return <code>true</code> if record type specified by <tt>sid</tt> is never encrypted
+ * @return {@code true} if record type specified by {@code sid} is never encrypted
*/
public static boolean isNeverEncryptedRecord(int sid) {
switch (sid) {
public final class ViewFieldsRecord extends StandardRecord {
public static final short sid = 0x00B1;
- /** the value of the <tt>cchName</tt> field when the {@link #_name} is not present */
+ /** the value of the {@code cchName} field when the {@link #_name} is not present */
private static final int STRING_NOT_PRESENT_LEN = 0xFFFF;
/** 5 shorts */
private static final int BASE_SIZE = 10;
- private int _sxaxis;
- private int _cSub;
- private int _grbitSub;
- private int _cItm;
+ private final int _sxaxis;
+ private final int _cSub;
+ private final int _grbitSub;
+ private final int _cItm;
private String _name;
COLUMN(2),
PAGE(4),
DATA(8);
- int id;
+ final int id;
Axis(int id) {
this.id = id;
}
public Ptg[] getFormula2() {
return _formula2;
}
-
+
}
-
+
private final int _validationType;
private int _operator;
private String[] _explicitListValues;
-
+
private String _formula1;
private String _formula2;
private Double _value1;
private Double _value2;
-
+
private DVConstraint(int validationType, int comparisonOperator, String formulaA,
String formulaB, Double value1, Double value2, String[] explicitListValues) {
_validationType = validationType;
_value2 = value2;
_explicitListValues = (explicitListValues == null) ? null : explicitListValues.clone();
}
-
-
+
+
/**
* Creates a list constraint
*/
/**
* Creates a number based data validation constraint. The text values entered for expr1 and expr2
- * can be either standard Excel formulas or formatted number values. If the expression starts
- * with '=' it is parsed as a formula, otherwise it is parsed as a formatted number.
- *
+ * can be either standard Excel formulas or formatted number values. If the expression starts
+ * with '=' it is parsed as a formula, otherwise it is parsed as a formatted number.
+ *
* @param validationType one of {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#ANY},
* {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#DECIMAL},
* {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#INTEGER},
* @param expr1 date formula (when first char is '=') or formatted number value
* @param expr2 date formula (when first char is '=') or formatted number value
*/
- public static DVConstraint createNumericConstraint(int validationType, int comparisonOperator,
+ public static DVConstraint createNumericConstraint(int validationType, int comparisonOperator,
String expr1, String expr2) {
switch (validationType) {
case ValidationType.ANY:
public static DVConstraint createExplicitListConstraint(String[] explicitListValues) {
return new DVConstraint(null, explicitListValues);
}
-
-
+
+
/**
* Creates a time based data validation constraint. The text values entered for expr1 and expr2
- * can be either standard Excel formulas or formatted time values. If the expression starts
- * with '=' it is parsed as a formula, otherwise it is parsed as a formatted time. To parse
- * formatted times, two formats are supported: "HH:MM" or "HH:MM:SS". This is contrary to
+ * can be either standard Excel formulas or formatted time values. If the expression starts
+ * with '=' it is parsed as a formula, otherwise it is parsed as a formatted time. To parse
+ * formatted times, two formats are supported: "HH:MM" or "HH:MM:SS". This is contrary to
* Excel which uses the default time format from the OS.
- *
+ *
* @param comparisonOperator constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum
* @param expr1 date formula (when first char is '=') or formatted time value
* @param expr2 date formula (when first char is '=') or formatted time value
throw new IllegalArgumentException("expr1 must be supplied");
}
OperatorType.validateSecondArg(comparisonOperator, expr1);
-
+
// formula1 and value1 are mutually exclusive
String formula1 = getFormulaFromTextExpression(expr1);
Double value1 = formula1 == null ? convertTime(expr1) : null;
Double value2 = formula2 == null ? convertTime(expr2) : null;
return new DVConstraint(ValidationType.TIME, comparisonOperator, formula1, formula2, value1, value2, null);
}
-
+
/**
* Creates a date based data validation constraint. The text values entered for expr1 and expr2
- * can be either standard Excel formulas or formatted date values. If the expression starts
- * with '=' it is parsed as a formula, otherwise it is parsed as a formatted date (Excel uses
+ * can be either standard Excel formulas or formatted date values. If the expression starts
+ * with '=' it is parsed as a formula, otherwise it is parsed as a formatted date (Excel uses
* the same convention). To parse formatted dates, a date format needs to be specified. This
* is contrary to Excel which uses the default short date format from the OS.
- *
+ *
* @param comparisonOperator constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum
* @param expr1 date formula (when first char is '=') or formatted date value
* @param expr2 date formula (when first char is '=') or formatted date value
* @param dateFormat ignored if both expr1 and expr2 are formulas. Default value is "YYYY/MM/DD"
- * otherwise any other valid argument for <tt>SimpleDateFormat</tt> can be used
+ * otherwise any other valid argument for {@code SimpleDateFormat} can be used
* @see <a href='http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html'>SimpleDateFormat</a>
*/
public static DVConstraint createDateConstraint(int comparisonOperator, String expr1, String expr2, String dateFormat) {
df = new SimpleDateFormat(dateFormat, LocaleUtil.getUserLocale());
df.setTimeZone(LocaleUtil.getUserTimeZone());
}
-
+
// formula1 and value1 are mutually exclusive
String formula1 = getFormulaFromTextExpression(expr1);
Double value1 = formula1 == null ? convertDate(expr1, df) : null;
Double value2 = formula2 == null ? convertDate(expr2, df) : null;
return new DVConstraint(ValidationType.DATE, comparisonOperator, formula1, formula2, value1, value2, null);
}
-
+
/**
- * Distinguishes formula expressions from simple value expressions. This logic is only
+ * Distinguishes formula expressions from simple value expressions. This logic is only
* required by a few factory methods in this class that create data validation constraints
* from more or less the same parameters that would have been entered in the Excel UI. The
* data validation dialog box uses the convention that formulas begin with '='. Other methods
- * in this class follow the POI convention (formulas and values are distinct), so the '='
+ * in this class follow the POI convention (formulas and values are distinct), so the '='
* convention is not used there.
- *
+ *
* @param textExpr a formula or value expression
- * @return all text after '=' if textExpr begins with '='. Otherwise <code>null</code> if textExpr does not begin with '='
+ * @return all text after '=' if textExpr begins with '='. Otherwise {@code null} if textExpr does not begin with '='
*/
private static String getFormulaFromTextExpression(String textExpr) {
if (textExpr == null) {
/**
- * @return <code>null</code> if numberStr is <code>null</code>
+ * @return {@code null} if numberStr is {@code null}
*/
private static Double convertNumber(String numberStr) {
if (numberStr == null) {
try {
return Double.valueOf(numberStr);
} catch (NumberFormatException e) {
- throw new RuntimeException("The supplied text '" + numberStr
+ throw new RuntimeException("The supplied text '" + numberStr
+ "' could not be parsed as a number");
}
}
/**
- * @return <code>null</code> if timeStr is <code>null</code>
+ * @return {@code null} if timeStr is {@code null}
*/
private static Double convertTime(String timeStr) {
if (timeStr == null) {
return null;
}
- return Double.valueOf(DateUtil.convertTime(timeStr));
+ return DateUtil.convertTime(timeStr);
}
/**
- * @param dateFormat pass <code>null</code> for default YYYYMMDD
- * @return <code>null</code> if timeStr is <code>null</code>
+ * @param dateFormat pass {@code null} for default YYYYMMDD
+ * @return {@code null} if timeStr is {@code null}
*/
private static Double convertDate(String dateStr, SimpleDateFormat dateFormat) {
if (dateStr == null) {
return null;
}
- Date dateVal;
+ Date dateVal;
if (dateFormat == null) {
dateVal = DateUtil.parseYYYYMMDDDate(dateStr);
} else {
try {
dateVal = dateFormat.parse(dateStr);
} catch (ParseException e) {
- throw new RuntimeException("Failed to parse date '" + dateStr
+ throw new RuntimeException("Failed to parse date '" + dateStr
+ "' using specified format '" + dateFormat + "'", e);
}
}
- return Double.valueOf(DateUtil.getExcelDate(dateVal));
+ return DateUtil.getExcelDate(dateVal);
}
public static DVConstraint createCustomFormulaConstraint(String formula) {
}
return new DVConstraint(ValidationType.FORMULA, OperatorType.IGNORED, formula, null, null, null, null);
}
-
+
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getValidationType()
*/
+ @Override
public int getValidationType() {
return _validationType;
}
/**
* Convenience method
- * @return <code>true</code> if this constraint is a 'list' validation
+ * @return {@code true} if this constraint is a 'list' validation
*/
public boolean isListValidationType() {
return _validationType == ValidationType.LIST;
}
/**
* Convenience method
- * @return <code>true</code> if this constraint is a 'list' validation with explicit values
+ * @return {@code true} if this constraint is a 'list' validation with explicit values
*/
public boolean isExplicitList() {
return _validationType == ValidationType.LIST && _explicitListValues != null;
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getOperator()
*/
+ @Override
public int getOperator() {
return _operator;
}
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setOperator(int)
*/
+ @Override
public void setOperator(int operator) {
_operator = operator;
}
-
+
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getExplicitListValues()
*/
+ @Override
public String[] getExplicitListValues() {
return _explicitListValues;
}
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setExplicitListValues(java.lang.String[])
*/
+ @Override
public void setExplicitListValues(String[] explicitListValues) {
if (_validationType != ValidationType.LIST) {
throw new RuntimeException("Cannot setExplicitListValues on non-list constraint");
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getFormula1()
*/
+ @Override
public String getFormula1() {
return _formula1;
}
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setFormula1(java.lang.String)
*/
+ @Override
public void setFormula1(String formula1) {
_value1 = null;
_explicitListValues = null;
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getFormula2()
*/
+ @Override
public String getFormula2() {
return _formula2;
}
/* (non-Javadoc)
* @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setFormula2(java.lang.String)
*/
+ @Override
public void setFormula2(String formula2) {
_value2 = null;
_formula2 = formula2;
}
/**
- * @return the numeric value for expression 1. May be <code>null</code>
+ * @return the numeric value for expression 1. May be {@code null}
*/
public Double getValue1() {
return _value1;
*/
public void setValue1(double value1) {
_formula1 = null;
- _value1 = Double.valueOf(value1);
+ _value1 = value1;
}
/**
- * @return the numeric value for expression 2. May be <code>null</code>
+ * @return the numeric value for expression 2. May be {@code null}
*/
public Double getValue2() {
return _value2;
*/
public void setValue2(double value2) {
_formula2 = null;
- _value2 = Double.valueOf(value2);
+ _value2 = value2;
}
-
+
/**
- * @return both parsed formulas (for expression 1 and 2).
+ * @return both parsed formulas (for expression 1 and 2).
*/
/* package */ FormulaPair createFormulas(HSSFSheet sheet) {
Ptg[] formula1;
sb.append('\0'); // list delimiter is the nul char
}
sb.append(_explicitListValues[i]);
-
+
}
return new Ptg[] { new StringPtg(sb.toString()), };
}
/**
- * @return The parsed token array representing the formula or value specified.
- * Empty array if both formula and value are <code>null</code>
+ * @return The parsed token array representing the formula or value specified.
+ * Empty array if both formula and value are {@code null}
*/
@SuppressWarnings("resource")
private static Ptg[] convertDoubleFormula(String formula, Double value, HSSFSheet sheet) {
if (value == null) {
return Ptg.EMPTY_PTG_ARRAY;
}
- return new Ptg[] { new NumberPtg(value.doubleValue()), };
+ return new Ptg[] { new NumberPtg(value), };
}
if (value != null) {
throw new IllegalStateException("Both formula and value cannot be present");
}
HSSFWorkbook wb = sheet.getWorkbook();
return HSSFFormulaParser.parse(formula, wb, FormulaType.CELL, wb.getSheetIndex(sheet));
- }
+ }
static DVConstraint createDVConstraint(DVRecord dvRecord, FormulaRenderingWorkbook book) {
switch (dvRecord.getDataType()) {
import org.apache.poi.ss.util.CellRangeAddress;
/**
- * HSSFConditionalFormatting class encapsulates all settings of Conditional Formatting.
- *
- * The class can be used
- *
- * <UL>
- * <LI>
- * to make a copy HSSFConditionalFormatting settings.
- * </LI>
- *
- *
+ * HSSFConditionalFormatting class encapsulates all settings of Conditional Formatting.
+ *
+ * The class can be used to make a copy HSSFConditionalFormatting settings.
+ *
+ *
* For example:
- * <PRE>
+ * <pre>{@code
* HSSFConditionalFormatting cf = sheet.getConditionalFormattingAt(index);
* newSheet.addConditionalFormatting(cf);
- * </PRE>
- *
- * <LI>
- * or to modify existing Conditional Formatting settings (formatting regions and/or rules).
- * </LI>
- * </UL>
- *
+ * }</pre>
+ *
+ * or to modify existing Conditional Formatting settings (formatting regions and/or rules).<p>
+ *
* Use {@link org.apache.poi.hssf.usermodel.HSSFSheet#getSheetConditionalFormatting()} to get access to an instance of this class.
* <P>
* To create a new Conditional Formatting set use the following approach:
- *
- * <PRE>
- *
+ *
+ * <pre>{@code
* // Define a Conditional Formatting rule, which triggers formatting
* // when cell's value is greater or equal than 100.0 and
* // applies patternFormatting defined below.
* HSSFConditionalFormattingRule rule = sheet.createConditionalFormattingRule(
- * ComparisonOperator.GE,
- * "100.0", // 1st formula
+ * ComparisonOperator.GE,
+ * "100.0", // 1st formula
* null // 2nd formula is not used for comparison operator GE
* );
- *
+ *
* // Create pattern with red background
* HSSFPatternFormatting patternFmt = rule.cretePatternFormatting();
* patternFormatting.setFillBackgroundColor(HSSFColor.RED.index);
- *
+ *
* // Define a region containing first column
- * Region [] regions =
- * {
+ * Region [] regions = {
* new Region(1,(short)1,-1,(short)1)
* };
- *
- * // Apply Conditional Formatting rule defined above to the regions
+ *
+ * // Apply Conditional Formatting rule defined above to the regions
* sheet.addConditionalFormatting(regions, rule);
- * </PRE>
+ * }</pre>
*/
public final class HSSFConditionalFormatting implements ConditionalFormatting {
private final HSSFSheet sheet;
if(cfAggregate == null) {
throw new IllegalArgumentException("cfAggregate must not be null");
}
- this.sheet = sheet;
+ this.sheet = sheet;
this.cfAggregate = cfAggregate;
}
CFRecordsAggregate getCFRecordsAggregate() {
}
/**
- * @return array of <tt>CellRangeAddress</tt>s. never <code>null</code>
+ * @return array of {@code CellRangeAddress}s. never {@code null}
*/
@Override
public CellRangeAddress[] getFormattingRanges() {
}
/**
- * Replaces an existing Conditional Formatting rule at position idx.
+ * Replaces an existing Conditional Formatting rule at position idx.
* Older versions of Excel only allow up to 3 Conditional Formatting rules,
* and will ignore rules beyond that, while newer versions are fine.
* This method can be useful to modify existing Conditional Formatting rules.
- *
+ *
* @param idx position of the rule. Should be between 0 and 2 for older Excel versions
* @param cfRule - Conditional Formatting rule
*/
}
/**
- * add a Conditional Formatting rule.
+ * add a Conditional Formatting rule.
* Excel allows to create up to 3 Conditional Formatting rules.
* @param cfRule - Conditional Formatting rule
*/
import org.apache.poi.ss.util.CellRangeAddress;
/**
- * The 'Conditional Formatting' facet of <tt>HSSFSheet</tt>
+ * The 'Conditional Formatting' facet of {@code HSSFSheet}
*/
public final class HSSFSheetConditionalFormatting implements SheetConditionalFormatting {
private final HSSFSheet _sheet;
* TODO - formulas containing cell references are currently not parsed properly
*
* @param comparisonOperation - a constant value from
- * <tt>{@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}</tt>: <p>
+ * {@code {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}}:
* <ul>
* <li>BETWEEN</li>
* <li>NOT_BETWEEN</li>
* <li>GE</li>
* <li>LE</li>
* </ul>
- * </p>
+ *
* @param formula1 - formula for the valued, compared with the cell
* @param formula2 - second formula (only used with
* {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator#BETWEEN}) and
* {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator#NOT_BETWEEN} operations)
*/
+ @Override
public HSSFConditionalFormattingRule createConditionalFormattingRule(
byte comparisonOperation,
String formula1,
return new HSSFConditionalFormattingRule(_sheet, rr);
}
+ @Override
public HSSFConditionalFormattingRule createConditionalFormattingRule(
byte comparisonOperation,
String formula1) {
* TODO - formulas containing cell references are currently not parsed properly
* @param formula - formula for the valued, compared with the cell
*/
+ @Override
public HSSFConditionalFormattingRule createConditionalFormattingRule(String formula) {
CFRuleRecord rr = CFRuleRecord.create(_sheet, formula);
return new HSSFConditionalFormattingRule(_sheet, rr);
* then
* {@link HSSFIconMultiStateFormatting#getThresholds()}
*/
+ @Override
public HSSFConditionalFormattingRule createConditionalFormattingRule(
IconSet iconSet) {
CFRule12Record rr = CFRule12Record.create(_sheet, iconSet);
CFRule12Record rr = CFRule12Record.create(_sheet, color.getExtendedColor());
return new HSSFConditionalFormattingRule(_sheet, rr);
}
+ @Override
public HSSFConditionalFormattingRule createConditionalFormattingRule(ExtendedColor color) {
return createConditionalFormattingRule((HSSFExtendedColor)color);
}
* and
* {@link HSSFColorScaleFormatting#getColors()}
*/
+ @Override
public HSSFConditionalFormattingRule createConditionalFormattingColorScaleRule() {
CFRule12Record rr = CFRule12Record.createColorScale(_sheet);
return new HSSFConditionalFormattingRule(_sheet, rr);
return _conditionalFormattingTable.add(cfraClone);
}
+ @Override
public int addConditionalFormatting( ConditionalFormatting cf ) {
return addConditionalFormatting((HSSFConditionalFormatting)cf);
}
return _conditionalFormattingTable.add(cfra);
}
+ @Override
public int addConditionalFormatting(CellRangeAddress[] regions, ConditionalFormattingRule[] cfRules) {
HSSFConditionalFormattingRule[] hfRules;
if(cfRules instanceof HSSFConditionalFormattingRule[]) {
);
}
+ @Override
public int addConditionalFormatting(CellRangeAddress[] regions,
ConditionalFormattingRule rule1) {
return addConditionalFormatting(regions, (HSSFConditionalFormattingRule)rule1);
new HSSFConditionalFormattingRule[] { rule1, rule2 });
}
+ @Override
public int addConditionalFormatting(CellRangeAddress[] regions,
ConditionalFormattingRule rule1,
ConditionalFormattingRule rule2) {
* of the Conditional Formatting object to fetch
* @return Conditional Formatting object
*/
+ @Override
public HSSFConditionalFormatting getConditionalFormattingAt(int index) {
CFRecordsAggregate cf = _conditionalFormattingTable.get(index);
if (cf == null) {
/**
* @return number of Conditional Formatting objects of the sheet
*/
+ @Override
public int getNumConditionalFormattings() {
return _conditionalFormattingTable.size();
}
* removes a Conditional Formatting object by index
* @param index of a Conditional Formatting object to remove
*/
+ @Override
public void removeConditionalFormatting(int index) {
_conditionalFormattingTable.remove(index);
}
* this holds the HSSFName objects attached to this workbook
*/
- private ArrayList<HSSFName> names;
+ private final ArrayList<HSSFName> names;
/**
* this holds the HSSFFont objects attached to this workbook.
* The locator of user-defined functions.
* By default includes functions from the Excel Analysis Toolpack
*/
- private UDFFinder _udfFinder = new IndexedUDFFinder(AggregatingUDFFinder.DEFAULT);
+ private final UDFFinder _udfFinder = new IndexedUDFFinder(AggregatingUDFFinder.DEFAULT);
public static HSSFWorkbook create(InternalWorkbook book) {
return new HSSFWorkbook(book);
/**
* Selects multiple sheets as a group. This is distinct from
* the 'active' sheet (which is the sheet with focus).
- * Unselects sheets that are not in <code>indexes</code>.
+ * Unselects sheets that are not in {@code indexes}.
*
* @param indexes Array of sheets to select, the index is 0-based.
*/
/**
* Selects multiple sheets as a group. This is distinct from
* the 'active' sheet (which is the sheet with focus).
- * Unselects sheets that are not in <code>indexes</code>.
+ * Unselects sheets that are not in {@code indexes}.
*
* @param indexes Collection of sheets to select, the index is 0-based.
*/
* Returns the index of the given sheet
*
* @param sheet the sheet to look up
- * @return index of the sheet (0 based). <tt>-1</tt> if not found
+ * @return index of the sheet (0 based). {@code -1} if not found
*/
@Override
public int getSheetIndex(Sheet sheet) {
* POI's SpreadsheetAPI silently truncates the input argument to 31 characters.
* Example:
*
- * <pre><code>
+ * <pre>{@code
* Sheet sheet = workbook.createSheet("My very long sheet name which is longer than 31 chars"); // will be truncated
* assert 31 == sheet.getSheetName().length();
* assert "My very long sheet name which i" == sheet.getSheetName();
- * </code></pre>
+ * }</pre>
* </p>
* <p>
* Except the 31-character constraint, Excel applies some other rules:
* Get sheet with the given name (case insensitive match)
*
* @param name of the sheet
- * @return HSSFSheet with the name provided or <code>null</code> if it does not exist
+ * @return HSSFSheet with the name provided or {@code null} if it does not exist
*/
@Override
}
/**
- * Removes sheet at the given index.<p>
+ * Removes sheet at the given index.
* <p>
* Care must be taken if the removed sheet is the currently active or only selected sheet in
* the workbook. There are a few situations when Excel must have a selection and/or active
*/
private static final class SheetRecordCollector implements RecordVisitor {
- private List<Record> _list;
+ private final List<Record> _list;
private int _totalSize;
public SheetRecordCollector() {
* Adds a picture to the workbook.
*
* @param pictureData The bytes of the picture
- * @param format The format of the picture. One of <code>PICTURE_TYPE_*</code>
+ * @param format The format of the picture. One of {@code PICTURE_TYPE_*}
* @return the index to this picture (1 based).
* @see #PICTURE_TYPE_WMF
* @see #PICTURE_TYPE_EMF
private static Map<Integer,HSSFColor> indexHash;
private static Map<HSSFColorPredefined,HSSFColor> enumList;
- private java.awt.Color color;
- private int index;
- private int index2;
+ private final java.awt.Color color;
+ private final int index;
+ private final int index2;
/**
* Predefined HSSFColors with their given palette index (and an optional 2nd index)
*/
AUTOMATIC (0x40, -1, 0x000000);
- private HSSFColor color;
+ private final HSSFColor color;
HSSFColorPredefined(int index, int index2, int rgb) {
this.color = new HSSFColor(index, index2, new java.awt.Color(rgb));
* This function returns all the colours in an unmodifiable Map.
* The map is cached on first use.
*
- * @return a Map containing all colours keyed by <tt>Integer</tt> excel-style palette indexes
+ * @return a Map containing all colours keyed by {@code Integer} excel-style palette indexes
*/
public static synchronized Map<Integer,HSSFColor> getIndexHash() {
if(indexHash == null) {
if (index != hssfColor.index) return false;
if (index2 != hssfColor.index2) return false;
- return color != null ? color.equals(hssfColor.color) : hssfColor.color == null;
+ return Objects.equals(color, hssfColor.color);
}
@Override
}
/**
- * Checked type cast <tt>color</tt> to an HSSFColor.
+ * Checked type cast {@code color} to an HSSFColor.
*
* @param color the color to type cast
* @return the type casted color
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.dev;
/**
* This class contains methods used to inspect POIFSViewable objects
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public class POIFSViewEngine
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.dev;
* A POIFSViewable object is also expected to provide a short
* description of itself, that can be used by a viewer when the
* viewable object is collapsed.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface POIFSViewable
*/
public Object [] getViewableArray();
-
+
/**
* Get an Iterator of objects, some of which may implement
* POIFSViewable
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.dev;
/**
* A simple viewer for POIFS files
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public final class POIFSViewer {
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.eventfilesystem;
/**
* Interface POIFSReaderListener
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
public interface POIFSReaderListener
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.eventfilesystem;
/**
* A registry for POIFSReaderListeners and the DocumentDescriptors of
* the documents those listeners are interested in
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
class POIFSReaderRegistry
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
/**
* This interface defines behaviors for objects managed by the Block
* Allocation Table (BAT).
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface BATManaged
/**
* This interface defines methods specific to Directory objects
* managed by a Filesystem instance.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface DirectoryEntry
*/
public Iterator<Entry> getEntries();
-
+
/**
* get the names of all the Entries contained directly in this
* instance (in other words, names of children only; no grandchildren
* etc).
*
* @return the names of all the entries that may be retrieved with
- * getEntry(String), which may be empty (if this
+ * getEntry(String), which may be empty (if this
* DirectoryEntry is empty)
*/
public Set<String> getEntryNames();
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
/**
* Class DocumentDescriptor
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
public class DocumentDescriptor
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
/**
* This interface defines methods specific to Document objects
* managed by a Filesystem instance.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface DocumentEntry
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
* This interface provides access to an object managed by a Filesystem
* instance. Entry objects are further divided into DocumentEntry and
* DirectoryEntry instances.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface Entry
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
* appropriate
*
* Extending classes must override isDeleteOK()
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public abstract class EntryNode
/**
* Maximum number size (in blocks) of the allocation table as supported by
- * POI.<p>
+ * POI.
* <p>
* This constant has been chosen to help POI identify corrupted data in the
* header block (rather than crash immediately with {@link OutOfMemoryError}
}
/**
- * <p>Creates a POIFSFileSystem from a <tt>File</tt>. This uses less memory than
- * creating from an <tt>InputStream</tt>. The File will be opened read-only</p>
+ * <p>Creates a POIFSFileSystem from a {@code File}. This uses less memory than
+ * creating from an {@code InputStream}. The File will be opened read-only</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying file closed, as the file is
}
/**
- * <p>Creates a POIFSFileSystem from a <tt>File</tt>. This uses less memory than
- * creating from an <tt>InputStream</tt>.</p>
+ * <p>Creates a POIFSFileSystem from a {@code File}. This uses less memory than
+ * creating from an {@code InputStream}.</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying file closed, as the file is
}
/**
- * <p>Creates a POIFSFileSystem from an open <tt>FileChannel</tt>. This uses
- * less memory than creating from an <tt>InputStream</tt>. The stream will
+ * <p>Creates a POIFSFileSystem from an open {@code FileChannel}. This uses
+ * less memory than creating from an {@code InputStream}. The stream will
* be used in read-only mode.</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
}
/**
- * <p>Creates a POIFSFileSystem from an open <tt>FileChannel</tt>. This uses
- * less memory than creating from an <tt>InputStream</tt>.</p>
+ * <p>Creates a POIFSFileSystem from an open {@code FileChannel}. This uses
+ * less memory than creating from an {@code InputStream}.</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying Channel closed, as the channel is
}
/**
- * Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until
- * EOF. The stream is always closed.<p>
+ * Create a POIFSFileSystem from an {@code InputStream}. Normally the stream is read until
+ * EOF. The stream is always closed.
* <p>
- * Some streams are usable after reaching EOF (typically those that return <code>true</code>
- * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream
+ * Some streams are usable after reaching EOF (typically those that return {@code true}
+ * for {@code markSupported()}). In the unlikely case that the caller has such a stream
* <i>and</i> needs to use it after this constructor completes, a work around is to wrap the
- * stream in order to trap the <tt>close()</tt> call. A convenience method (
- * <tt>createNonClosingInputStream()</tt>) has been provided for this purpose:
+ * stream in order to trap the {@code close()} call. A convenience method (
+ * {@code createNonClosingInputStream()}) has been provided for this purpose:
* <pre>
* InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is);
* HSSFWorkbook wb = new HSSFWorkbook(wrappedStream);
* is.reset();
* doSomethingElse(is);
* </pre>
- * Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt>
+ * Note also the special case of {@code ByteArrayInputStream} for which the {@code close()}
* method does nothing.
* <pre>
* ByteArrayInputStream bais = ...
/**
* @param stream the stream to be closed
- * @param success <code>false</code> if an exception is currently being thrown in the calling method
+ * @param success {@code false} if an exception is currently being thrown in the calling method
*/
private void closeInputStream(InputStream stream, boolean success) {
try {
}
/**
- * Creates a new {@link POIFSFileSystem} in a new {@link File}.
+ * Creates a new POIFSFileSystem in a new {@link File}.
* Use {@link #POIFSFileSystem(File)} to open an existing File,
* this should only be used to create a new empty filesystem.
*
* @param file The file to create and open
- * @return The created and opened {@link POIFSFileSystem}
+ * @return The created and opened POIFSFileSystem
*/
public static POIFSFileSystem create(File file) throws IOException {
// Create a new empty POIFS in the file
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
/**
* Class POIFSWriterEvent
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
public class POIFSWriterEvent
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
/**
* Interface POIFSWriterListener
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
public interface POIFSWriterListener
public class TempFilePOIFSFileSystem extends POIFSFileSystem {
File tempFile;
+ @Override
protected void createNewDataSource() {
try {
tempFile = TempFile.createTempFile("poifs", ".tmp");
}
}
+ @Override
public void close() throws IOException {
if (tempFile != null && tempFile.exists()) tempFile.delete();
super.close();
/**
* This tool extracts out the source of all VBA Modules of an office file,
* both OOXML (eg XLSM) and OLE2/POIFS (eg DOC), to STDOUT or a directory.
- *
+ *
* @since 3.15-beta2
*/
public class VBAMacroExtractor {
System.err.println("Otherwise they are output to the screen");
System.exit(1);
}
-
+
File input = new File(args[0]);
File output = null;
if (args.length > 1) {
output = new File(args[1]);
}
-
+
VBAMacroExtractor extractor = new VBAMacroExtractor();
extractor.extract(input, output);
}
-
+
/**
* Extracts the VBA modules from a macro-enabled office file and writes them
- * to files in <tt>outputDir</tt>.
+ * to files in {@code outputDir}.
*
- * Creates the <tt>outputDir</tt>, directory, including any necessary but
- * nonexistent parent directories, if <tt>outputDir</tt> does not exist.
- * If <tt>outputDir</tt> is null, writes the contents to standard out instead.
+ * Creates the {@code outputDir}, directory, including any necessary but
+ * nonexistent parent directories, if {@code outputDir} does not exist.
+ * If {@code outputDir} is null, writes the contents to standard out instead.
*
* @param input the macro-enabled office file.
* @param outputDir the directory to write the extracted VBA modules to.
try (VBAMacroReader reader = new VBAMacroReader(input)) {
macros = reader.readMacros();
}
-
+
final String divider = "---------------------------------------";
for (Entry<String, String> entry : macros.entrySet()) {
String moduleName = entry.getKey();
/**
* Extracts the VBA modules from a macro-enabled office file and writes them
- * to <tt>.vba</tt> files in <tt>outputDir</tt>.
- *
- * Creates the <tt>outputDir</tt>, directory, including any necessary but
- * nonexistent parent directories, if <tt>outputDir</tt> does not exist.
- * If <tt>outputDir</tt> is null, writes the contents to standard out instead.
- *
+ * to {@code .vba} files in {@code outputDir}.
+ *
+ * Creates the {@code outputDir}, directory, including any necessary but
+ * nonexistent parent directories, if {@code outputDir} does not exist.
+ * If {@code outputDir} is null, writes the contents to standard out instead.
+ *
* @param input the macro-enabled office file.
* @param outputDir the directory to write the extracted VBA modules to.
* @since 3.15-beta2
throw new IllegalArgumentException("No VBA project found");
}
+ @Override
public void close() throws IOException {
fs.close();
fs = null;
out.close();
buf = out.toByteArray();
}
+ @Override
public String getContent() {
return new String(buf, charset);
}
+ @Override
public ModuleType geModuleType() {
return moduleType;
}
}
/**
- * Recursively traverses directory structure rooted at <tt>dir</tt>.
+ * Recursively traverses directory structure rooted at {@code dir}.
* For each macro module that is found, the module's name and code are
- * added to <tt>modules<tt>.
+ * added to {@code modules}.
*
* @param dir The directory of entries to look at
* @param modules The resulting map of modules
module.read(decompressed);
}
return;
- } catch (IllegalArgumentException | IllegalStateException e) {
+ } catch (IllegalArgumentException | IllegalStateException ignored) {
}
//bad module.offset, try brute force
- ;
byte[] decompressedBytes;
try (InputStream compressed = new DocumentInputStream(documentNode)) {
decompressedBytes = findCompressedStreamWBruteForce(compressed);
}
/**
- * Skips <tt>n</tt> bytes in an input stream, throwing IOException if the
+ * Skips {@code n} bytes in an input stream, throwing IOException if the
* number of bytes skipped is different than requested.
* @throws IOException If skipping would exceed the available data or skipping did not work.
*/
/**
* Reads VBA Project modules from a VBA Project directory located at
- * <tt>macroDir</tt> into <tt>modules</tt>.
+ * {@code macroDir} into {@code modules}.
*
* @since 3.15-beta2
*/
Map<String, String> moduleNames, Charset charset) throws IOException {
//see 2.3.3 PROJECTwm Stream: Module Name Information
//multibytecharstring
- String mbcs = null;
- String unicode = null;
+ String mbcs;
+ String unicode;
//arbitrary sanity threshold
final int maxNameRecords = 10000;
int records = 0;
}
/**
- * Read <tt>length</tt> bytes of MBCS (multi-byte character set) characters from the stream
+ * Read {@code length} bytes of MBCS (multi-byte character set) characters from the stream
*
* @param stream the inputstream to read from
* @param length number of bytes to read from stream
* This relies on some, er, heuristics, admittedly.
*
* @param is full module inputstream to read
- * @return uncompressed bytes if found, <code>null</code> otherwise
+ * @return uncompressed bytes if found, {@code null} otherwise
* @throws IOException for a true IOException copying the is to a byte array
*/
private static byte[] findCompressedStreamWBruteForce(InputStream is) throws IOException {
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.property;
/**
* This interface defines methods for finding and setting sibling
* Property instances
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface Child {
/**
* This abstract base class is the ancestor of all classes
* implementing POIFS Property behavior.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public abstract class Property implements Child, POIFSViewable {
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.property;
* should correspond to a Property, but which does not map to a proper
* Property (i.e., a DirectoryProperty, DocumentProperty, or
* RootProperty) will get mapped to a null Property in the array.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
final class PropertyFactory {
properties.add(null);
break;
}
-
+
offset += POIFSConstants.PROPERTY_SIZE;
}
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.storage;
/**
* An interface for persisting block storage of POIFS components.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
-
-public interface BlockWritable
-{
+public interface BlockWritable {
/**
* Write the storage to an OutputStream
/**
* Constants used in reading/writing the Header block
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public interface HeaderBlockConstants
{
// BAT ~= FAT
// SBAT ~= MiniFAT
// XBAT ~= DIFat
-
+
// useful offsets
int _signature_offset = 0;
int _bat_count_offset = 0x2C;
* it is unchanged.
*
* @param shape the shape to be removed from this sheet, if present
- * @return <tt>true</tt> if this sheet contained the specified element
+ * @return {@code true} if this sheet contained the specified element
* @throws IllegalArgumentException if the type of the specified shape
* is incompatible with this sheet (optional)
*/
* create a text box
*/
TextBox<S,P> createTextBox();
-
+
/**
* create a connector
*/
ConnectorShape<S,P> createConnector();
-
+
/**
* create a group of shapes belonging to this container
*/
GroupShape<S,P> createGroup();
-
+
/**
* create a picture belonging to this container
*/
PictureShape<S,P> createPicture(PictureData pictureData);
-
+
/**
* Create a new Table of the given number of rows and columns
*
* @param numCols the number of columns
*/
TableShape<S,P> createTable(int numRows, int numCols);
-
+
/**
* Create a new OLE object shape with the given pictureData as preview image
*
/**
* Specifies a list of available anchoring types for text
- *
+ *
* <!-- FIXME: Identical to {@link org.apache.poi.ss.usermodel.VerticalAlignment}. Should merge these to
* {@link org.apache.poi.common.usermodel}.VerticalAlignment in the future. -->
- *
- * @author Yegor Kozlov
*/
public enum VerticalAlignment {
/**
dateFmt.setTimeZone(LocaleUtil.getUserTimeZone());
}
- /** {@inheritDoc} */
+ @Override
public synchronized void formatValue(StringBuffer toAppendTo, Object value) {
if (value == null)
value = 0.0;
/**
* {@inheritDoc}
* <p>
- * For a date, this is <tt>"mm/d/y"</tt>.
+ * For a date, this is {@code "mm/d/y"}.
*/
+ @Override
public void simpleValue(StringBuffer toAppendTo, Object value) {
synchronized (CellDateFormatter.class) {
if (SIMPLE_DATE == null || !SIMPLE_DATE.EXCEL_EPOCH_CAL.equals(EXCEL_EPOCH_CAL)) {
/**
* This class implements printing out an elapsed time format.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public class CellElapsedFormatter extends CellFormatter {
private final List<TimeSpec> specs;
// only special character for this is '%', so we have to handle all the
// quoting in this method ourselves.
+ @Override
public String handlePart(Matcher m, String part, CellFormatType type,
StringBuffer desc) {
}
}
- /** {@inheritDoc} */
+ @Override
public void formatValue(StringBuffer toAppendTo, Object value) {
double elapsed = ((Number) value).doubleValue();
/**
* {@inheritDoc}
* <p>
- * For a date, this is <tt>"mm/d/y"</tt>.
+ * For a date, this is {@code "mm/d/y"}.
*/
+ @Override
public void simpleValue(StringBuffer toAppendTo, Object value) {
formatValue(toAppendTo, value);
}
* specifies what to do with particular kinds of values, depending on the number
* of parts given:
* <dl>
- * <dt>One part (example: <tt>[Green]#.##</tt>)</dt>
+ * <dt>One part (example: {@code [Green]#.##})</dt>
* <dd>If the value is a number, display according to this one part (example: green text,
* with up to two decimal points). If the value is text, display it as is.</dd>
*
- * <dt>Two parts (example: <tt>[Green]#.##;[Red]#.##</tt>)</dt>
+ * <dt>Two parts (example: {@code [Green]#.##;[Red]#.##})</dt>
* <dd>If the value is a positive number or zero, display according to the first part (example: green
* text, with up to two decimal points); if it is a negative number, display
* according to the second part (example: red text, with up to two decimal
* points). If the value is text, display it as is.</dd>
*
- * <dt>Three parts (example: <tt>[Green]#.##;[Black]#.##;[Red]#.##</tt>)</dt>
+ * <dt>Three parts (example: {@code [Green]#.##;[Black]#.##;[Red]#.##})</dt>
* <dd>If the value is a positive
* number, display according to the first part (example: green text, with up to
* two decimal points); if it is zero, display according to the second part
* number, display according to the third part (example: red text, with up to
* two decimal points). If the value is text, display it as is.</dd>
*
- * <dt>Four parts (example: <tt>[Green]#.##;[Black]#.##;[Red]#.##;[@]</tt>)</dt>
+ * <dt>Four parts (example: {@code [Green]#.##;[Black]#.##;[Red]#.##;[@]})</dt>
* <dd>If the value is a positive number, display according to the first part (example: green text,
* with up to two decimal points); if it is zero, display according to the
* second part (example: black text, with up to two decimal points); if it is a
* </dl>
* <p>
* A given format part may specify a given Locale, by including something
- * like <tt>[$$-409]</tt> or <tt>[$£-809]</tt> or <tt>[$-40C]</tt>. These
+ * like {@code [$$-409]} or {@code [$£-809]} or {@code [$-40C]}. These
* are (currently) largely ignored. You can use {@link DateFormatConverter}
* to look these up into Java Locales if desired.
* <p>
new WeakHashMap<>();
/**
- * Returns a {@link CellFormat} that applies the given format. Two calls
+ * Returns a CellFormat that applies the given format. Two calls
* with the same format may or may not return the same object.
*
* @param format The format.
*
- * @return A {@link CellFormat} that applies the given format.
+ * @return A CellFormat that applies the given format.
*/
public static CellFormat getInstance(String format) {
return getInstance(LocaleUtil.getUserLocale(), format);
}
/**
- * Returns a {@link CellFormat} that applies the given format. Two calls
+ * Returns a CellFormat that applies the given format. Two calls
* with the same format may or may not return the same object.
*
* @param locale The locale.
* @param format The format.
*
- * @return A {@link CellFormat} that applies the given format.
+ * @return A CellFormat that applies the given format.
*/
public static synchronized CellFormat getInstance(Locale locale, String format) {
Map<String, CellFormat> formatMap = formatCache.computeIfAbsent(locale, k -> new WeakHashMap<>());
} else if (value instanceof java.util.Date) {
// Don't know (and can't get) the workbook date windowing (1900 or 1904)
// so assume 1900 date windowing
- Double numericValue = DateUtil.getExcelDate((Date) value);
+ double numericValue = DateUtil.getExcelDate((Date) value);
if (DateUtil.isValidExcelDate(numericValue)) {
return getApplicableFormatPart(numericValue).apply(value);
} else {
case BOOLEAN:
return apply(c.getBooleanCellValue());
case NUMERIC:
- Double value = c.getNumericCellValue();
+ double value = c.getNumericCellValue();
if (getApplicableFormatPart(value).getCellFormatType() == CellFormatType.DATE) {
if (DateUtil.isValidExcelDate(value)) {
return apply(c.getDateCellValue(), value);
case BOOLEAN:
return apply(label, c.getBooleanCellValue());
case NUMERIC:
- Double value = c.getNumericCellValue();
+ double value = c.getNumericCellValue();
if (getApplicableFormatPart(value).getCellFormatType() == CellFormatType.DATE) {
if (DateUtil.isValidExcelDate(value)) {
return apply(label, c.getDateCellValue(), value);
}
/**
- * Returns <tt>true</tt> if the other object is a {@link CellFormat} object
+ * Returns {@code true} if the other object is a CellFormat object
* with the same format.
*
* @param obj The other object.
*
- * @return <tt>true</tt> if the two objects are equal.
+ * @return {@code true} if the two objects are equal.
*/
@Override
public boolean equals(Object obj) {
/**
* This object represents a condition in a cell format.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public abstract class CellFormatCondition {
private static final int LT = 0;
switch (test) {
case LT:
return new CellFormatCondition() {
+ @Override
public boolean pass(double value) {
return value < c;
}
};
case LE:
return new CellFormatCondition() {
+ @Override
public boolean pass(double value) {
return value <= c;
}
};
case GT:
return new CellFormatCondition() {
+ @Override
public boolean pass(double value) {
return value > c;
}
};
case GE:
return new CellFormatCondition() {
+ @Override
public boolean pass(double value) {
return value >= c;
}
};
case EQ:
return new CellFormatCondition() {
+ @Override
public boolean pass(double value) {
return value == c;
}
};
case NE:
return new CellFormatCondition() {
+ @Override
public boolean pass(double value) {
return value != c;
}
}
/**
- * Returns <tt>true</tt> if the given value passes the constraint's test.
+ * Returns {@code true} if the given value passes the constraint's test.
*
* @param value The value to compare against.
*
- * @return <tt>true</tt> if the given value passes the constraint's test.
+ * @return {@code true} if the given value passes the constraint's test.
*/
public abstract boolean pass(double value);
}
\ No newline at end of file
}
/**
- * Returns <tt>true</tt> if this format part applies to the given value. If
+ * Returns {@code true} if this format part applies to the given value. If
* the value is a number and this is part has a condition, returns
- * <tt>true</tt> only if the number passes the condition. Otherwise, this
- * always return <tt>true</tt>.
+ * {@code true} only if the number passes the condition. Otherwise, this
+ * always return {@code true}.
*
* @param valueObject The value to evaluate.
*
- * @return <tt>true</tt> if this format part applies to the given value.
+ * @return {@code true} if this format part applies to the given value.
*/
public boolean applies(Object valueObject) {
if (condition == null || !(valueObject instanceof Number)) {
}
/**
- * Returns the color specification from the matcher, or <tt>null</tt> if
+ * Returns the color specification from the matcher, or {@code null} if
* there is none.
*
* @param m The matcher for the format part.
*
- * @return The color specification or <tt>null</tt>.
+ * @return The color specification or {@code null}.
*/
private static Color getColor(Matcher m) {
String cdesc = m.group(COLOR_GROUP);
}
/**
- * Returns the condition specification from the matcher, or <tt>null</tt> if
+ * Returns the condition specification from the matcher, or {@code null} if
* there is none.
*
* @param m The matcher for the format part.
*
- * @return The condition specification or <tt>null</tt>.
+ * @return The condition specification or {@code null}.
*/
private CellFormatCondition getCondition(Matcher m) {
String mdesc = m.group(CONDITION_OPERATOR_GROUP);
* @param label The label
* @param value The value to apply this format part to.
*
- * @return <tt>true</tt> if the
+ * @return {@code true} if the
*/
public CellFormatResult apply(JLabel label, Object value) {
CellFormatResult result = apply(value);
}
/**
- * Returns <tt>true</tt> if this format part has a condition.
+ * Returns {@code true} if this format part has a condition.
*
- * @return <tt>true</tt> if this format part has a condition.
+ * @return {@code true} if this format part has a condition.
*/
boolean hasCondition() {
return condition != null;
}
/**
- * Returns the string from the group, or <tt>""</tt> if the group is
- * <tt>null</tt>.
+ * Returns the string from the group, or {@code ""} if the group is
+ * {@code null}.
*
* @param m The matcher.
* @param g The group number.
*
- * @return The group or <tt>""</tt>.
+ * @return The group or {@code ""}.
*/
public static String group(Matcher m, int g) {
String str = m.group(g);
* This object contains the result of applying a cell format or cell format part
* to a value.
*
- * @author Ken Arnold, Industrious Media LLC
* @see CellFormatPart#apply(Object)
* @see CellFormat#apply(Object)
*/
public class CellFormatResult {
/**
- * This is <tt>true</tt> if no condition was given that applied to the
+ * This is {@code true} if no condition was given that applied to the
* value, or if the condition is satisfied. If a condition is relevant, and
- * when applied the value fails the test, this is <tt>false</tt>.
+ * when applied the value fails the test, this is {@code false}.
*/
public final boolean applies;
- /** The resulting text. This will never be <tt>null</tt>. */
+ /** The resulting text. This will never be {@code null}. */
public final String text;
/**
- * The color the format sets, or <tt>null</tt> if the format sets no color.
- * This will always be <tt>null</tt> if {@link #applies} is <tt>false</tt>.
+ * The color the format sets, or {@code null} if the format sets no color.
+ * This will always be {@code null} if {@link #applies} is {@code false}.
*/
public final Color textColor;
/**
* The different kinds of formats that the formatter understands.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public enum CellFormatType {
- /** The general (default) format; also used for <tt>"General"</tt>. */
+ /** The general (default) format; also used for {@code "General"}. */
GENERAL {
+ @Override
boolean isSpecial(char ch) {
return false;
}
+ @Override
CellFormatter formatter(String pattern) {
return new CellGeneralFormatter();
}
+ @Override
CellFormatter formatter(Locale locale, String pattern) {
return new CellGeneralFormatter(locale);
}
},
/** A numeric format. */
NUMBER {
+ @Override
boolean isSpecial(char ch) {
return false;
}
+ @Override
CellFormatter formatter(String pattern) {
return new CellNumberFormatter(pattern);
}
+ @Override
CellFormatter formatter(Locale locale, String pattern) {
return new CellNumberFormatter(locale, pattern);
}
},
/** A date format. */
DATE {
+ @Override
boolean isSpecial(char ch) {
return ch == '\'' || (ch <= '\u007f' && Character.isLetter(ch));
}
+ @Override
CellFormatter formatter(String pattern) {
return new CellDateFormatter(pattern);
}
+ @Override
CellFormatter formatter(Locale locale, String pattern) {
return new CellDateFormatter(locale, pattern);
}
},
/** An elapsed time format. */
ELAPSED {
+ @Override
boolean isSpecial(char ch) {
return false;
}
+ @Override
CellFormatter formatter(String pattern) {
return new CellElapsedFormatter(pattern);
}
+ @Override
CellFormatter formatter(Locale locale, String pattern) {
return new CellElapsedFormatter(pattern);
}
},
/** A text format. */
TEXT {
+ @Override
boolean isSpecial(char ch) {
return false;
}
+ @Override
CellFormatter formatter(String pattern) {
return new CellTextFormatter(pattern);
}
+ @Override
CellFormatter formatter(Locale locale, String pattern) {
return new CellTextFormatter(pattern);
}
};
/**
- * Returns <tt>true</tt> if the format is special and needs to be quoted.
+ * Returns {@code true} if the format is special and needs to be quoted.
*
* @param ch The character to test.
*
- * @return <tt>true</tt> if the format is special and needs to be quoted.
+ * @return {@code true} if the format is special and needs to be quoted.
*/
abstract boolean isSpecial(char ch);
/**
* A formatter for the default "General" cell format.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public class CellGeneralFormatter extends CellFormatter {
/** Creates a new general formatter. */
super(locale, "General");
}
+ @Override
public void formatValue(StringBuffer toAppendTo, Object value) {
if (value == null) {
return;
cf.formatValue(toAppendTo, value);
}
+ @Override
public void simpleValue(StringBuffer toAppendTo, Object value) {
formatValue(toAppendTo, value);
}
return (afterFractional == null) ? specials.size() : specials.indexOf(afterFractional);
}
- /** {@inheritDoc} */
+ @Override
public void formatValue(StringBuffer toAppendTo, Object valueObject) {
double value = ((Number) valueObject).doubleValue();
value *= scale;
/**
* {@inheritDoc}
* <p>
- * For a number, this is <tt>"#"</tt> for integer values, and <tt>"#.#"</tt>
+ * For a number, this is {@code "#"} for integer values, and {@code "#.#"}
* for floating-point values.
*/
+ @Override
public void simpleValue(StringBuffer toAppendTo, Object value) {
SIMPLE_NUMBER.formatValue(toAppendTo, value);
}
private final List<Special> specials = new LinkedList<>();
private boolean improperFraction;
+ @Override
public String handlePart(Matcher m, String part, CellFormatType type, StringBuffer descBuf) {
int pos = descBuf.length();
char firstCh = part.charAt(0);
}
return null;
}
-
+
private static boolean isDigitFmt(Special s) {
return s.ch == '0' || s.ch == '?' || s.ch == '#';
}
/**
* This class implements printing out text.
- *
- * @author Ken Arnold, Industrious Media LLC
*/
public class CellTextFormatter extends CellFormatter {
private final int[] textPos;
import org.apache.poi.ss.util.CellReference;
/**
- * @author Robert Hulbert
* Provides holding structure for temporary values in arrays during the evaluation process.
* As such, Row/Column references do not actually correspond to data in the file.
*/
* Performance optimisation for {@link org.apache.poi.ss.usermodel.FormulaEvaluator}.
* This class stores previously calculated values of already visited cells,
* to avoid unnecessary re-calculation when the same cells are referenced multiple times
- *
- * @author Josh Micich
*/
final class EvaluationCache {
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.util.Internal;
/**
* Abstracts a cell for the purpose of formula evaluation. This interface represents both formula
- * and non-formula cells.<br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
+ * and non-formula cells.
*/
+@Internal
public interface EvaluationCell {
/**
* @return an Object that identifies the underlying cell,
import org.apache.poi.ss.formula.ptg.NamePtg;
import org.apache.poi.ss.formula.ptg.Ptg;
+import org.apache.poi.util.Internal;
+
/**
- * Abstracts a name record for formula evaluation.<br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
+ * Abstracts a name record for formula evaluation.
*/
+@Internal
public interface EvaluationName {
String getNameText();
import org.apache.poi.util.Internal;
/**
- * Abstracts a sheet for the purpose of formula evaluation.<br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
+ * Abstracts a sheet for the purpose of formula evaluation.
*/
@Internal
public interface EvaluationSheet {
* @return <code>null</code> if there is no cell at the specified coordinates
*/
EvaluationCell getCell(int rowIndex, int columnIndex);
-
+
/**
* Propagated from {@link EvaluationWorkbook#clearAllCachedResultValues()} to clear locally cached data.
- *
+ *
* @see WorkbookEvaluator#clearAllCachedResultValues()
* @see EvaluationWorkbook#clearAllCachedResultValues()
* @since POI 3.15 beta 3
*/
public void clearAllCachedResultValues();
-
+
/**
* @return last row index referenced on this sheet, for evaluation optimization
* @since POI 4.0.0
*/
public int getLastRowNum();
-
+
/**
* Used by SUBTOTAL and similar functions that have options to ignore hidden rows
* @param rowIndex
* The main purpose of this class is to detect an attempt to evaluate a cell
* that is already being evaluated. In other words, it detects circular
* references in spreadsheet formulas.
- *
- * @author Josh Micich
*/
final class EvaluationTracker {
// TODO - consider deleting this class and letting CellEvaluationFrame take care of itself
* Notifies this evaluation tracker that evaluation of the specified cell is
* about to start.<br>
*
- * In the case of a <code>true</code> return code, the caller should
+ * In the case of a {@code true} return code, the caller should
* continue evaluation of the specified cell, and also be sure to call
- * <tt>endEvaluate()</tt> when complete.<br>
+ * {@code endEvaluate()} when complete.<br>
*
- * In the case of a <code>null</code> return code, the caller should
+ * In the case of a {@code null} return code, the caller should
* return an evaluation result of
- * <tt>ErrorEval.CIRCULAR_REF_ERROR<tt>, and not call <tt>endEvaluate()</tt>.
+ * {@code ErrorEval.CIRCULAR_REF_ERROR}, and not call {@code endEvaluate()}.
* <br>
- * @return <code>false</code> if the specified cell is already being evaluated
+ * @return {@code false} if the specified cell is already being evaluated
*/
public boolean startEvaluate(FormulaCellCacheEntry cce) {
if (cce == null) {
/**
* Notifies this evaluation tracker that the evaluation of the specified cell is complete. <p>
*
- * Every successful call to <tt>startEvaluate</tt> must be followed by a call to <tt>endEvaluate</tt> (recommended in a finally block) to enable
+ * Every successful call to {@code startEvaluate} must be followed by a call to {@code endEvaluate} (recommended in a finally block) to enable
* proper tracking of which cells are being evaluated at any point in time.<p>
*
* Assuming a well behaved client, parameters to this method would not be
import org.apache.poi.util.Internal;
/**
- * Abstracts a workbook for the purpose of formula evaluation.<br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
+ * Abstracts a workbook for the purpose of formula evaluation.
*/
@Internal
public interface EvaluationWorkbook {
ExternalSheet getExternalSheet(String firstSheetName, String lastSheetName, int externalWorkbookNumber);
/**
* HSSF Only - convert an external sheet index to an internal sheet index,
- * for an external-style reference to one of this workbook's own sheets
+ * for an external-style reference to one of this workbook's own sheets
*/
int convertFromExternSheetIndex(int externSheetIndex);
* XSSF Only - fetch the external-style name details
*/
ExternalName getExternalName(String nameName, String sheetName, int externalWorkbookNumber);
-
+
EvaluationName getName(NamePtg namePtg);
EvaluationName getName(String name, int sheetIndex);
String resolveNameXText(NameXPtg ptg);
Ptg[] getFormulaTokens(EvaluationCell cell);
UDFFinder getUDFFinder();
SpreadsheetVersion getSpreadsheetVersion();
-
+
/**
* Propagated from {@link WorkbookEvaluator#clearAllCachedResultValues()} to clear locally cached data.
* Implementations must call the same method on all referenced {@link EvaluationSheet} instances, as well as clearing local caches.
* @see WorkbookEvaluator#clearAllCachedResultValues()
- *
+ *
* @since POI 3.15 beta 3
*/
public void clearAllCachedResultValues();
super(workbookName, firstSheetName);
this._lastSheetName = lastSheetName;
}
-
+
public String getFirstSheetName() {
return getSheetName();
}
* Should be implemented by any {@link org.apache.poi.ss.formula.ptg.Ptg} subclass that needs has an extern sheet index <br>
*
* For POI internal use only
- *
- * @author Josh Micich
*/
public interface ExternSheetReferenceToken {
int getExternSheetIndex();
return read(encodedTokenLen, in, encodedTokenLen);
}
/**
- * When there are no array constants present, <tt>encodedTokenLen</tt>==<tt>totalEncodedLen</tt>
+ * When there are no array constants present, {@code encodedTokenLen}=={@code totalEncodedLen}
* @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens
* @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding
- * for array constants, but does not include 2 bytes for initial <tt>ushort encodedTokenLen</tt> field.
- * @return A new formula object as read from the stream. Possibly empty, never <code>null</code>.
+ * for array constants, but does not include 2 bytes for initial {@code ushort encodedTokenLen} field.
+ * @return A new formula object as read from the stream. Possibly empty, never {@code null}.
*/
public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) {
byte[] byteEncoding = IOUtils.safelyAllocate(totalEncodedLen, MAX_ENCODED_LEN);
* <li>tokenData</li>
* <li>arrayConstantData (optional)</li>
* </ul>
- * Note - this value is different to <tt>tokenDataLength</tt>
+ * Note - this value is different to {@code tokenDataLength}
*/
public int getEncodedSize() {
return 2 + _byteEncoding.length;
}
/**
- * Creates a {@link Formula} object from a supplied {@link Ptg} array.
- * Handles <code>null</code>s OK.
- * @param ptgs may be <code>null</code>
- * @return Never <code>null</code> (Possibly empty if the supplied <tt>ptgs</tt> is <code>null</code>)
+ * Creates a Formula object from a supplied {@link Ptg} array.
+ * Handles {@code null}s OK.
+ * @param ptgs may be {@code null}
+ * @return Never {@code null} (Possibly empty if the supplied {@code ptgs} is {@code null})
*/
public static Formula create(Ptg[] ptgs) {
if (ptgs == null || ptgs.length < 1) {
return new Formula(encodedData, encodedTokenLen);
}
/**
- * Gets the {@link Ptg} array from the supplied {@link Formula}.
- * Handles <code>null</code>s OK.
+ * Gets the {@link Ptg} array from the supplied Formula.
+ * Handles {@code null}s OK.
*
- * @param formula may be <code>null</code>
- * @return possibly <code>null</code> (if the supplied <tt>formula</tt> is <code>null</code>)
+ * @param formula may be {@code null}
+ * @return possibly {@code null} (if the supplied {@code formula} is {@code null})
*/
public static Ptg[] getTokens(Formula formula) {
if (formula == null) {
* The return value is usually not the same as the location of the cell containing this formula.
*
* @return the firstRow & firstColumn of an array formula or shared formula that this formula
- * belongs to. <code>null</code> if this formula is not part of an array or shared formula.
+ * belongs to. {@code null} if this formula is not part of an array or shared formula.
*/
public CellReference getExpReference() {
byte[] data = _byteEncoding;
import java.util.Iterator;
import java.util.Map;
-/**
- *
- * @author Josh Micich
- */
final class FormulaCellCache {
static interface IEntryOperation {
* Profiling tests (Oct 2008) have shown that each element {@link FormulaCellCacheEntry} takes
* around 32 bytes to store in a HashSet, but around 6 bytes to store here. For Spreadsheets with
* thousands of formula cells with multiple interdependencies, the savings can be very significant.
- *
- * @author Josh Micich
*/
final class FormulaCellCacheEntrySet {
private static final FormulaCellCacheEntry[] EMPTY_ARRAY = { };
* supported by POI). It is primarily used by test code to confirm specific parsing exceptions.
* Application code should also handle this exception if it potentially supplies formula text
* that is not guaranteed to be well-formed.
- *
- * @author Josh Micich
*/
public final class FormulaParseException extends RuntimeException {
* Abstracts a workbook for the purpose of formula parsing.<br>
*
* For POI internal use only
- *
- * @author Josh Micich
*/
public interface FormulaParsingWorkbook {
/**
* named range name matching is case insensitive
*/
EvaluationName getName(String name, int sheetIndex);
-
+
/**
* Return the underlying workbook
*/
* XSSF Only - gets a table that exists in the worksheet
*/
Table getTable(String name);
-
+
/**
* Return an external name (named range, function, user-defined function) Ptg
*/
Ptg getNameXPtg(String name, SheetIdentifier sheet);
-
+
/**
* Produce the appropriate Ptg for a 3d cell reference
*/
import org.apache.poi.ss.formula.ptg.OperationPtg;
import org.apache.poi.ss.formula.ptg.ParenthesisPtg;
import org.apache.poi.ss.formula.ptg.Ptg;
+import org.apache.poi.util.Internal;
/**
- * Common logic for rendering formulas.<br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
+ * Common logic for rendering formulas.
*/
+@Internal
public class FormulaRenderer {
/**
import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalSheet;
import org.apache.poi.ss.formula.ptg.NamePtg;
import org.apache.poi.ss.formula.ptg.NameXPtg;
+import org.apache.poi.util.Internal;
/**
- * Abstracts a workbook for the purpose of converting formula to text.<br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
+ * Abstracts a workbook for the purpose of converting formula to text.
*/
+@Internal
public interface FormulaRenderingWorkbook {
/**
* @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook
*/
ExternalSheet getExternalSheet(int externSheetIndex);
-
+
/**
* @return the name of the (first) sheet referred to by the given external sheet index
*/
* @return the name of the (last) sheet referred to by the given external sheet index
*/
String getSheetLastNameByExternSheet(int externSheetIndex);
-
+
String resolveNameXText(NameXPtg nameXPtg);
String getNameText(NamePtg namePtg);
}
* Tests can implement this class to track the internal working of the {@link WorkbookEvaluator}.<br>
*
* For POI internal testing use only
- *
- * @author Josh Micich
*/
interface IEvaluationListener {
/**
* parts of a workbook are <em>final</em>.<br>
* The term <b>final</b> is introduced here to denote immutability or 'having constant definition'.
* This classification refers to potential actions (on the evaluated workbook) by the evaluating
- * application. It does not refer to operations performed by the evaluator ({@link
+ * application. It does not refer to operations performed by the evaluator ({@link
* WorkbookEvaluator}).<br>
* <br>
* <b>General guidelines</b>:
* to {@link WorkbookEvaluator#evaluate(EvaluationCell)}.
* </li>
* <li>a formula cell can be marked as 'final' if its formula will not be changed after the first
- * call to {@link WorkbookEvaluator#evaluate(EvaluationCell)}. This remains true even if changes
+ * call to {@link WorkbookEvaluator#evaluate(EvaluationCell)}. This remains true even if changes
* in dependent values may cause the evaluated value to change.</li>
* <li>plain value cells should be marked as 'not final' if their plain value value may change.
- * </li>
- * <li>formula cells should be marked as 'not final' if their formula definition may change.</li>
+ * </li>
+ * <li>formula cells should be marked as 'not final' if their formula definition may change.</li>
* <li>cells which may switch between plain value and formula should also be marked as 'not final'.
- * </li>
+ * </li>
* </ul>
* <b>Notes</b>:
* <ul>
* <li>If none of the spreadsheet cells is expected to have its definition changed after evaluation
- * begins, every cell can be marked as 'final'. This is the most efficient / least resource
+ * begins, every cell can be marked as 'final'. This is the most efficient / least resource
* intensive option.</li>
* <li>To retain freedom to change any cell definition at any time, an application may classify all
* cells as 'not final'. This freedom comes at the expense of greater memory consumption.</li>
- * <li>For the purpose of these classifications, setting the cached formula result of a cell (for
+ * <li>For the purpose of these classifications, setting the cached formula result of a cell (for
* example in {@link org.apache.poi.ss.usermodel.FormulaEvaluator#evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)})
* does not constitute changing the definition of the cell.</li>
- * <li>Updating cells which have been classified as 'final' will cause the evaluator to behave
- * unpredictably (typically ignoring the update).</li>
+ * <li>Updating cells which have been classified as 'final' will cause the evaluator to behave
+ * unpredictably (typically ignoring the update).</li>
* </ul>
- *
- * @author Josh Micich
*/
public interface IStabilityClassifier {
/**
* Checks if a cell's value(/formula) is fixed - in other words - not expected to be modified
- * between calls to the evaluator. (Note - this is an independent concept from whether a
+ * between calls to the evaluator. (Note - this is an independent concept from whether a
* formula cell's evaluated value may change during successive calls to the evaluator).
- *
+ *
* @param sheetIndex zero based index into workbook sheet list
* @param rowIndex zero based row index of cell
* @param columnIndex zero based column index of cell
- * @return <code>false</code> if the evaluating application may need to modify the specified
- * cell between calls to the evaluator.
+ * @return <code>false</code> if the evaluating application may need to modify the specified
+ * cell between calls to the evaluator.
*/
boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex);
}
import org.apache.poi.ss.formula.ptg.RangePtg;
import org.apache.poi.ss.formula.ptg.UnionPtg;
import org.apache.poi.ss.formula.ptg.ValueOperatorPtg;
-import org.apache.poi.util.Removal;
/**
* This class performs 'operand class' transformation. Non-base tokens are classified into three
*
* Hopefully, as additional important test cases are identified and added to the test suite,
* patterns might become more obvious in this code and allow for simplification.
- *
- * @author Josh Micich
*/
final class OperandClassTransformer {
}
/**
- * Traverses the supplied formula parse tree, calling <tt>Ptg.setClass()</tt> for each non-base
+ * Traverses the supplied formula parse tree, calling {@code Ptg.setClass()} for each non-base
* token to set its operand class.
*/
public void transformFormula(ParseNode rootNode) {
}
/**
- * @param callerForceArrayFlag <code>true</code> if one of the current node's parents is a
+ * @param callerForceArrayFlag {@code true} if one of the current node's parents is a
* function Ptg which has been changed from default 'V' to 'A' type (due to requirements on
* the function return value).
*/
if (isSimpleValueFunc) {
boolean localForceArray = desiredOperandClass == Ptg.CLASS_ARRAY;
- for (int i = 0; i < children.length; i++) {
- transformNode(children[i], desiredOperandClass, localForceArray);
+ for (ParseNode child : children) {
+ transformNode(child, desiredOperandClass, localForceArray);
}
setSimpleValueFuncClass((AbstractFunctionPtg) token, desiredOperandClass, callerForceArrayFlag);
return;
// All direct operands of value operators that are initially 'R' type will
// be converted to 'V' type.
byte localDesiredOperandClass = desiredOperandClass == Ptg.CLASS_REF ? Ptg.CLASS_VALUE : desiredOperandClass;
- for (int i = 0; i < children.length; i++) {
- transformNode(children[i], localDesiredOperandClass, callerForceArrayFlag);
+ for (ParseNode child : children) {
+ transformNode(child, localDesiredOperandClass, callerForceArrayFlag);
}
return;
}
}
/**
- * @return <code>null</code> if either workbook or sheet is not found
+ * @return {@code null} if either workbook or sheet is not found
*/
private SheetRefEvaluator createExternSheetRefEvaluator(String workbookName, String sheetName) {
WorkbookEvaluator targetEvaluator;
/**
* Resolves a cell or area reference dynamically.
- * @param workbookName the name of the workbook containing the reference. If <code>null</code>
+ * @param workbookName the name of the workbook containing the reference. If {@code null}
* the current workbook is assumed. Note - to evaluate formulas which use multiple workbooks,
* a {@link CollaboratingWorkbooksEnvironment} must be set up.
- * @param sheetName the name of the sheet containing the reference. May be <code>null</code>
- * (when <tt>workbookName</tt> is also null) in which case the current workbook and sheet is
+ * @param sheetName the name of the sheet containing the reference. May be {@code null}
+ * (when {@code workbookName} is also null) in which case the current workbook and sheet is
* assumed.
* @param refStrPart1 the single cell reference or first part of the area reference. Must not
- * be <code>null</code>.
+ * be {@code null}.
* @param refStrPart2 the second part of the area reference. For single cell references this
- * parameter must be <code>null</code>
- * @param isA1Style specifies the format for <tt>refStrPart1</tt> and <tt>refStrPart2</tt>.
- * Pass <code>true</code> for 'A1' style and <code>false</code> for 'R1C1' style.
+ * parameter must be {@code null}
+ * @param isA1Style specifies the format for {@code refStrPart1} and {@code refStrPart2}.
+ * Pass {@code true} for 'A1' style and {@code false} for 'R1C1' style.
* TODO - currently POI only supports 'A1' reference style
* @return a {@link RefEval} or {@link AreaEval}
*/
import org.apache.poi.ss.util.CellRangeAddress;
/**
- * This class creates <tt>OperationEval</tt> instances to help evaluate <tt>OperationPtg</tt>
+ * This class creates {@code OperationEval} instances to help evaluate {@code OperationPtg}
* formula tokens.
- *
- * @author Josh Micich
*/
final class OperationEvaluatorFactory {
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.function.FunctionMetadataRegistry;
/**
- * Represents a syntactic element from a formula by encapsulating the corresponding <tt>Ptg</tt>
- * token. Each <tt>ParseNode</tt> may have child <tt>ParseNode</tt>s in the case when the wrapped
- * <tt>Ptg</tt> is non-atomic.
+ * Represents a syntactic element from a formula by encapsulating the corresponding {@code Ptg}
+ * token. Each {@code ParseNode} may have child {@code ParseNode}s in the case when the wrapped
+ * {@code Ptg} is non-atomic.
*/
final class ParseNode {
public static final ParseNode[] EMPTY_ARRAY = { };
private final Ptg _token;
private final ParseNode[] _children;
- private boolean _isIf;
+ private final boolean _isIf;
private final int _tokenCount;
public ParseNode(Ptg token, ParseNode[] children) {
_children = children.clone();
_isIf = isIf(token);
int tokenCount = 1;
- for (int i = 0; i < children.length; i++) {
- tokenCount += children[i].getTokenCount();
+ for (ParseNode child : children) {
+ tokenCount += child.getTokenCount();
}
if (_isIf) {
// there will be 2 or 3 extra tAttr tokens according to whether the false param is present
}
public int getEncodedSize() {
int result = _token instanceof ArrayPtg ? ArrayPtg.PLAIN_TOKEN_SIZE : _token.getSize();
- for (int i = 0; i < _children.length; i++) {
- result += _children[i].getEncodedSize();
+ for (ParseNode child : _children) {
+ result += child.getEncodedSize();
}
return result;
}
/**
- * Collects the array of <tt>Ptg</tt> tokens for the specified tree.
+ * Collects the array of {@code Ptg} tokens for the specified tree.
*/
public static Ptg[] toTokenArray(ParseNode rootNode) {
TokenCollector temp = new TokenCollector(rootNode.getTokenCount());
private static boolean isIf(Ptg token) {
if (token instanceof FuncVarPtg) {
FuncVarPtg func = (FuncVarPtg) token;
- if (FunctionMetadataRegistry.FUNCTION_NAME_IF.equals(func.getName())) {
- return true;
- }
+ return FunctionMetadataRegistry.FUNCTION_NAME_IF.equals(func.getName());
}
return false;
}
/**
* Used for non-formula cells, primarily to keep track of the referencing (formula) cells.
- *
- * @author Josh Micich
*/
final class PlainValueCellCacheEntry extends CellCacheEntry {
public PlainValueCellCacheEntry(ValueEval value) {
/**
* Formats sheet names for use in formula expressions.
- *
- * @author Josh Micich
*/
public final class SheetNameFormatter {
-
+
private static final char DELIMITER = '\'';
-
+
/**
* Matches a single cell ref with no absolute ('$') markers
*/
/**
* Used to format sheet names as they would appear in cell formula expressions.
* @return the sheet name unchanged if there is no need for delimiting. Otherwise the sheet
- * name is enclosed in single quotes ('). Any single quotes which were already present in the
- * sheet name will be converted to double single quotes ('').
+ * name is enclosed in single quotes ('). Any single quotes which were already present in the
+ * sheet name will be converted to double single quotes ('').
*/
public static String format(String rawSheetName) {
StringBuilder sb = new StringBuilder((rawSheetName == null ? 0 : rawSheetName.length()) + 2);
}
if(Character.isLetter(rawSheetName.charAt(0))
&& Character.isDigit(rawSheetName.charAt(len-1))) {
- // note - values like "A$1:$C$20" don't get this far
+ // note - values like "A$1:$C$20" don't get this far
if(nameLooksLikePlainCellReference(rawSheetName)) {
return true;
}
// so they don't get this far
return false;
}
-
+
private static boolean nameLooksLikeBooleanLiteral(String rawSheetName) {
switch(rawSheetName.charAt(0)) {
case 'T': case 't':
}
/**
- * @return <code>true</code> if the presence of the specified character in a sheet name would
- * require the sheet name to be delimited in formulas. This includes every non-alphanumeric
+ * @return <code>true</code> if the presence of the specified character in a sheet name would
+ * require the sheet name to be delimited in formulas. This includes every non-alphanumeric
* character besides underscore '_' and dot '.'.
*/
/* package */ static boolean isSpecialChar(char ch) {
case '\n':
case '\r':
case '\t':
- throw new RuntimeException("Illegal character (0x"
+ throw new RuntimeException("Illegal character (0x"
+ Integer.toHexString(ch) + ") found in sheet name");
}
return true;
}
-
+
/**
- * Used to decide whether sheet names like 'AB123' need delimiting due to the fact that they
+ * Used to decide whether sheet names like 'AB123' need delimiting due to the fact that they
* look like cell references.
* <p>
* This code is currently being used for translating formulas represented with <code>Ptg</code>
- * tokens into human readable text form. In formula expressions, a sheet name always has a
- * trailing '!' so there is little chance for ambiguity. It doesn't matter too much what this
+ * tokens into human readable text form. In formula expressions, a sheet name always has a
+ * trailing '!' so there is little chance for ambiguity. It doesn't matter too much what this
* method returns but it is worth noting the likely consumers of these formula text strings:
* <ol>
* <li>POI's own formula parser</li>
* <li>Manual entry into Excel cell contents</li>
* <li>Some third party formula parser</li>
* </ol>
- *
+ *
* At the time of writing, POI's formula parser tolerates cell-like sheet names in formulas
- * with or without delimiters. The same goes for Excel(2007), both manual and automated entry.
+ * with or without delimiters. The same goes for Excel(2007), both manual and automated entry.
* <p>
* For better or worse this implementation attempts to replicate Excel's formula renderer.
* Excel uses range checking on the apparent 'row' and 'column' components. Note however that
}
/**
- * Note - this method assumes the specified rawSheetName has only letters and digits. It
+ * Note - this method assumes the specified rawSheetName has only letters and digits. It
* cannot be used to match absolute or range references (using the dollar or colon char).
* <p>
* Some notable cases:
- * <blockquote><table border="0" cellpadding="1" cellspacing="0"
+ * <blockquote><table border="0" cellpadding="1" cellspacing="0"
* summary="Notable cases.">
* <tr><th>Input </th><th>Result </th><th>Comments</th></tr>
* <tr><td>"A1" </td><td>true</td><td> </td></tr>
* <tr><td>"SALES20080101" </td><td>true</td>
* <td>Still needs delimiting even though well out of range</td></tr>
* </table></blockquote>
- *
+ *
* @return <code>true</code> if there is any possible ambiguity that the specified rawSheetName
* could be interpreted as a valid cell name.
*/
if(!matcher.matches()) {
return false;
}
-
+
// rawSheetName == "Sheet1" gets this far.
String lettersPrefix = matcher.group(1);
String numbersSuffix = matcher.group(2);
/**
*
* Common entry point for all user-defined (non-built-in) functions (where
- * <tt>AbstractFunctionPtg.field_2_fnc_index</tt> == 255)
- *
- * @author Josh Micich
- * @author Petr Udalau - Improved resolving of UDFs through the ToolPacks.
+ * {@code AbstractFunctionPtg.field_2_fnc_index} == 255)
*/
final class UserDefinedFunction implements FreeRefFunction {
// enforce singleton
}
+ @Override
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
int nIncomingArgs = args.length;
if(nIncomingArgs < 1) {
package org.apache.poi.ss.formula;
+import org.apache.poi.util.Internal;
+
/**
* Should be implemented by any {@link org.apache.poi.ss.formula.ptg.Ptg} subclass that needs a workbook to render its formula.
- * <br>
- *
- * For POI internal use only
- *
- * @author Josh Micich
*/
+@Internal
public interface WorkbookDependentFormula {
String toFormulaString(FormulaRenderingWorkbook book);
}
import static org.apache.logging.log4j.util.Unbox.box;
/**
- * Evaluates formula cells.<p/>
+ * Evaluates formula cells.<p>
*
* For performance reasons, this class keeps a cache of all previously calculated intermediate
* cell values. Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between
- * calls to evaluate~ methods on this class.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- * @author Thies Wellpott (debug output enhancements)
+ * calls to evaluate~ methods on this class.
*/
@Internal
public final class WorkbookEvaluator {
-
+
private static final Logger LOG = LogManager.getLogger(WorkbookEvaluator.class);
private final EvaluationWorkbook _workbook;
private int dbgEvaluationOutputIndent = -1;
/**
- * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
+ * @param udfFinder pass {@code null} for default (AnalysisToolPak only)
*/
public WorkbookEvaluator(EvaluationWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) {
this (workbook, null, stabilityClassifier, udfFinder);
/* package */ EvaluationSheet getSheet(int sheetIndex) {
return _workbook.getSheet(sheetIndex);
}
-
+
/* package */ EvaluationWorkbook getWorkbook() {
return _workbook;
}
int sheetIndex = getSheetIndex(cell.getSheet());
_cache.notifyDeleteCell(_workbookIx, sheetIndex, cell);
}
-
+
private int getSheetIndex(EvaluationSheet sheet) {
Integer result = _sheetIndexesBySheet.get(sheet);
if (result == null) {
if (sheetIndex < 0) {
throw new RuntimeException("Specified sheet from a different book");
}
- result = Integer.valueOf(sheetIndex);
+ result = sheetIndex;
_sheetIndexesBySheet.put(sheet, result);
}
- return result.intValue();
+ return result;
}
public ValueEval evaluate(EvaluationCell srcCell) {
if (sheetIndex < 0) {
return -1;
}
- result = Integer.valueOf(sheetIndex);
+ result = sheetIndex;
_sheetIndexesByName.put(sheetName, result);
}
- return result.intValue();
+ return result;
}
-
+
/* package */ int getSheetIndexByExternIndex(int externSheetIndex) {
return _workbook.convertFromExternSheetIndex(externSheetIndex);
}
/**
- * @return never <code>null</code>, never {@link BlankEval}
+ * @return never {@code null}, never {@link BlankEval}
*/
private ValueEval evaluateAny(EvaluationCell srcCell, int sheetIndex,
int rowIndex, int columnIndex, EvaluationTracker tracker) {
}
/**
* Gets the value from a non-formula cell.
- * @param cell may be <code>null</code>
- * @return {@link BlankEval} if cell is <code>null</code> or blank, never <code>null</code>
+ * @param cell may be {@code null}
+ * @return {@link BlankEval} if cell is {@code null} or blank, never {@code null}
*/
/* package */ static ValueEval getValueFromNonFormulaCell(EvaluationCell cell) {
if (cell == null) {
default:
throw new RuntimeException("Unexpected cell type (" + cellType + ")");
}
-
+
}
FuncVarPtg f = (FuncVarPtg)ptgs[ii];
try {
Function func = FunctionEval.getBasicFunction(f.getFunctionIndex());
- if (func != null && func instanceof ArrayMode) {
+ if (func instanceof ArrayMode) {
arrayMode = true;
}
} catch (NotImplementedException ne){
if (!stack.isEmpty()) {
throw new IllegalStateException("evaluation stack not empty");
}
-
+
ValueEval result;
-
+
if (ec.isSingleValue()) {
result = dereferenceResult(value, ec);
}
/**
* Calculates the number of tokens that the evaluator should skip upon reaching a tAttrSkip.
*
- * @return the number of tokens (starting from <tt>startIndex+1</tt>) that need to be skipped
- * to achieve the specified <tt>distInBytes</tt> skip distance.
+ * @return the number of tokens (starting from {@code startIndex+1}) that need to be skipped
+ * to achieve the specified {@code distInBytes} skip distance.
*/
private static int countTokensToBeSkipped(Ptg[] ptgs, int startIndex, int distInBytes) {
int remBytes = distInBytes;
int index = startIndex;
while (remBytes != 0) {
index++;
+ if (index >= ptgs.length) {
+ throw new RuntimeException("Skip distance too far (ran out of formula tokens).");
+ }
remBytes -= ptgs[index].getSize();
if (remBytes < 0) {
throw new RuntimeException("Bad skip distance (wrong token size calculation).");
}
- if (index >= ptgs.length) {
- throw new RuntimeException("Skip distance too far (ran out of formula tokens).");
- }
}
return index-startIndex;
}
-
+
/**
* Dereferences a single value from any AreaEval or RefEval evaluation
* result. If the supplied evaluationResult is just a plain value, it is
* returned as-is.
*
* @return a {@link NumberEval}, {@link StringEval}, {@link BoolEval}, or
- * {@link ErrorEval}. Never <code>null</code>. {@link BlankEval} is
+ * {@link ErrorEval}. Never {@code null}. {@link BlankEval} is
* converted to {@link NumberEval#ZERO}
*/
private static ValueEval dereferenceResult(ValueEval evaluationResult, OperationEvaluationContext ec) {
EvaluationSheet evalSheet = ec.getWorkbook().getSheet(ec.getSheetIndex());
EvaluationCell evalCell = evalSheet.getCell(ec.getRowIndex(), ec.getColumnIndex());
-
+
if (evalCell != null && evalCell.isPartOfArrayFormulaGroup() && evaluationResult instanceof AreaEval) {
value = OperandResolver.getElementFromArray((AreaEval) evaluationResult, evalCell);
}
// Formulas _never_ evaluate to blank. If a formula appears to have evaluated to
// blank, the actual value is empty string. This can be verified with ISBLANK().
}
-
+
return value;
}
* returned as-is.
*
* @return a {@link NumberEval}, {@link StringEval}, {@link BoolEval}, or
- * {@link ErrorEval}. Never <code>null</code>. {@link BlankEval} is
+ * {@link ErrorEval}. Never {@code null}. {@link BlankEval} is
* converted to {@link NumberEval#ZERO}
*/
public static ValueEval dereferenceResult(ValueEval evaluationResult, int srcRowNum, int srcColNum) {
/**
* returns an appropriate Eval impl instance for the Ptg. The Ptg must be
* one of: Area3DPtg, AreaPtg, ReferencePtg, Ref3DPtg, IntPtg, NumberPtg,
- * StringPtg, BoolPtg <br/>special Note: OperationPtg subtypes cannot be
- * passed here!
+ * StringPtg, BoolPtg<p>
+ *
+ * special Note: OperationPtg subtypes cannot be passed here!
*/
private ValueEval getEvalForPtg(Ptg ptg, OperationEvaluationContext ec) {
// consider converting all these (ptg instanceof XxxPtg) expressions to (ptg.getClass() == XxxPtg.class)
AreaPtg aptg = (AreaPtg) ptg;
return ec.getAreaEval(aptg.getFirstRow(), aptg.getFirstColumn(), aptg.getLastRow(), aptg.getLastColumn());
}
-
+
if (ptg instanceof ArrayPtg) {
ArrayPtg aptg = (ArrayPtg) ptg;
return ec.getAreaValueEval(0, 0, aptg.getRowCount() - 1, aptg.getColumnCount() - 1, aptg.getTokenArrayValues());
throw new RuntimeException("Unexpected ptg class (" + ptg.getClass().getName() + ")");
}
-
+
private ValueEval processNameEval(ValueEval eval, OperationEvaluationContext ec) {
if (eval instanceof ExternalNameEval) {
EvaluationName name = ((ExternalNameEval)eval).getName();
}
return eval;
}
-
+
private ValueEval getEvalForNameRecord(EvaluationName nameRecord, OperationEvaluationContext ec) {
if (nameRecord.isFunctionName()) {
return new FunctionNameEval(nameRecord.getNameText());
throw new RuntimeException("Don't know how to evaluate name '" + nameRecord.getNameText() + "'");
}
-
+
/**
* YK: Used by OperationEvaluationContext to resolve indirect names.
*/
if (ptgs.length == 1 && !(ptgs[0] instanceof FuncVarPtg)) {
return getEvalForPtg(ptgs[0], ec);
}
-
+
OperationEvaluationContext anyValueContext = new OperationEvaluationContext(this, ec.getWorkbook(), ec.getSheetIndex(), ec.getRowIndex(), ec.getColumnIndex(), new EvaluationTracker(_cache), false);
return evaluateFormula(anyValueContext, ptgs);
}
/**
* Evaluate a formula outside a cell value, e.g. conditional format rules or data validation expressions
- *
+ *
* @param formula to evaluate
* @param ref defines the optional sheet and row/column base for the formula, if it is relative
* @return value
int rowIndex = ref == null ? -1 : ref.getRow();
short colIndex = ref == null ? -1 : ref.getCol();
final OperationEvaluationContext ec = new OperationEvaluationContext(
- this,
- getWorkbook(),
- sheetIndex,
- rowIndex,
- colIndex,
+ this,
+ getWorkbook(),
+ sheetIndex,
+ rowIndex,
+ colIndex,
new EvaluationTracker(_cache)
);
Ptg[] ptgs = FormulaParser.parse(formula, (FormulaParsingWorkbook) getWorkbook(), FormulaType.CELL, sheetIndex, rowIndex);
return evaluateNameFormula(ptgs, ec);
}
-
+
/**
* Some expressions need to be evaluated in terms of an offset from the top left corner of a region,
* such as some data validation and conditional format expressions, when those constraints apply
* offset position relative to the top left of the range.
* <p>
* Returns a single value e.g. a cell formula result or boolean value for conditional formatting.
- *
+ *
* @param formula The formula to evaluate
* @param target cell context for the operation
* @param region containing the cell
public ValueEval evaluate(String formula, CellReference target, CellRangeAddressBase region) {
return evaluate(formula, target, region, FormulaType.CELL);
}
-
+
/**
* Some expressions need to be evaluated in terms of an offset from the top left corner of a region,
* such as some data validation and conditional format expressions, when those constraints apply
public ValueEval evaluateList(String formula, CellReference target, CellRangeAddressBase region) {
return evaluate(formula, target, region, FormulaType.DATAVALIDATION_LIST);
}
-
+
private ValueEval evaluate(String formula, CellReference target, CellRangeAddressBase region, FormulaType formulaType) {
final String sheetName = target == null ? null : target.getSheetName();
if (sheetName == null) throw new IllegalArgumentException("Sheet name is required");
-
+
final int sheetIndex = getWorkbook().getSheetIndex(sheetName);
Ptg[] ptgs = FormulaParser.parse(formula, (FormulaParsingWorkbook) getWorkbook(), formulaType, sheetIndex, target.getRow());
adjustRegionRelativeReference(ptgs, target, region);
-
+
final OperationEvaluationContext ec = new OperationEvaluationContext(this, getWorkbook(), sheetIndex, target.getRow(), target.getCol(), new EvaluationTracker(_cache), formulaType.isSingleValue());
return evaluateNameFormula(ptgs, ec);
}
-
+
/**
* Adjust formula relative references by the offset between the start of the given region and the given target cell.
* That is, treat the region top-left cell as "A1" for the purposes of evaluating relative reference components (row and/or column),
- * and further move references by the position of the target within the region.
- * <p><pre>formula ref + range top-left + current cell range offset </pre></p>
+ * and further move references by the position of the target within the region.<p>
+ *
+ * {@code formula ref + range top-left + current cell range offset}
* which simplifies to
- * <p><pre>formula ref + current cell ref</pre></p>
- * @param ptgs
+ * {@code formula ref + current cell ref}
+ *
* @param target cell within the region to use.
* @param region containing the cell, OR, for conditional format rules with multiple ranges, the region with the top-left-most cell
* @return true if any Ptg references were shifted
*/
protected boolean adjustRegionRelativeReference(Ptg[] ptgs, CellReference target, CellRangeAddressBase region) {
// region may not be the one that contains the target, if a conditional formatting rule applies to multiple regions
-
+
int deltaRow = target.getRow() - region.getFirstRow();
int deltaColumn = target.getCol() - region.getFirstColumn();
-
+
boolean shifted = false;
for (Ptg ptg : ptgs) {
// base class for cell reference "things"
}
return shifted;
}
-
+
/**
* Whether to ignore missing references to external workbooks and
* use cached formula results in the main workbook instead.
/**
* Evaluator for formula arguments.
- *
- * @author jfaenomoto@gmail.com
*/
final class ArgumentsEvaluator {
/**
* Evaluate a generic {@link ValueEval} argument to a double value that represents a date in POI.
- *
+ *
* @param arg {@link ValueEval} an argument.
* @param srcCellRow number cell row.
* @param srcCellCol number cell column.
/**
* Evaluate a generic {@link ValueEval} argument to an array of double values that represents dates in POI.
- *
+ *
* @param arg {@link ValueEval} an argument.
* @param srcCellRow number cell row.
* @param srcCellCol number cell column.
/**
* Evaluate a generic {@link ValueEval} argument to a double value.
- *
+ *
* @param arg {@link ValueEval} an argument.
* @param srcCellRow number cell row.
* @param srcCellCol number cell column.
* Implementation of 'Analysis Toolpak' Excel function IFERROR()<br>
*
* Returns an error text if there is an error in the evaluation<p>
- *
+ *
* <b>Syntax</b><br>
* <b>IFERROR</b>(<b>expression</b>, <b>string</b>)
- *
- * @author Johan Karlsteen
*/
final class IfError implements FreeRefFunction {
*
* <b>Syntax</b><br>
* <b>MROUND</b>(<b>number</b>, <b>multiple</b>)
- *
- * <p>
- *
- * @author Yegor Kozlov
*/
final class MRound implements FreeRefFunction {
* <b>Syntax</b><br>
* <b>NETWORKDAYS</b>(<b>startDate</b>, <b>endDate</b>, holidays)
* <p>
- *
- * @author jfaenomoto@gmail.com
*/
final class NetworkdaysFunction implements FreeRefFunction {
/**
* Constructor.
- *
+ *
* @param anEvaluator an injected {@link ArgumentsEvaluator}.
*/
private NetworkdaysFunction(ArgumentsEvaluator anEvaluator) {
/**
* Evaluate for NETWORKDAYS. Given two dates and a optional date or interval of holidays, determines how many working days are there
* between those dates.
- *
+ *
* @return {@link ValueEval} for the number of days between two dates.
*/
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { // NOSONAR
import org.apache.poi.ss.formula.OperationEvaluationContext;
/**
* Implementation of Excel 'Analysis ToolPak' function ISEVEN() ISODD()<br>
- *
- * @author Josh Micich
*/
final class ParityFunction implements FreeRefFunction {
*
* <b>bottom</b> is the smallest integer RANDBETWEEN will return.<br>
* <b>top</b> is the largest integer RANDBETWEEN will return.<br>
-
- * @author Brendan Nolan
*/
final class RandBetween implements FreeRefFunction{
* Evaluate for RANDBETWEEN(). Must be given two arguments. Bottom must be greater than top.
* Bottom is rounded up and top value is rounded down. After rounding top has to be set greater
* than top.
- *
+ *
* @see org.apache.poi.ss.formula.functions.FreeRefFunction#evaluate(org.apache.poi.ss.formula.eval.ValueEval[], org.apache.poi.ss.formula.OperationEvaluationContext)
*/
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
-
+
double bottom, top;
if (args.length != 2) {
return ErrorEval.VALUE_INVALID;
}
-
+
try {
bottom = OperandResolver.coerceValueToDouble(OperandResolver.getSingleValue(args[0], ec.getRowIndex(), ec.getColumnIndex()));
top = OperandResolver.coerceValueToDouble(OperandResolver.getSingleValue(args[1], ec.getRowIndex(), ec.getColumnIndex()));
if(bottom > top) {
top = bottom;
}
-
+
return new NumberEval((bottom + (long)(Math.random() * ((top - bottom) + 1))));
-
+
}
-
+
}
* <b>Syntax</b><br>
* <b>WORKDAY</b>(<b>startDate</b>, <b>days</b>, holidays)
* <p>
- *
- * @author jfaenomoto@gmail.com
*/
final class WorkdayFunction implements FreeRefFunction {
/**
* Evaluate for WORKDAY. Given a date, a number of days and a optional date or interval of holidays, determines which date it is past
* number of parametrized workdays.
- *
+ *
* @return {@link ValueEval} with date as its value.
*/
public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
/**
* To support Constant Values (2.5.7) as required by the CRN record.
- * This class is also used for two dimensional arrays which are encoded by
+ * This class is also used for two dimensional arrays which are encoded by
* EXTERNALNAME (5.39) records and Array tokens.<p>
- *
- * @author Josh Micich
*/
public final class ConstantValueParser {
// note - these (non-combinable) enum values are sparse.
private static final int TYPE_EMPTY = 0;
private static final int TYPE_NUMBER = 1;
private static final int TYPE_STRING = 2;
- private static final int TYPE_BOOLEAN = 4;
+ private static final int TYPE_BOOLEAN = 4;
private static final int TYPE_ERROR_CODE = 16; // TODO - update OOO document to include this value
-
- private static final int TRUE_ENCODING = 1;
+
+ private static final int TRUE_ENCODING = 1;
private static final int FALSE_ENCODING = 0;
-
+
// TODO - is this the best way to represent 'EMPTY'?
private static final Object EMPTY_REPRESENTATION = null;
switch(grbit) {
case TYPE_EMPTY:
in.readLong(); // 8 byte 'not used' field
- return EMPTY_REPRESENTATION;
+ return EMPTY_REPRESENTATION;
case TYPE_NUMBER:
return Double.valueOf(in.readDouble());
case TYPE_STRING:
return 8;
}
Class<?> cls = object.getClass();
-
+
if(cls == Boolean.class || cls == Double.class || cls == ErrorConstant.class) {
return 8;
}
* Represents a constant error code value as encoded in a constant values array. <p>
*
* This class is a type-safe wrapper for a 16-bit int value performing a similar job to
- * <tt>ErrorEval</tt>.
+ * {@code ErrorEval}.
*/
public final class ErrorConstant {
private static final Logger LOG = LogManager.getLogger(ErrorConstant.class);
}
public String toString() {
- StringBuilder sb = new StringBuilder(64);
- sb.append(getClass().getName()).append(" [");
- sb.append(getText());
- sb.append("]");
- return sb.toString();
+ return getClass().getName() + " [" + getText() + "]";
}
}
import org.apache.poi.ss.formula.SheetRange;
import org.apache.poi.ss.formula.ptg.AreaI;
-/**
- * @author Josh Micich
- */
public abstract class AreaEvalBase implements AreaEval {
private final int _firstSheet;
_nColumns = _lastColumn - _firstColumn + 1;
_nRows = _lastRow - _firstRow + 1;
-
+
if (sheets != null) {
_firstSheet = sheets.getFirstSheetIndex();
_lastSheet = sheets.getLastSheetIndex();
public final int getLastRow() {
return _lastRow;
}
-
+
public int getFirstSheetIndex() {
return _firstSheet;
}
public int getLastSheetIndex() {
return _lastSheet;
}
-
+
public final ValueEval getAbsoluteValue(int row, int col) {
int rowOffsetIx = row - _firstRow;
int colOffsetIx = col - _firstColumn;
package org.apache.poi.ss.formula.eval;
/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com > This class is a
- * marker class. It is a special value for empty cells.
+ * This class is a marker class. It is a special value for empty cells.
*/
public final class BlankEval implements ValueEval {
package org.apache.poi.ss.formula.eval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public final class BoolEval implements NumericValueEval, StringValueEval {
- private boolean _value;
+ private final boolean _value;
public static final BoolEval FALSE = new BoolEval(false);
/**
* Convenience method for the following:<br>
- * <code>(b ? BoolEval.TRUE : BoolEval.FALSE)</code>
+ * {@code (b ? BoolEval.TRUE : BoolEval.FALSE)}
*
- * @return the <tt>BoolEval</tt> instance representing <tt>b</tt>.
+ * @return the {@code BoolEval} instance representing {@code b}.
*/
public static BoolEval valueOf(boolean b) {
return b ? TRUE : FALSE;
return _value;
}
+ @Override
public double getNumberValue() {
return _value ? 1 : 0;
}
+ @Override
public String getStringValue() {
return _value ? "TRUE" : "FALSE";
}
import org.apache.poi.ss.formula.functions.Fixed2ArgFunction;
import org.apache.poi.ss.formula.functions.Function;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public final class ConcatEval extends Fixed2ArgFunction {
public static final Function instance = new ConcatEval();
/**
* This class is used to simplify error handling logic <i>within</i> operator and function
- * implementations. Note - <tt>OperationEval.evaluate()</tt> and <tt>Function.evaluate()</tt>
+ * implementations. Note - {@code OperationEval.evaluate()} and {@code Function.evaluate()}
* method signatures do not throw this exception so it cannot propagate outside.<p>
*
- * Here is an example coded without <tt>EvaluationException</tt>, to show how it can help:
+ * Here is an example coded without {@code EvaluationException}, to show how it can help:
* <pre>{@code
* public Eval evaluate(Eval[] args, int srcRow, short srcCol) {
* // ...
* In this example, if any error is encountered while processing the arguments, an error is
* returned immediately. This code is difficult to refactor due to all the points where errors
* are returned.<br>
- * Using <tt>EvaluationException</tt> allows the error returning code to be consolidated to one
- * place.<p>
+ * Using {@code EvaluationException} allows the error returning code to be consolidated to one
+ * place.
+ *
* <pre>{@code
* public Eval evaluate(Eval[] args, int srcRow, short srcCol) {
* try {
* error), because exceptions conveniently propagate up the call stack regardless of execution
* points or the number of levels of nested calls.<p>
*
- * <b>Note</b> - Only standard evaluation errors are represented by <tt>EvaluationException</tt> (
+ * <b>Note</b> - Only standard evaluation errors are represented by {@code EvaluationException} (
* i.e. conditions expected to be encountered when evaluating arbitrary Excel formulas). Conditions
* that could never occur in an Excel spreadsheet should result in runtime exceptions. Care should
* be taken to not translate any POI internal error into an Excel evaluation error code.
- *
- * @author Josh Micich
*/
public final class EvaluationException extends Exception {
private final ErrorEval _errorEval;
package org.apache.poi.ss.formula.eval;
-/**
- * @author Josh Micich
- */
public final class FunctionNameEval implements ValueEval {
private final String _functionName;
import org.apache.poi.ss.formula.functions.Fixed2ArgFunction;
import org.apache.poi.ss.formula.functions.Function;
-/**
- * @author Josh Micich
- */
public final class IntersectionEval extends Fixed2ArgFunction {
public static final Function instance = new IntersectionEval();
// enforces singleton
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
try {
/**
* @return simple rectangular {@link AreaEval} which represents the intersection of areas
- * <tt>aeA</tt> and <tt>aeB</tt>. If the two areas do not intersect, the result is <code>null</code>.
+ * {@code aeA} and {@code aeB}. If the two areas do not intersect, the result is {@code null}.
*/
private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) {
* COUNT and COUNTA <em>do</em> count their missing args. Note - the differences between
* {@link MissingArgEval} and {@link BlankEval} have not been investigated fully, so the POI
* evaluator may need to be updated to account for these as they are found.
- *
- * @author Josh Micich
*/
public final class MissingArgEval implements ValueEval {
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.util.NumberToTextConverter;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public final class NumberEval implements NumericValueEval, StringValueEval {
-
+
public static final NumberEval ZERO = new NumberEval(0);
private final double _value;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-/*
- * Created on May 8, 2005
- *
- */
package org.apache.poi.ss.formula.eval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public interface NumericValueEval extends ValueEval {
double getNumberValue();
/**
* Provides functionality for evaluating arguments to functions and operators.
- *
- * @author Josh Micich
- * @author Brendan Nolan
*/
public final class OperandResolver {
"(\\."+Digits+"("+Exp+")?))"+
"[\\x00-\\x20]*");
private static final Pattern fpPattern = Pattern.compile(fpRegex);
-
+
private OperandResolver() {
// no instances of this class
}
* @param arg the evaluated argument as passed to the function or operator.
* @param srcCellRow used when arg is a single column AreaRef
* @param srcCellCol used when arg is a single row AreaRef
- * @return a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt> or <tt>BlankEval</tt>.
- * Never <code>null</code> or <tt>ErrorEval</tt>.
+ * @return a {@code NumberEval}, {@code StringEval}, {@code BoolEval} or {@code BlankEval}.
+ * Never {@code null} or {@code ErrorEval}.
* @throws EvaluationException if srcCellRow or srcCellCol do not properly index into
* an AreaEval. If the actual value retrieved is an ErrorEval, a corresponding
* EvaluationException is thrown.
}
return result;
}
-
+
/**
* Retrieves a single value from an area evaluation utilizing the 2D indices of the cell
* within its own area reference to index the value in the area evaluation.
*
* @param ae area reference after evaluation
* @param cell the source cell of the formula that contains its 2D indices
- * @return a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt> or <tt>BlankEval</tt>. or <tt>ErrorEval<tt>
- * Never <code>null</code>.
+ * @return a {@code NumberEval}, {@code StringEval}, {@code BoolEval} or {@code BlankEval}. or {@code ErrorEval}
+ * Never {@code null}.
*/
public static ValueEval getElementFromArray(AreaEval ae, EvaluationCell cell) {
else if (ae.isRow() && relativeColIndex < ae.getWidth()) {
return ae.getRelativeValue(0, relativeColIndex);
}
-
+
return ErrorEval.NA;
}
*
* Of course with carefully (or carelessly) chosen parameters, cyclic references can occur and
* hence this method <b>can</b> throw a 'circular reference' EvaluationException. Note that
- * this method does not attempt to detect cycles. Every cell in the specified Area <tt>ae</tt>
+ * this method does not attempt to detect cycles. Every cell in the specified Area {@code ae}
* has already been evaluated prior to this method call. Any cell (or cell<b>s</b>) part of
- * <tt>ae</tt> that would incur a cyclic reference error if selected by this method, will
- * already have the value <t>ErrorEval.CIRCULAR_REF_ERROR</tt> upon entry to this method. It
+ * {@code ae} that would incur a cyclic reference error if selected by this method, will
+ * already have the value {@code ErrorEval.CIRCULAR_REF_ERROR} upon entry to this method. It
* is assumed logic exists elsewhere to produce this behaviour.
*
- * @return whatever the selected cell's evaluated value is. Never <code>null</code>. Never
- * <tt>ErrorEval</tt>.
+ * @return whatever the selected cell's evaluated value is. Never {@code null}. Never
+ * {@code ErrorEval}.
* @throws EvaluationException if there is a problem with indexing into the area, or if the
* evaluated cell has an error.
*/
}
/**
- * @return possibly <tt>ErrorEval</tt>, and <code>null</code>
+ * @return possibly {@code ErrorEval}, and {@code null}
*/
private static ValueEval chooseSingleElementFromAreaInternal(AreaEval ae,
int srcCellRow, int srcCellCol) throws EvaluationException {
}
return ae.getAbsoluteValue(ae.getFirstRow(), srcCellCol);
}
-
+
private static ValueEval chooseSingleElementFromRef(RefEval ref) {
return ref.getInnerValueEval( ref.getFirstSheetIndex() );
}
/**
* Applies some conversion rules if the supplied value is not already an integer.<br>
- * Value is first coerced to a <tt>double</tt> ( See <tt>coerceValueToDouble()</tt> ).
- * Note - <tt>BlankEval</tt> is converted to <code>0</code>.<p>
+ * Value is first coerced to a {@code double} ( See {@code coerceValueToDouble()} ).
+ * Note - {@code BlankEval} is converted to {@code 0}.<p>
*
* Excel typically converts doubles to integers by truncating toward negative infinity.<br>
* The equivalent java code is:<br>
- * <code>return (int)Math.floor(d);</code><br>
+ * {@code return (int)Math.floor(d);}<br>
* <b>not</b>:<br>
- * <code>return (int)d; // wrong - rounds toward zero</code>
+ * {@code return (int)d; // wrong - rounds toward zero}
*
*/
public static int coerceValueToInt(ValueEval ev) throws EvaluationException {
/**
* Applies some conversion rules if the supplied value is not already a number.
- * Note - <tt>BlankEval</tt> is converted to {@link NumberEval#ZERO}.
+ * Note - {@code BlankEval} is converted to {@link NumberEval#ZERO}.
* @param ev must be a {@link NumberEval}, {@link StringEval}, {@link BoolEval} or
* {@link BlankEval}
* @return actual, parsed or interpreted double value (respectively).
* @throws EvaluationException if a StringEval is supplied and cannot be parsed
- * as a double (See <tt>parseDouble()</tt> for allowable formats).
+ * as a double (See {@code parseDouble()} for allowable formats).
* @throws RuntimeException if the supplied parameter is not {@link NumberEval},
* {@link StringEval}, {@link BoolEval} or {@link BlankEval}
*/
if (dd == null) {
throw EvaluationException.invalidValue();
}
- return dd.doubleValue();
+ return dd;
}
throw new RuntimeException("Unexpected arg eval type (" + ev.getClass().getName() + ")");
}
/**
* Converts a string to a double using standard rules that Excel would use.<br>
* Tolerates leading and trailing spaces, <p>
- *
- * Doesn't support currency prefixes, commas, percentage signs or arithmetic operations strings.
+ *
+ * Doesn't support currency prefixes, commas, percentage signs or arithmetic operations strings.
*
* Some examples:<br>
* " 123 " -> 123.0<br>
* "5**2" -> 500<br>
* "250%" -> 2.5<br>
*
- * @return <code>null</code> if the specified text cannot be parsed as a number
+ * @return {@code null} if the specified text cannot be parsed as a number
*/
public static Double parseDouble(String pText) {
else {
return null;
}
-
+
}
public static Double parseDateTime(String pText) {
}
/**
- * @param ve must be a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt>, or <tt>BlankEval</tt>
- * @return the converted string value. never <code>null</code>
+ * @param ve must be a {@code NumberEval}, {@code StringEval}, {@code BoolEval}, or {@code BlankEval}
+ * @return the converted string value. never {@code null}
*/
public static String coerceValueToString(ValueEval ve) {
if (ve instanceof StringValueEval) {
}
/**
- * @return <code>null</code> to represent blank values
+ * @return {@code null} to represent blank values
* @throws EvaluationException if ve is an ErrorEval, or if a string value cannot be converted
*/
public static Boolean coerceValueToBoolean(ValueEval ve, boolean stringsAreBlanks) throws EvaluationException {
return null;
}
if (ve instanceof BoolEval) {
- return Boolean.valueOf(((BoolEval) ve).getBooleanValue());
+ return ((BoolEval) ve).getBooleanValue();
}
if (ve instanceof StringEval) {
if (Double.isNaN(d)) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
- return Boolean.valueOf(d != 0);
+ return d != 0;
}
if (ve instanceof ErrorEval) {
throw new EvaluationException((ErrorEval) ve);
/**
* Implementation of Excel formula token '%'. <p>
- * @author Josh Micich
*/
public final class PercentEval extends Fixed1ArgFunction {
import org.apache.poi.ss.formula.functions.Function;
-/**
- *
- * @author Josh Micich
- */
public final class RangeEval extends Fixed2ArgFunction {
public static final Function instance = new RangeEval();
// enforces singleton
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
try {
/**
* @return simple rectangular {@link AreaEval} which fully encloses both areas
- * <tt>aeA</tt> and <tt>aeB</tt>
+ * {@code aeA} and {@code aeB}
*/
private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) {
int aeAfr = aeA.getFirstRow();
/**
* Base class for all comparison operator evaluators
- *
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*/
public abstract class RelationalOperationEval extends Fixed2ArgFunction implements ArrayFunction {
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.ptg.StringPtg;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public final class StringEval implements StringValueEval {
public static final StringEval EMPTY_INSTANCE = new StringEval("");
package org.apache.poi.ss.formula.eval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public interface StringValueEval extends ValueEval {
/**
import org.apache.poi.ss.formula.functions.MatrixFunction.MutableValueCollector;
import org.apache.poi.ss.formula.functions.MatrixFunction.TwoArrayArg;
-/**
- * @author Josh Micich
- */
public abstract class TwoOperandNumericOperation extends Fixed2ArgFunction implements ArrayFunction {
protected final double singleOperandEvaluate(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException {
ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, srcCellCol);
return OperandResolver.coerceValueToDouble(ve);
}
-
+
public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
if (args.length != 2) {
return ErrorEval.VALUE_INVALID;
});
}
-
+
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
double result;
try {
private final class ArrayEval extends TwoArrayArg {
private final MutableValueCollector instance = new MutableValueCollector(true, true);
-
+
protected double[] collectValues(ValueEval arg) throws EvaluationException {
return instance.collectValues(arg);
}
-
+
protected double[][] evaluate(double[][] d1, double[][] d2) throws IllegalArgumentException, EvaluationException {
int width = (d1[0].length < d2[0].length) ? d1[0].length : d2[0].length;
int height = (d1.length < d2.length) ? d1.length : d2.length;
double[][] result = new double[height][width];
-
+
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
result[j][i] = TwoOperandNumericOperation.this.evaluate(d1[j][i], d2[j][i]);
}
}
-
+
return result;
}
}
-
+
public static final Function AddEval = new TwoOperandNumericOperation() {
protected double evaluate(double d0, double d1) {
return d0+d1;
import org.apache.poi.ss.formula.functions.Fixed1ArgFunction;
import org.apache.poi.ss.formula.functions.Function;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public final class UnaryMinusEval extends Fixed1ArgFunction implements ArrayFunction {
public static final Function instance = new UnaryMinusEval();
import org.apache.poi.ss.formula.functions.Function;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public final class UnaryPlusEval extends Fixed1ArgFunction implements ArrayFunction {
public static final Function instance = new UnaryPlusEval();
package org.apache.poi.ss.formula.eval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public interface ValueEval {
// no methods
}
/**
* Represents a cell being used for forked evaluation that has had a value set different from the
* corresponding cell in the shared master workbook.
- *
- * @author Josh Micich
*/
final class ForkedEvaluationCell implements EvaluationCell {
public int getColumnIndex() {
return _masterCell.getColumnIndex();
}
-
+
@Override
public CellRangeAddress getArrayFormulaRange() {
return _masterCell.getArrayFormulaRange();
}
-
+
@Override
public boolean isPartOfArrayFormulaGroup() {
return _masterCell.isPartOfArrayFormulaGroup();
}
/**
- * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
+ * @param udfFinder pass {@code null} for default (AnalysisToolPak only)
*/
public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) {
return new ForkedEvaluator(wb.createEvaluationWorkbook(), stabilityClassifier, udfFinder);
}
/**
- * Sets the specified cell to the supplied <tt>value</tt>
+ * Sets the specified cell to the supplied {@code value}
* @param sheetName the name of the sheet containing the cell
* @param rowIndex zero based
* @param columnIndex zero based
}
/**
* Copies the values of all updated cells (modified by calls to {@link
- * #updateCell(String, int, int, ValueEval)}) to the supplied <tt>workbook</tt>.<br>
- * Typically, the supplied <tt>workbook</tt> is a writable copy of the 'master workbook',
+ * #updateCell(String, int, int, ValueEval)}) to the supplied {@code workbook}.<br>
+ * Typically, the supplied {@code workbook} is a writable copy of the 'master workbook',
* but at the very least it must contain sheets with the same names.
*/
public void copyUpdatedCells(Workbook workbook) {
* @param sheetName the name of the sheet containing the cell
* @param rowIndex zero based
* @param columnIndex zero based
- * @return <code>null</code> if the supplied cell is <code>null</code> or blank
+ * @return {@code null} if the supplied cell is {@code null} or blank
*/
public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) {
EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex);
import java.util.Set;
/**
- * Temporarily collects <tt>FunctionMetadata</tt> instances for creation of a
- * <tt>FunctionMetadataRegistry</tt>.
- *
- * @author Josh Micich
+ * Temporarily collects {@code FunctionMetadata} instances for creation of a
+ * {@code FunctionMetadataRegistry}.
*/
final class FunctionDataBuilder {
private int _maxFunctionIndex;
FunctionMetadata fm = new FunctionMetadata(functionIndex, functionName, minParams, maxParams,
returnClassCode, parameterClassCodes);
- Integer indexKey = Integer.valueOf(functionIndex);
+ Integer indexKey = functionIndex;
if(functionIndex > _maxFunctionIndex) {
if(!hasFootnote || !_mutatingFunctionIndexes.contains(indexKey)) {
throw new RuntimeException("Multiple entries for function name '" + functionName + "'");
}
- _functionDataByIndex.remove(Integer.valueOf(prevFM.getIndex()));
+ _functionDataByIndex.remove(prevFM.getIndex());
}
prevFM = _functionDataByIndex.get(indexKey);
if(prevFM != null) {
/**
* Holds information about Excel built-in functions.
- *
- * @author Josh Micich
*/
public final class FunctionMetadata {
/**
}
/**
- * Some varags functions (like VLOOKUP) have a specific limit to the number of arguments that
+ * Some varags functions (like VLOOKUP) have a specific limit to the number of arguments that
* can be passed. Other functions (like SUM) don't have such a limit. For those functions,
* the spreadsheet version determines the maximum number of arguments that can be passed.
* @return <code>true</code> if this function can the maximum number of arguments allowable by
import org.apache.poi.util.IOUtils;
/**
- * Converts the text meta-data file into a <tt>FunctionMetadataRegistry</tt>
- *
- * @author Josh Micich
+ * Converts the text meta-data file into a {@code FunctionMetadataRegistry}
*/
final class FunctionMetadataReader {
}
private static boolean isDash(String codes) {
- if(codes.length() == 1) {
- if (codes.charAt(0) == '-') {
- return true;
- }
- }
- return false;
+ return codes.length() == 1 && codes.charAt(0) == '-';
}
private static byte parseOperandTypeCode(String code) {
import java.util.Map;
import java.util.Set;
+
/**
* Allows clients to get {@link FunctionMetadata} instances for any built-in function of Excel.
- *
- * @author Josh Micich
*/
public final class FunctionMetadataRegistry {
/**
/**
* Creates a text reference as text, given specified row and column numbers.
- *
- * @author Aniket Banerjee (banerjee@google.com)
*/
public class Address implements Function {
public static final int REF_ABSOLUTE = 1;
import org.apache.poi.ss.formula.eval.OperandResolver;
import org.apache.poi.ss.formula.eval.ValueEval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public abstract class AggregateFunction extends MultiOperandNumericFunction {
private static final class LargeSmall extends Fixed2ArgFunction {
/**
* Returns the number of areas in a reference. An area is a range of contiguous cells or a single cell.
- *
- * @author Loopbing (loopbing@gmail.com)
*/
public final class Areas implements Function {
import java.util.function.BiFunction;
/**
- * @author Robert Hulbert
* Common Interface for any excel built-in function that has implemented array formula functionality.
*/
* Remark
* If number is not a valid binary number, or if number contains more than 10 characters (10 bits),
* BIN2DEC returns the #NUM! error value.
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Bin2Dec extends Fixed1ArgFunction implements FreeRefFunction {
String inverted = toggleBits(unsigned);
// Calculate decimal number
int sum = getDecimalValue(inverted);
-
+
//Add 1 to obtained number
sum++;
-
+
value = "-" + sum;
}
} catch (NumberFormatException e) {
* Implementation of Excel functions Date parsing functions:
* Date - DAY, MONTH and YEAR
* Time - HOUR, MINUTE and SECOND
- *
- * @author Others (not mentioned in code)
- * @author Thies Wellpott
*/
public final class CalendarFieldFunction extends Fixed1ArgFunction {
public static final Function YEAR = new CalendarFieldFunction(Calendar.YEAR);
// rounding issues); use UTC here to prevent daylight saving issues for HOUR
Calendar c = DateUtil.getJavaCalendarUTC(serialDate + 0.4995 / DateUtil.SECONDS_PER_DAY, false);
int result = c.get(_dateFieldId);
-
+
// Month is a special case due to C semantics
if (_dateFieldId == Calendar.MONTH) {
result++;
}
-
+
return result;
}
}
import org.apache.poi.ss.formula.eval.OperandResolver;
import org.apache.poi.ss.formula.eval.ValueEval;
-/**
- * @author Josh Micich
- */
public final class Choose implements Function {
public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
* Returns a numeric code for the first character in a text string. The returned code corresponds to the character set used by your computer.
* <p>
* text The text for which you want the code of the first character.
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Code extends Fixed1ArgFunction {
/**
* Implementation for Excel COLUMNS function.
- *
- * @author Josh Micich
*/
public final class Columns extends Fixed1ArgFunction {
* <li>If omitted, suffix is assumed to be "i".</li>
* <li>If suffix is neither "i" nor "j", COMPLEX returns the #VALUE! error value.</li>
* </ul>
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Complex extends Var2or3ArgFunction implements FreeRefFunction {
if (suffixValue.length() == 0) {
suffixValue = DEFAULT_SUFFIX;
}
- if (suffixValue.equals(DEFAULT_SUFFIX.toUpperCase(Locale.ROOT)) ||
+ if (suffixValue.equals(DEFAULT_SUFFIX.toUpperCase(Locale.ROOT)) ||
suffixValue.equals(SUPPORTED_SUFFIX.toUpperCase(Locale.ROOT))) {
return ErrorEval.VALUE_INVALID;
}
/**
* Common logic for COUNT, COUNTA and COUNTIF
- *
- * @author Josh Micich
*/
final class CountUtils {
for (int rrIx=0; rrIx<height; rrIx++) {
for (int rcIx=0; rcIx<width; rcIx++) {
ValueEval ve = areaEval.getValue(sIx, rrIx, rcIx);
-
+
if(criteriaPredicate instanceof I_MatchAreaPredicate){
I_MatchAreaPredicate areaPredicate = (I_MatchAreaPredicate)criteriaPredicate;
if(!areaPredicate.matches(areaEval, rrIx, rcIx)) continue;
}
-
+
if(criteriaPredicate.matches(ve)) {
result++;
}
*/
public static int countMatchingCellsInRef(RefEval refEval, I_MatchPredicate criteriaPredicate) {
int result = 0;
-
+
final int firstSheetIndex = refEval.getFirstSheetIndex();
final int lastSheetIndex = refEval.getLastSheetIndex();
for (int sIx = firstSheetIndex; sIx <= lastSheetIndex; sIx++) {
* Excel Syntax
* COUNTA(value1,value2,...)
* Value1, value2, ... are 1 to 30 arguments representing the values or ranges to be counted.
- *
- * @author Josh Micich
*/
public final class Counta implements Function {
private final I_MatchPredicate _predicate;
public boolean matches(ValueEval valueEval) {
return defaultPredicate.matches(valueEval);
}
-
+
/**
* don't count cells in rows that are hidden or subtotal cells
*/
return !areEval.isSubTotal(rowIndex, columnIndex) && ! areEval.isRowHidden(rowIndex);
}
};
-
+
public static Counta subtotalInstance(boolean includeHiddenRows) {
return new Counta(includeHiddenRows ? subtotalPredicate : subtotalVisibleOnlyPredicate);
}
* <tr><th>range </th><td>is the range of cells to count blanks</td></tr>
* </table>
* </p>
- *
- * @author Mads Mohr Christensen
*/
public final class Countblank extends Fixed1ArgFunction {
* <p>
* To view a date serial number as a date, you must apply a date format to the cell. Find links to more
* information about displaying numbers as dates in the See Also section.
- *
- * @author Milosz Rembisz
*/
public class DateValue extends Fixed1ArgFunction {
* <li>If places is nonnumeric, DEC2BIN returns the #VALUE! error value.</li>
* <li>If places is zero or negative, DEC2BIN returns the #NUM! error value.</li>
* </ul>
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Dec2Bin extends Var1or2ArgFunction implements FreeRefFunction {
* <li>If number1 is nonnumeric, DELTA returns the #VALUE! error value.</li>
* <li>If number2 is nonnumeric, DELTA returns the #VALUE! error value.</li>
* </ul>
- *
- * @author cedric dot walter @ gmail dot com
*/
public final class Delta extends Fixed2ArgFunction implements FreeRefFunction {
* <b>Syntax:</b><br>
* <b>ERROR.TYPE</b>(<b>errorValue</b>)</p>
* <p>
- * Returns a number corresponding to the error type of the supplied argument.<p>
- * <p>
+ * Returns a number corresponding to the error type of the supplied argument.
* <table border="1" cellpadding="1" cellspacing="1" summary="Return values for ERROR.TYPE()">
* <tr><td>errorValue</td><td>Return Value</td></tr>
* <tr><td>#NULL!</td><td>1</td></tr>
* </table>
*
* Note - the results of ERROR.TYPE() are different to the constants defined in
- * <tt>ErrorConstants</tt>.
- * </p>
- *
- * @author Josh Micich
+ * {@code ErrorConstants}.
*/
public final class Errortype extends Fixed1ArgFunction {
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
try {
* <li>If number is negative, FACTDOUBLE returns the #NUM! error value.</li>
* </ul>
* Use a cache for more speed of previously calculated factorial
- *
- * @author cedric dot walter @ gmail dot com
*/
public class FactDouble extends Fixed1ArgFunction implements FreeRefFunction {
import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.ValueEval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public abstract class FinanceFunction implements Function3Arg, Function4Arg {
private static final ValueEval DEFAULT_ARG3 = NumberEval.ZERO;
private static final ValueEval DEFAULT_ARG4 = BoolEval.FALSE;
package org.apache.poi.ss.formula.functions;
/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- *
* This class is a functon library for common fiscal functions.
* <b>Glossary of terms/abbreviations:</b>
* <br>
/**
* Convenience base class for functions that must take exactly one argument.
- *
- * @author Josh Micich
*/
public abstract class Fixed1ArgFunction implements Function1Arg {
public final ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
/**
* Convenience base class for functions that must take exactly two arguments.
- *
- * @author Josh Micich
*/
public abstract class Fixed2ArgFunction implements Function2Arg {
public final ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
/**
* Convenience base class for functions that must take exactly three arguments.
- *
- * @author Josh Micich
*/
public abstract class Fixed3ArgFunction implements Function3Arg {
public final ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
/**
* Convenience base class for functions that must take exactly four arguments.
- *
- * @author Josh Micich
*/
public abstract class Fixed4ArgFunction implements Function4Arg {
public final ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
*
* For the moment this interface only exists to serve the <b>INDIRECT</b> which can decode
* arbitrary text into cell references, and evaluate them..
- *
- * @author Josh Micich
*/
public interface FreeRefFunction {
/**
- * @param args the pre-evaluated arguments for this function. args is never <code>null</code>,
+ * @param args the pre-evaluated arguments for this function. args is never {@code null},
* nor are any of its elements.
* @param ec primarily used to identify the source cell containing the formula being evaluated.
* may also be used to dynamically create reference evals.
- * @return never <code>null</code>. Possibly an instance of <tt>ErrorEval</tt> in the case of
+ * @return never {@code null}. Possibly an instance of {@code ErrorEval} in the case of
* a specified Excel error (Exceptions are never thrown to represent Excel errors).
*/
ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec);
* If data_array contains no values, FREQUENCY returns an array of zeros.<br>
* <b>bins_array</b> Required. An array of or reference to intervals into which you want to group the values in data_array.
* If bins_array contains no values, FREQUENCY returns the number of elements in data_array.<br>
- *
- * @author Yegor Kozlov
*/
public class Frequency extends Fixed2ArgFunction {
public static final Function instance = new Frequency();
/**
* Common interface for all implementations of Excel built-in functions.
- *
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*/
public interface Function {
/**
* Implemented by all functions that can be called with one argument
- *
- * @author Josh Micich
*/
public interface Function1Arg extends Function {
/**
/**
* Implemented by all functions that can be called with two arguments
- *
- * @author Josh Micich
*/
public interface Function2Arg extends Function {
/**
/**
* Implemented by all functions that can be called with three arguments
- *
- * @author Josh Micich
*/
public interface Function3Arg extends Function {
/**
/**
* Implemented by all functions that can be called with four arguments
- *
- * @author Josh Micich
*/
public interface Function4Arg extends Function {
/**
* The remaining 39 bits are magnitude bits. Negative numbers are represented using two's-complement notation.
* Remark
* If number is not a valid hexadecimal number, HEX2DEC returns the #NUM! error value.
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Hex2Dec extends Fixed1ArgFunction implements FreeRefFunction {
* <b>row_index_num</b> a 1 based index specifying which row value of the lookup data will be returned.<br>
* <b>range_lookup</b> If TRUE (default), HLOOKUP finds the largest value less than or equal to
* the lookup_value. If FALSE, only exact matches will be considered<br>
- *
- * @author Josh Micich
*/
public final class Hlookup extends Var3or4ArgFunction {
private static final ValueEval DEFAULT_ARG3 = BoolEval.TRUE;
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2) {
return evaluate(srcRowIndex, srcColumnIndex, arg0, arg1, arg2, DEFAULT_ARG3);
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2, ValueEval arg3) {
try {
}
/**
- * Returns one column from an <tt>AreaEval</tt>
+ * Returns one column from an {@code AreaEval}
*
* @param rowIndex assumed to be non-negative
*
* <b>friendly_name</b> (optional) the value to display<p>
*
* Returns last argument. Leaves type unchanged (does not convert to {@link org.apache.poi.ss.formula.eval.StringEval}).
- *
- * @author Wayne Clingingsmith
*/
public final class Hyperlink extends Var1or2ArgFunction {
* <li>If inumber is not in the form x + yi or x + yj, this function returns the #NUM! error value.</li>
* <li>Use COMPLEX to convert real and imaginary coefficients into a complex number.</li>
* </ul>
- *
- * @author cedric dot walter @ gmail dot com
*/
public class ImReal extends Fixed1ArgFunction implements FreeRefFunction {
* <ul>
* <li>Use COMPLEX to convert real and imaginary coefficients into a complex number.</li>
* </ul>
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Imaginary extends Fixed1ArgFunction implements FreeRefFunction {
* Implementation for the Excel function INDEX
* <p>
*
- * Syntax : <br>
- * INDEX ( reference, row_num[, column_num [, area_num]])</br>
+ * Syntax : <p>
+ * INDEX ( reference, row_num[, column_num [, area_num]])<p>
* INDEX ( array, row_num[, column_num])
* <table border="0" cellpadding="1" cellspacing="0" summary="Parameter descriptions">
* <tr><th>reference</th><td>typically an area reference, possibly a union of areas</td></tr>
* <tr><th>column_num</th><td>selects column within the array or area reference. default is 1</td></tr>
* <tr><th>area_num</th><td>used when reference is a union of areas</td></tr>
* </table>
- * </p>
- *
- * @author Josh Micich
*/
public final class Index implements Function2Arg, Function3Arg, Function4Arg, ArrayMode {
* normally be written in a cell formula.<br>
* <b>isA1Style</b> (default TRUE) specifies whether the ref_text should be
* interpreted as A1-style or R1C1-style.
- *
- * @author Josh Micich
*/
public final class Indirect implements FreeRefFunction {
private static ValueEval evaluateIndirect(final OperationEvaluationContext ec, String text,
boolean isA1style) {
-
+
// Search backwards for '!' because sheet names can contain '!'
int plingPos = text.lastIndexOf('!');
int colonPos = refText.indexOf(':');
if (colonPos < 0) {
refStrPart1 = refText.trim();
- refStrPart2 = null;
+ refStrPart2 = null;
} else {
refStrPart1 = refText.substring(0, colonPos).trim();
refStrPart2 = refText.substring(colonPos + 1).trim();
* (http://introcs.cs.princeton.edu/java/97data/LinearRegression.java.html)
* <b>Syntax</b>:<br>
* <b>INTERCEPT</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
- *
- *
- * @author Johan Karlsteen
*/
public final class Intercept extends Fixed2ArgFunction {
public Intercept() {
func = new LinearRegressionFunction(FUNCTION.INTERCEPT);
}
-
+
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex,
ValueEval arg0, ValueEval arg1) {
return func.evaluate(srcRowIndex, srcColumnIndex, arg0, arg1);
* <b>Syntax</b>:<br>
* <b>INTERCEPT</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
* or
- * <b>SLOPE</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
- *
- *
- * @author Johan Karlsteen
+ * <b>SLOPE</b>(<b>arrayX</b>, <b>arrayY</b>)
*/
public final class LinearRegressionFunction extends Fixed2ArgFunction {
_size = size;
}
- public ValueEval getItem(int index) {
+ @Override
+ public ValueEval getItem(int index) {
if (index < 0 || index > _size) {
throw new IllegalArgumentException("Specified index " + index
+ " is outside range (0.." + (_size - 1) + ")");
*/
public abstract class LogicalFunction extends Fixed1ArgFunction implements ArrayFunction{
- @SuppressWarnings("unused")
+ @Override
+ @SuppressWarnings("unused")
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
ValueEval ve;
try {
protected abstract boolean evaluate(ValueEval arg);
public static final Function ISLOGICAL = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return arg instanceof BoolEval;
}
};
public static final Function ISNONTEXT = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return !(arg instanceof StringEval);
}
};
public static final Function ISNUMBER = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return arg instanceof NumberEval;
}
};
public static final Function ISTEXT = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return arg instanceof StringEval;
}
public static final Function ISBLANK = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return arg instanceof BlankEval;
}
public static final Function ISERROR = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return arg instanceof ErrorEval;
}
};
/**
- * Implementation of Excel <tt>ISERR()</tt> function.<p>
+ * Implementation of Excel {@code ISERR()} function.<p>
*
* <b>Syntax</b>:<br>
* <b>ISERR</b>(<b>value</b>)<p>
*
* <b>value</b> The value to be tested<p>
*
- * Returns the logical value <tt>TRUE</tt> if value refers to any error value except
- * <tt>'#N/A'</tt>; otherwise, it returns <tt>FALSE</tt>.
+ * Returns the logical value {@code TRUE} if value refers to any error value except
+ * {@code '#N/A'}; otherwise, it returns {@code FALSE}.
*/
public static final Function ISERR = new LogicalFunction() {
@Override
*
* <b>value</b> The value to be tested<br>
* <br>
- * Returns <tt>TRUE</tt> if the specified value is '#N/A', <tt>FALSE</tt> otherwise.
+ * Returns {@code TRUE} if the specified value is '#N/A', {@code FALSE} otherwise.
*/
public static final Function ISNA = new LogicalFunction() {
+ @Override
protected boolean evaluate(ValueEval arg) {
return arg == ErrorEval.NA;
}
public static final Function ISREF = new Fixed1ArgFunction() {
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
if (arg0 instanceof RefEval || arg0 instanceof AreaEval || arg0 instanceof RefListEval) {
return BoolEval.TRUE;
final class LookupUtils {
/**
- * Represents a single row or column within an <tt>AreaEval</tt>.
+ * Represents a single row or column within an {@code AreaEval}.
*/
public interface ValueVector {
ValueEval getItem(int index);
_size = tableArray.getWidth();
}
+ @Override
public ValueEval getItem(int index) {
if(index > _size) {
throw new ArrayIndexOutOfBoundsException("Specified index (" + index
}
return _tableArray.getValue(_rowIndex, index);
}
+ @Override
public int getSize() {
return _size;
}
_size = _tableArray.getHeight();
}
+ @Override
public ValueEval getItem(int index) {
if(index > _size) {
throw new ArrayIndexOutOfBoundsException("Specified index (" + index
}
return _tableArray.getValue(index, _columnIndex);
}
+ @Override
public int getSize() {
return _size;
}
_re = re;
}
- public ValueEval getItem(int index) {
+ @Override
+ public ValueEval getItem(int index) {
if(index >= _size) {
throw new ArrayIndexOutOfBoundsException("Specified index (" + index
+ ") is outside the allowed range (0.." + (_size-1) + ")");
int sheetIndex = _re.getFirstSheetIndex() + index;
return _re.getInnerValueEval(sheetIndex);
}
- public int getSize() {
+ @Override
+ public int getSize() {
return _size;
}
}
return new ColumnVector(tableArray, relativeColumnIndex);
}
/**
- * @return <code>null</code> if the supplied area is neither a single row nor a single column
+ * @return {@code null} if the supplied area is neither a single row nor a single column
*/
public static ValueVector createVector(TwoDEval ae) {
if (ae.isColumn()) {
* changes behaviour when the evaluated 'mid' value has a different type to the lookup value.<p>
*
* A simple int might have done the same job, but there is risk in confusion with the well
- * known <tt>Comparable.compareTo()</tt> and <tt>Comparator.compare()</tt> which both use
+ * known {@code Comparable.compareTo()} and {@code Comparator.compare()} which both use
* a ubiquitous 3 value result encoding.
*/
public static final class CompareResult {
public interface LookupValueComparer {
/**
- * @return one of 4 instances or <tt>CompareResult</tt>: <tt>LESS_THAN</tt>, <tt>EQUAL</tt>,
- * <tt>GREATER_THAN</tt> or <tt>TYPE_MISMATCH</tt>
+ * @return one of 4 instances or {@code CompareResult}: {@code LESS_THAN}, {@code EQUAL},
+ * {@code GREATER_THAN} or {@code TYPE_MISMATCH}
*/
CompareResult compareTo(ValueEval other);
}
}
_targetClass = targetValue.getClass();
}
+ @Override
public final CompareResult compareTo(ValueEval other) {
if (other == null) {
throw new RuntimeException("compare to value cannot be null");
_isMatchFunction = isMatchFunction;
}
+ @Override
protected CompareResult compareSameType(ValueEval other) {
StringEval se = (StringEval) other;
return CompareResult.valueOf(_value.compareToIgnoreCase(stringValue));
}
+ @Override
protected String getValueAsString() {
return _value;
}
super(ne);
_value = ne.getNumberValue();
}
+ @Override
protected CompareResult compareSameType(ValueEval other) {
NumberEval ne = (NumberEval) other;
return CompareResult.valueOf(Double.compare(_value, ne.getNumberValue()));
}
+ @Override
protected String getValueAsString() {
return String.valueOf(_value);
}
super(be);
_value = be.getBooleanValue();
}
+ @Override
protected CompareResult compareSameType(ValueEval other) {
BoolEval be = (BoolEval) other;
boolean otherVal = be.getBooleanValue();
}
return CompareResult.LESS_THAN;
}
+ @Override
protected String getValueAsString() {
return String.valueOf(_value);
}
/**
* Resolves the last (optional) parameter (<b>range_lookup</b>) to the VLOOKUP and HLOOKUP functions.
- * @param rangeLookupArg must not be <code>null</code>
+ * @param rangeLookupArg must not be {@code null}
*/
public static boolean resolveRangeLookupArg(ValueEval rangeLookupArg, int srcCellRow, int srcCellCol) throws EvaluationException {
*/
public final class Match extends Var2or3ArgFunction {
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
// default match_type is 1.0
return eval(srcRowIndex, srcColumnIndex, arg0, arg1, 1.0);
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2) {
_value = value;
}
- public ValueEval getItem(int index) {
+ @Override
+ public ValueEval getItem(int index) {
if (index != 0) {
throw new RuntimeException("Invalid index ("
+ index + ") only zero is allowed");
return _value;
}
+ @Override
public int getSize() {
return 1;
}
import org.apache.poi.ss.util.NumberToTextConverter;
/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
* This class is an extension to the standard math library
* provided by java.lang.Math class. It follows the Math class
* in that it has a private constructor and all static methods.
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.MatrixUtils;
-/**
- * @author Robert Hulbert
- */
public abstract class MatrixFunction implements Function{
-
+
public static void checkValues(double[] results) throws EvaluationException {
for (double result : results) {
if (Double.isNaN(result) || Double.isInfinite(result)) {
}
}
}
-
+
protected final double singleOperandEvaluate(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException {
ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, srcCellCol);
return OperandResolver.coerceValueToDouble(ve);
}
-
+
/* converts 1D array to 2D array for calculations */
private static double[][] fillDoubleArray(double[] vector, int rows, int cols) throws EvaluationException {
int i = 0, j = 0;
-
+
if (rows < 1 || cols < 1 || vector.length < 1) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
-
+
double[][] matrix = new double[rows][cols];
for (double aVector : vector) {
if (j < matrix.length) matrix[j][i++] = aVector;
}
}
-
+
return matrix;
}
-
+
/* retrieves 1D array from 2D array after calculations */
private static double[] extractDoubleArray(double[][] matrix) throws EvaluationException {
int idx = 0;
-
+
if (matrix == null || matrix.length < 1 || matrix[0].length < 1) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
-
+
double[] vector = new double[matrix.length * matrix[0].length];
for (double[] aMatrix : matrix) {
}
return vector;
}
-
+
public static abstract class OneArrayArg extends Fixed1ArgFunction {
protected OneArrayArg() {
//no fields to initialize
}
-
+
@Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
if (arg0 instanceof AreaEval) {
double[] result;
double[][] resultArray;
int width, height;
-
+
try {
double[] values = collectValues(arg0);
double[][] array = fillDoubleArray(values, ((AreaEval) arg0).getHeight(), ((AreaEval) arg0).getWidth());
width = resultArray[0].length;
height = resultArray.length;
result = extractDoubleArray(resultArray);
-
+
checkValues(result);
}
catch(EvaluationException e){
}
ValueEval[] vals = new ValueEval[result.length];
-
+
for (int idx = 0; idx < result.length; idx++) {
vals[idx] = new NumberEval(result[idx]);
}
-
+
if (result.length == 1) {
return vals[0];
}
else {
/* find a better solution */
- return new CacheAreaEval(((AreaEval) arg0).getFirstRow(), ((AreaEval) arg0).getFirstColumn(),
- ((AreaEval) arg0).getFirstRow() + height - 1,
+ return new CacheAreaEval(((AreaEval) arg0).getFirstRow(), ((AreaEval) arg0).getFirstColumn(),
+ ((AreaEval) arg0).getFirstRow() + height - 1,
((AreaEval) arg0).getFirstColumn() + width - 1, vals);
}
}
catch (EvaluationException e) {
return e.getErrorEval();
}
-
+
return new NumberEval(result[0][0]);
}
}
-
+
protected abstract double[][] evaluate(double[][] d1) throws EvaluationException;
protected abstract double[] collectValues(ValueEval arg) throws EvaluationException;
}
-
+
public static abstract class TwoArrayArg extends Fixed2ArgFunction {
protected TwoArrayArg() {
//no fields to initialize
}
-
+
@Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
double[] result;
return e.getErrorEval();
}
}
-
+
if (arg1 instanceof AreaEval) {
try {
double[] values = collectValues(arg1);
return e.getErrorEval();
}
}
-
+
resultArray = evaluate(array0, array1);
width = resultArray[0].length;
height = resultArray.length;
ValueEval[] vals = new ValueEval[result.length];
-
+
for (int idx = 0; idx < result.length; idx++) {
vals[idx] = new NumberEval(result[idx]);
}
-
+
if (result.length == 1)
return vals[0];
else {
- return new CacheAreaEval(((AreaEval) arg0).getFirstRow(), ((AreaEval) arg0).getFirstColumn(),
- ((AreaEval) arg0).getFirstRow() + height - 1,
+ return new CacheAreaEval(((AreaEval) arg0).getFirstRow(), ((AreaEval) arg0).getFirstColumn(),
+ ((AreaEval) arg0).getFirstRow() + height - 1,
((AreaEval) arg0).getFirstColumn() + width - 1, vals);
}
-
+
}
-
+
protected abstract double[][] evaluate(double[][] d1, double[][] d2) throws EvaluationException;
protected abstract double[] collectValues(ValueEval arg) throws EvaluationException;
}
-
+
public static final class MutableValueCollector extends MultiOperandNumericFunction {
public MutableValueCollector(boolean isReferenceBoolCounted, boolean isBlankCounted) {
super(isReferenceBoolCounted, isBlankCounted);
throw new IllegalStateException("should not be called");
}
}
-
+
public static final Function MINVERSE = new OneArrayArg() {
private final MutableValueCollector instance = new MutableValueCollector(false, false);
-
+
protected double[] collectValues(ValueEval arg) throws EvaluationException {
double[] values = instance.collectValues(arg);
-
+
/* handle case where MDETERM is operating on an array that that is not completely filled*/
if (arg instanceof AreaEval && values.length == 1)
throw new EvaluationException(ErrorEval.VALUE_INVALID);
-
+
return values;
}
-
+
protected double[][] evaluate(double[][] d1) throws EvaluationException {
if (d1.length != d1[0].length) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
-
+
Array2DRowRealMatrix temp = new Array2DRowRealMatrix(d1);
return MatrixUtils.inverse(temp).getData();
}
};
-
+
public static final Function TRANSPOSE = new OneArrayArg() {
private final MutableValueCollector instance = new MutableValueCollector(false, true);
-
+
protected double[] collectValues(ValueEval arg) throws EvaluationException {
return instance.collectValues(arg);
}
-
+
protected double[][] evaluate(double[][] d1) throws EvaluationException {
-
+
Array2DRowRealMatrix temp = new Array2DRowRealMatrix(d1);
return temp.transpose().getData();
}
};
-
+
public static final Function MDETERM = new Mdeterm();
private static class Mdeterm extends OneArrayArg {
protected double[] collectValues(ValueEval arg) throws EvaluationException {
double[] values = instance.collectValues(arg);
-
+
/* handle case where MDETERM is operating on an array that that is not completely filled*/
if (arg instanceof AreaEval && values.length == 1)
throw new EvaluationException(ErrorEval.VALUE_INVALID);
return instance.collectValues(arg);
}
-
+
protected double[][] evaluate(double[][] d1) throws EvaluationException {
if (d1.length != d1[0].length) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
return result;
}
}
-
+
public static final Function MMULT = new TwoArrayArg() {
private final MutableValueCollector instance = new MutableValueCollector(false, false);
-
+
protected double[] collectValues(ValueEval arg) throws EvaluationException {
double[] values = instance.collectValues(arg);
-
+
/* handle case where MMULT is operating on an array that is not completely filled*/
if (arg instanceof AreaEval && values.length == 1)
throw new EvaluationException(ErrorEval.VALUE_INVALID);
-
+
return values;
}
-
+
protected double[][] evaluate(double[][] d1, double[][] d2) throws EvaluationException{
Array2DRowRealMatrix first = new Array2DRowRealMatrix(d1);
Array2DRowRealMatrix second = new Array2DRowRealMatrix(d2);
-
+
try {
MatrixUtils.checkMultiplicationCompatible(first, second);
}
catch (DimensionMismatchException e) {
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
-
- return first.multiply(second).getData();
+
+ return first.multiply(second).getData();
}
};
}
package org.apache.poi.ss.formula.functions;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public abstract class MinaMaxa extends MultiOperandNumericFunction {
protected MinaMaxa() {
* Finance_rate is the interest rate you pay on the money used in the cash flows.
* Reinvest_rate is the interest rate you receive on the cash flows as you reinvest them.
*
- * @author Carlos Delgado (carlos dot del dot est at gmail dot com)
- * @author Cedric Walter (cedric dot walter at gmail dot com)
- *
* @see <a href="http://en.wikipedia.org/wiki/MIRR">Wikipedia on MIRR</a>
* @see <a href="http://office.microsoft.com/en-001/excel-help/mirr-HP005209180.aspx">Excel MIRR</a>
* @see Irr
import org.apache.poi.ss.formula.eval.StringEval;
import org.apache.poi.ss.formula.eval.ValueEval;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public final class Mode implements Function {
/**
* values). Minimum 2 arguments, first arg is the rate of discount over the
* length of one period others up to 254 arguments representing the payments and
* income.
- *
- * @author SPetrakovsky
- * @author Marcel May
*/
public final class Npv implements Function {
}
/**
- * @throws EvaluationException (#NUM!) if <tt>result</tt> is {@code NaN} or {@code Infinity}
+ * @throws EvaluationException (#NUM!) if {@code result} is {@code NaN} or {@code Infinity}
*/
public static void checkValue(double result) throws EvaluationException {
if (Double.isNaN(result) || Double.isInfinite(result)) {
}
}
+ @Override
public final ValueEval evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) {
double result;
try {
* Negative numbers are represented using two's-complement notation..
* <p>
* If number is not a valid octal number, OCT2DEC returns the #NUM! error value.
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Oct2Dec extends Fixed1ArgFunction implements FreeRefFunction {
* <b>cols</b> is the number of columns left or right from the base reference.<br>
* <b>height</b> (default same height as base reference) is the row count for the returned area reference.<br>
* <b>width</b> (default same width as base reference) is the column count for the returned area reference.<br>
- *
- * @author Josh Micich
*/
public final class Offset implements Function {
// These values are specific to BIFF8
*
* @param translationAmount may be zero negative or positive
*
- * @return the equivalent <tt>LinearOffsetRange</tt> with a positive length, moved by the
+ * @return the equivalent {@code LinearOffsetRange} with a positive length, moved by the
* specified translationAmount.
*/
public LinearOffsetRange normaliseAndTranslate(int translationAmount) {
}
public boolean isOutOfBounds(int lowValidIx, int highValidIx) {
- if(_offset < lowValidIx) {
- return true;
- }
- if(getLastIndex() > highValidIx) {
- return true;
- }
- return false;
+ return _offset < lowValidIx || getLastIndex() > highValidIx;
}
public String toString() {
- StringBuilder sb = new StringBuilder(64);
- sb.append(getClass().getName()).append(" [");
- sb.append(_offset).append("...").append(getLastIndex());
- sb.append("]");
- return sb.toString();
+ return getClass().getName() + " [" + _offset + "..." + getLastIndex() + "]";
}
}
}
}
+ @Override
@SuppressWarnings("fallthrough")
public ValueEval evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) {
if(args.length < 1 || args.length > 5) {
/**
* Compute the interest portion of a payment.
- *
- * @author Mike Argyriou micharg@gmail.com
*/
public class PPMT extends NumericFunction {
result = Finance.ppmt(interestRate, period, numberPayments, PV) ;
checkValue(result);
-
+
return result;
}
-
+
}
* If order is 0 (zero) or omitted, Microsoft Excel ranks number as if ref were a list sorted in descending order.
* If order is any nonzero value, Microsoft Excel ranks number as if ref were a list sorted in ascending order.
- *
- * @author Rubin Wang
*/
public class Rank extends Var2or3ArgFunction {
public class Rate implements Function {
private static final Logger LOG = LogManager.getLogger(Rate.class);
+ @Override
public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
if (args.length < 3) { //First 3 parameters are mandatory
return ErrorEval.VALUE_INVALID;
if (args.length >= 6)
v6 = OperandResolver.getSingleValue(args[5], srcRowIndex, srcColumnIndex);
- periods = OperandResolver.coerceValueToDouble(v1);
+ periods = OperandResolver.coerceValueToDouble(v1);
payment = OperandResolver.coerceValueToDouble(v2);
present_val = OperandResolver.coerceValueToDouble(v3);
if (args.length >= 4)
int FINANCIAL_MAX_ITERATIONS = 20;//Bet accuracy with 128
double FINANCIAL_PRECISION = 0.0000001;//1.0e-8
- double y, y0, y1, x0, x1 = 0, f = 0, i = 0;
+ double y, y0, y1, x0, x1, f = 0, i;
double rate = guess;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
/**
* Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases
- *
- * @throws EvaluationException (#NUM!) if <tt>result</tt> is <tt>NaN</> or <tt>Infinity</tt>
+ *
+ * @throws EvaluationException (#NUM!) if {@code result} is {@code NaN} or {@code Infinity}
*/
static void checkValue(double result) throws EvaluationException {
if (Double.isNaN(result) || Double.isInfinite(result)) {
* <b>startNum</b> The position of the first character to replace (1-based)<br>
* <b>numChars</b> The number of characters to replace<br>
* <b>newText</b> The new text value to replace the removed section<br>
- *
- * @author Manda Wilson < wilson at c bio dot msk cc dot org >
*/
public final class Replace extends Fixed4ArgFunction {
* If this argument contains a decimal value, this function ignores the numbers to the right side of the decimal point.
*
* The result of the REPT function cannot be longer than 32,767 characters, or REPT returns #VALUE!.
- *
- * @author cedric dot walter @ gmail dot com
*/
public class Rept extends Fixed2ArgFunction {
/**
* Implementation for Excel ROWS function.
- *
- * @author Josh Micich
*/
public final class Rows extends Fixed1ArgFunction {
* (http://introcs.cs.princeton.edu/java/97data/LinearRegression.java.html)
* <b>Syntax</b>:<br>
* <b>SLOPE</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
- *
- *
- * @author Johan Karlsteen
*/
public final class Slope extends Fixed2ArgFunction {
-
+
private final LinearRegressionFunction func;
public Slope() {
func = new LinearRegressionFunction(FUNCTION.SLOPE);
}
-
+
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex,
ValueEval arg0, ValueEval arg1) {
return func.evaluate(srcRowIndex, srcColumnIndex, arg0, arg1);
import java.util.Arrays;
/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
* Library for common statistics functions
*/
final class StatsLib {
/**
* An implementation of the SUBSTITUTE function:<p>
* Substitutes text in a text string with new text, some number of times.
- * @author Manda Wilson < wilson at c bio dot msk cc dot org >
*/
public final class Substitute extends Var3or4ArgFunction {
* * Not implemented in POI yet. Functions 101-111 are the same as functions 1-11 but with
* the option 'ignore hidden values'.
* <p>
- *
- * @author Paul Tomlin < pault at bulk sms dot com >
*/
public class Subtotal implements Function {
* <tr><th>criteria</th><td>The value or expression used to filter rows from <b>range</b></td></tr>
* <tr><th>sum_range</th><td>Locates the top-left corner of the corresponding range of addends - values to be added (after being selected by the criteria)</td></tr>
* </table><br>
- * </p>
- * @author Josh Micich
*/
public final class Sumif extends Var2or3ArgFunction {
AreaEval aeSum) {
// TODO - junit to prove last arg must be srcColumnIndex and not srcRowIndex
I_MatchPredicate mp = Countif.createCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex);
-
+
// handle empty cells
if(mp == null) {
return NumberEval.ZERO;
* A<b>n</b><sub>(<b>i</b>,<b>j</b>)</sub>
* )
* )
- * </p>
- * @author Josh Micich
*/
public final class Sumproduct implements Function {
* <b>SUMX2MY2</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
*
* result = Σ<sub>i: 0..n</sub>(x<sub>i</sub><sup>2</sup>-y<sub>i</sub><sup>2</sup>)
- *
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*/
public final class Sumx2my2 extends XYNumericFunction {
private static final Accumulator XSquaredMinusYSquaredAccumulator = new Accumulator() {
- public double accumulate(double x, double y) {
+ @Override
+ public double accumulate(double x, double y) {
return x * x - y * y;
}
};
+ @Override
protected Accumulator createAccumulator() {
return XSquaredMinusYSquaredAccumulator;
}
* <b>SUMX2PY2</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
*
* result = Σ<sub>i: 0..n</sub>(x<sub>i</sub><sup>2</sup>+y<sub>i</sub><sup>2</sup>)
- *
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*/
public final class Sumx2py2 extends XYNumericFunction {
private static final Accumulator XSquaredPlusYSquaredAccumulator = new Accumulator() {
- public double accumulate(double x, double y) {
+ @Override
+ public double accumulate(double x, double y) {
return x * x + y * y;
}
};
+ @Override
protected Accumulator createAccumulator() {
return XSquaredPlusYSquaredAccumulator;
}
* <b>SUMXMY2</b>(<b>arrayX</b>, <b>arrayY</b>)<p>
*
* result = Σ<sub>i: 0..n</sub>(x<sub>i</sub>-y<sub>i</sub>)<sup>2</sup>
- *
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
*/
public final class Sumxmy2 extends XYNumericFunction {
private static final Accumulator XMinusYSquaredAccumulator = new Accumulator() {
- public double accumulate(double x, double y) {
+ @Override
+ public double accumulate(double x, double y) {
double xmy = x - y;
return xmy * xmy;
}
};
+ @Override
protected Accumulator createAccumulator() {
return XMinusYSquaredAccumulator;
}
import java.util.Locale;
-import org.apache.poi.ss.formula.OperationEvaluationContext;
import org.apache.poi.ss.formula.eval.AreaEval;
import org.apache.poi.ss.formula.eval.BoolEval;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.DataFormatter;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- * @author Josh Micich
- * @author Stephen Wolke (smwolke at geistig.com)
- */
public abstract class TextFunction implements Function {
protected static final DataFormatter formatter = new DataFormatter();
return OperandResolver.coerceValueToDouble(ve);
}
+ @Override
public final ValueEval evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) {
try {
return evaluateFunc(args, srcCellRow, srcCellCol);
protected SingleArgTextFunc() {
// no fields to initialise
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
String arg;
try {
* Returns the character specified by a number.
*/
public static final Function CHAR = new Fixed1ArgFunction() {
- public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
+ @Override
+ public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
int arg;
try {
arg = evaluateIntArg(arg0, srcRowIndex, srcColumnIndex);
};
public static final Function LEN = new SingleArgTextFunc() {
+ @Override
protected ValueEval evaluate(String arg) {
return new NumberEval(arg.length());
}
};
public static final Function LOWER = new SingleArgTextFunc() {
+ @Override
protected ValueEval evaluate(String arg) {
return new StringEval(arg.toLowerCase(Locale.ROOT));
}
};
public static final Function UPPER = new SingleArgTextFunc() {
+ @Override
protected ValueEval evaluate(String arg) {
return new StringEval(arg.toUpperCase(Locale.ROOT));
}
* This is nearly equivalent to toTitleCase if the Java language had it
*/
public static final Function PROPER = new SingleArgTextFunc() {
+ @Override
protected ValueEval evaluate(String text) {
StringBuilder sb = new StringBuilder();
boolean shouldMakeUppercase = true;
* Author: Manda Wilson < wilson at c bio dot msk cc dot org >
*/
public static final Function TRIM = new SingleArgTextFunc() {
+ @Override
protected ValueEval evaluate(String arg) {
return new StringEval(arg.trim());
}
* Author: Aniket Banerjee(banerjee@google.com)
*/
public static final Function CLEAN = new SingleArgTextFunc() {
- protected ValueEval evaluate(String arg) {
+ @Override
+ protected ValueEval evaluate(String arg) {
StringBuilder result = new StringBuilder();
for (final char c : arg.toCharArray()) {
if (isPrintable(c)) {
*/
public static final Function MID = new Fixed3ArgFunction() {
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1, ValueEval arg2) {
String text;
protected LeftRight(boolean isLeft) {
_isLeft = isLeft;
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) {
return evaluate(srcRowIndex, srcColumnIndex, arg0, DEFAULT_ARG1);
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1) {
String arg;
public static final Function LEFT = new LeftRight(true);
public static final Function RIGHT = new LeftRight(false);
- public static final FreeRefFunction CONCAT = new FreeRefFunction() {
- public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) {
- StringBuilder sb = new StringBuilder();
- for (ValueEval arg : args) {
- try {
- if (arg instanceof AreaEval) {
- AreaEval area = (AreaEval)arg;
- for (int rn=0; rn<area.getHeight(); rn++) {
- for (int cn=0; cn<area.getWidth(); cn++) {
- ValueEval ve = area.getRelativeValue(rn, cn);
- sb.append(evaluateStringArg(ve, ec.getRowIndex(), ec.getColumnIndex()));
- }
- }
- } else {
- sb.append(evaluateStringArg(arg, ec.getRowIndex(), ec.getColumnIndex()));
- }
- } catch (EvaluationException e) {
- return e.getErrorEval();
- }
- }
- return new StringEval(sb.toString());
- }
+ public static final FreeRefFunction CONCAT = (args, ec) -> {
+ StringBuilder sb = new StringBuilder();
+ for (ValueEval arg : args) {
+ try {
+ if (arg instanceof AreaEval) {
+ AreaEval area = (AreaEval)arg;
+ for (int rn=0; rn<area.getHeight(); rn++) {
+ for (int cn=0; cn<area.getWidth(); cn++) {
+ ValueEval ve = area.getRelativeValue(rn, cn);
+ sb.append(evaluateStringArg(ve, ec.getRowIndex(), ec.getColumnIndex()));
+ }
+ }
+ } else {
+ sb.append(evaluateStringArg(arg, ec.getRowIndex(), ec.getColumnIndex()));
+ }
+ } catch (EvaluationException e) {
+ return e.getErrorEval();
+ }
+ }
+ return new StringEval(sb.toString());
};
- public static final Function CONCATENATE = new Function() {
- public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
- StringBuilder sb = new StringBuilder();
- for (ValueEval arg : args) {
- try {
- sb.append(evaluateStringArg(arg, srcRowIndex, srcColumnIndex));
- } catch (EvaluationException e) {
- return e.getErrorEval();
- }
- }
- return new StringEval(sb.toString());
- }
+
+ public static final Function CONCATENATE = (args, srcRowIndex, srcColumnIndex) -> {
+ StringBuilder sb = new StringBuilder();
+ for (ValueEval arg : args) {
+ try {
+ sb.append(evaluateStringArg(arg, srcRowIndex, srcColumnIndex));
+ } catch (EvaluationException e) {
+ return e.getErrorEval();
+ }
+ }
+ return new StringEval(sb.toString());
};
public static final Function EXACT = new Fixed2ArgFunction() {
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0,
ValueEval arg1) {
String s0;
*/
public static final Function TEXT = new Fixed2ArgFunction() {
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
double s0;
String s1;
public SearchFind(boolean isCaseSensitive) {
_isCaseSensitive = isCaseSensitive;
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
try {
String needle = TextFunction.evaluateStringArg(arg0, srcRowIndex, srcColumnIndex);
return e.getErrorEval();
}
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2) {
try {
* <b>FIND</b>(<b>find_text</b>, <b>within_text</b>, start_num)<p>
*
* FIND returns the character position of the first (case sensitive) occurrence of
- * <tt>find_text</tt> inside <tt>within_text</tt>. The third parameter,
- * <tt>start_num</tt>, is optional (default=1) and specifies where to start searching
+ * {@code find_text} inside {@code within_text}. The third parameter,
+ * {@code start_num}, is optional (default=1) and specifies where to start searching
* from. Character positions are 1-based.<p>
*
* Author: Torstein Tauno Svendsen (torstei@officenet.no)
import org.apache.poi.ss.formula.eval.ValueEval;
/**
- * Implementation for the Excel function TIME
- *
- * @author Steven Butler (sebutler @ gmail dot com)
+ * Implementation for the Excel function TIME<p>
*
* Based on POI {@link DateFunc}
*/
import org.apache.poi.ss.formula.eval.ValueEval;
/**
- * Convenience base class for any function which must take two or three
- * arguments
- *
- * @author Josh Micich
+ * Convenience base class for any function which must take two or three arguments
*/
abstract class Var1or2ArgFunction implements Function1Arg, Function2Arg {
import org.apache.poi.ss.formula.eval.ValueEval;
/**
- * Convenience base class for any function which must take two or three
- * arguments
- *
- * @author Josh Micich
+ * Convenience base class for any function which must take two or three arguments
*/
abstract class Var2or3ArgFunction implements Function2Arg, Function3Arg {
import org.apache.poi.ss.formula.eval.ValueEval;
/**
- * Convenience base class for any function which must take three or four
- * arguments
- *
- * @author Josh Micich
+ * Convenience base class for any function which must take three or four arguments
*/
abstract class Var3or4ArgFunction implements Function3Arg, Function4Arg {
public final class Vlookup extends Var3or4ArgFunction {
private static final ValueEval DEFAULT_ARG3 = BoolEval.TRUE;
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1,
ValueEval arg2) {
return evaluate(srcRowIndex, srcColumnIndex, arg0, arg1, arg2, DEFAULT_ARG3);
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval lookup_value, ValueEval table_array,
ValueEval col_index, ValueEval range_lookup) {
try {
/**
- * Returns one column from an <tt>AreaEval</tt>
+ * Returns one column from an {@code AreaEval}
*
* @param colIndex assumed to be non-negative
*
/**
* Implementation for the Excel function WEEKDAY
- *
- * @author Thies Wellpott
*/
public final class WeekdayFunc implements Function {
//or: extends Var1or2ArgFunction {
import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.formula.functions.LookupUtils.ValueVector;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
public abstract class XYNumericFunction extends Fixed2ArgFunction {
private static abstract class ValueArray implements ValueVector {
protected ValueArray(int size) {
_size = size;
}
- public ValueEval getItem(int index) {
+ @Override
+ public ValueEval getItem(int index) {
if (index < 0 || index > _size) {
throw new IllegalArgumentException("Specified index " + index
+ " is outside range (0.." + (_size - 1) + ")");
return getItemInternal(index);
}
protected abstract ValueEval getItemInternal(int index);
+ @Override
public final int getSize() {
return _size;
}
super(1);
_value = value;
}
+ @Override
protected ValueEval getItemInternal(int index) {
return _value;
}
private static final class RefValueArray extends ValueArray {
private final RefEval _ref;
private final int _width;
-
+
public RefValueArray(RefEval ref) {
super(ref.getNumberOfSheets());
_ref = ref;
_width = ref.getNumberOfSheets();
}
+ @Override
protected ValueEval getItemInternal(int index) {
- int sIx = (index % _width) + _ref.getFirstSheetIndex();
+ int sIx = (index % _width) + _ref.getFirstSheetIndex();
return _ref.getInnerValueEval(sIx);
}
}
_ae = ae;
_width = ae.getWidth();
}
+ @Override
protected ValueEval getItemInternal(int index) {
int rowIx = index / _width;
int colIx = index % _width;
}
}
- protected static interface Accumulator {
+ protected interface Accumulator {
double accumulate(double x, double y);
}
*/
protected abstract Accumulator createAccumulator();
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
double result;
returnClass = (byte) pReturnClass;
paramClass = paramTypes;
}
+ @Override
public final boolean isBaseToken() {
return false;
}
public final short getFunctionIndex() {
return _functionIndex;
}
+ @Override
public final int getNumberOfOperands() {
return _numberOfArgs;
}
}
/**
* external functions get some special processing
- * @return <code>true</code> if this is an external function
+ * @return {@code true} if this is an external function
*/
public final boolean isExternalFunction() {
return _functionIndex == FUNCTION_INDEX_EXTERNAL;
}
+ @Override
public final String toFormulaString() {
return getName();
}
+ @Override
public String toFormulaString(String[] operands) {
StringBuilder buf = new StringBuilder();
buf.append(")");
}
+ @Override
public abstract int getSize();
* Used to detect whether a function name found in a formula is one of the standard excel functions
* <p>
* The name matching is case insensitive.
- * @return <code>true</code> if the name specifies a standard worksheet function,
- * <code>false</code> if the name should be assumed to be an external function.
+ * @return {@code true} if the name specifies a standard worksheet function,
+ * {@code false} if the name should be assumed to be an external function.
*/
public static boolean isBuiltInFunctionName(String name) {
short ix = FunctionMetadataRegistry.lookupIndexByName(name.toUpperCase(Locale.ROOT));
* Resolves internal function names into function indexes.
* <p>
* The name matching is case insensitive.
- * @return the standard worksheet function index if found, otherwise <tt>FUNCTION_INDEX_EXTERNAL</tt>
+ * @return the standard worksheet function index if found, otherwise {@code FUNCTION_INDEX_EXTERNAL}
*/
protected static short lookupIndex(String name) {
short ix = FunctionMetadataRegistry.lookupIndexByName(name.toUpperCase(Locale.ROOT));
return ix;
}
+ @Override
public byte getDefaultOperandClass() {
return returnClass;
}
return FormulaError.REF.getString();
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_REF;
}
/**
* Specifies a rectangular area of cells A1:A4 for instance.
- * @author Jason Height (jheight at chariot dot net dot au)
*/
public final class AreaNPtg extends Area2DPtgBase {
public static final short sid = 0x2D;
return formatReferenceAsString();
}
+ @Override
public byte getDefaultOperandClass() {
return Ptg.CLASS_REF;
}
private static RuntimeException invalid() {
throw new IllegalStateException("This object is a partially initialised tArray, and cannot be used as a Ptg");
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
throw invalid();
}
public int getSize() {
return ArrayPtg.PLAIN_TOKEN_SIZE;
}
+ @Override
public boolean isBaseToken() {
return false;
}
return result;
}
+ @Override
public boolean isBaseToken() {
return false;
}
throw new IllegalArgumentException("Unexpected constant class (" + o.getClass().getName() + ")");
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_ARRAY;
}
}
/**
- * @param type a constant from <tt>SpaceType</tt>
+ * @param type a constant from {@code SpaceType}
* @param count the number of space characters
*/
public static AttrPtg createSpace(int type, int count) {
return _chooseFuncOffset;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(sid + getPtgClass());
out.writeByte(_options);
return sid;
}
+ @Override
public int getSize() {
if (_jumpTable != null) {
return SIZE + (_jumpTable.length + 1) * LittleEndianConsts.SHORT_SIZE;
return -1;
}
+ @Override
public String toFormulaString() {
if (semiVolatile.isSet(_options)) {
return "ATTR(semiVolatile)";
protected ControlPtg() {}
+ @Override
public boolean isBaseToken() {
return true;
}
- public final byte getDefaultOperandClass() {
+ @Override
+ public final byte getDefaultOperandClass() {
throw new IllegalStateException("Control tokens are not classified");
}
}
return sb.toString();
}
+ @Override
public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
public String toFormulaString() {
throw new RuntimeException("3D references need a workbook to determine formula text");
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_REF;
}
public String toFormulaString() {
throw new RuntimeException("3D references need a workbook to determine formula text");
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_REF;
}
package org.apache.poi.ss.formula.ptg;
-/**
- *
- * @author andy
- */
public final class EqualPtg extends ValueOperatorPtg {
public static final byte sid = 0x0b;
import org.apache.poi.ss.formula.FormulaRenderingWorkbook;
import org.apache.poi.ss.formula.SheetNameFormatter;
-/**
- * @author Josh Micich
- */
final class ExternSheetNameResolver {
private ExternSheetNameResolver() {
// no instances of this class
/**
* Excel represents integers 0..65535 with the tInt token.
*
- * @return <code>true</code> if the specified value is within the range of values
- * <tt>IntPtg</tt> can represent.
+ * @return {@code true} if the specified value is within the range of values
+ * {@code IntPtg} can represent.
*/
public static boolean isInRange(int i) {
return i >= MIN_VALUE && i <= MAX_VALUE;
return field_1_value;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(sid + getPtgClass());
out.writeShort(getValue());
return sid;
}
+ @Override
public int getSize() {
return SIZE;
}
+ @Override
public String toFormulaString() {
return String.valueOf(getValue());
}
// enforce singleton
}
- public final boolean isBaseToken() {
+ @Override
+ public final boolean isBaseToken() {
return true;
}
return ""; // TODO: Not sure how to format this. -- DN
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
return "ERR#";
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
return "";
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_REF;
}
throw new RuntimeException("3D references need a workbook to determine formula text");
}
- public byte getDefaultOperandClass() {
+ @Override
+ public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
return sb.toString();
}
+ @Override
public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
return field_1_value;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(sid + getPtgClass());
out.writeDouble(getValue());
return sid;
}
+ @Override
public int getSize() {
return SIZE;
}
+ @Override
public String toFormulaString() {
return NumberToTextConverter.toText(field_1_value);
}
/**
* All Operand {@link Ptg}s are classified ('relative', 'value', 'array')
*/
- public final boolean isBaseToken() {
+ @Override
+ public final boolean isBaseToken() {
return false;
}
/**
* defines a Ptg that is an operation instead of an operand
- * @author andy
*/
public abstract class OperationPtg extends Ptg {
public static final int TYPE_UNARY = 0;
*/
public abstract int getNumberOfOperands();
+ @Override
public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
import org.apache.poi.util.LittleEndianOutput;
/**
- * <tt>Ptg</tt> represents a syntactic token in a formula. 'PTG' is an acronym for
+ * {@code Ptg} represents a syntactic token in a formula. 'PTG' is an acronym for
* '<b>p</b>arse <b>t</b>hin<b>g</b>'. Originally, the name referred to the single
- * byte identifier at the start of the token, but in POI, <tt>Ptg</tt> encapsulates
+ * byte identifier at the start of the token, but in POI, {@code Ptg} encapsulates
* the whole formula token (initial byte + value data).
* <p>
*
- * <tt>Ptg</tt>s are logically arranged in a tree representing the structure of the
- * parsed formula. However, in BIFF files <tt>Ptg</tt>s are written/read in
+ * {@code Ptg}s are logically arranged in a tree representing the structure of the
+ * parsed formula. However, in BIFF files {@code Ptg}s are written/read in
* <em>Reverse-Polish Notation</em> order. The RPN ordering also simplifies formula
- * evaluation logic, so POI mostly accesses <tt>Ptg</tt>s in the same way.
+ * evaluation logic, so POI mostly accesses {@code Ptg}s in the same way.
*/
public abstract class Ptg implements Duplicatable, GenericRecord {
public static final Ptg[] EMPTY_PTG_ARRAY = { };
}
/**
- * Reads <tt>size</tt> bytes of the input stream, to create an array of <tt>Ptg</tt>s.
- * Extra data (beyond <tt>size</tt>) may be read if and <tt>ArrayPtg</tt>s are present.
+ * Reads {@code size} bytes of the input stream, to create an array of {@code Ptg}s.
+ * Extra data (beyond {@code size}) may be read if and {@code ArrayPtg}s are present.
*/
public static Ptg[] readTokens(int size, LittleEndianInput in) {
List<Ptg> temp = new ArrayList<>(4 + size / 2);
/**
* This method will return the same result as {@link #getEncodedSizeWithoutArrayData(Ptg[])}
* if there are no array tokens present.
- * @return the full size taken to encode the specified <tt>Ptg</tt>s
+ * @return the full size taken to encode the specified {@code Ptg}s
*/
public static int getEncodedSize(Ptg[] ptgs) {
int result = 0;
public abstract byte getDefaultOperandClass();
/**
- * @return <code>false</code> if this token is classified as 'reference', 'value', or 'array'
+ * @return {@code false} if this token is classified as 'reference', 'value', or 'array'
*/
public abstract boolean isBaseToken();
if (ptg instanceof AreaErrPtg) {
return true;
}
- if (ptg instanceof RefErrorPtg) {
- return true;
- }
- return false;
+ return ptg instanceof RefErrorPtg;
}
@Override
// enforce singleton
}
+ @Override
public final boolean isBaseToken() {
return true;
}
return sid;
}
+ @Override
public int getSize() {
return SIZE;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(sid + getPtgClass());
}
+ @Override
public String toFormulaString()
{
return ":";
/** implementation of method from OperationsPtg*/
+ @Override
public String toFormulaString(String[] operands) {
return operands[0] + ":" + operands[1];
}
+ @Override
public int getNumberOfOperands()
{
return 2;
private static final int SIZE = 5;
public static final byte sid = 0x2A;
- private int field_1_reserved;
+ private final int field_1_reserved;
public RefErrorPtg() {
field_1_reserved = 0;
field_1_reserved = in.readInt();
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(sid + getPtgClass());
out.writeInt(field_1_reserved);
return sid;
}
+ @Override
public int getSize() {
return SIZE;
}
+ @Override
public String toFormulaString() {
return FormulaError.REF.getString();
}
+ @Override
public byte getDefaultOperandClass() {
return Ptg.CLASS_REF;
}
* Common superclass of all {@link Ptg Ptgs} that represent simple constant values.
*/
public abstract class ScalarConstantPtg extends Ptg {
+ @Override
public final boolean isBaseToken() {
return true;
}
- public final byte getDefaultOperandClass() {
+ @Override
+ public final byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
}
import org.apache.poi.util.LittleEndianOutput;
-/**
- * @author Glen Stampoultzis (glens at apache.org)
- */
public final class UnionPtg extends OperationPtg {
public static final byte sid = 0x10;
// enforce singleton
}
+ @Override
public final boolean isBaseToken() {
return true;
}
return sid;
}
+ @Override
public int getSize() {
return 1;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(sid + getPtgClass());
}
+ @Override
public String toFormulaString()
{
return ",";
/** implementation of method from OperationsPtg*/
+ @Override
public String toFormulaString(String[] operands) {
return operands[0] + "," + operands[1];
}
+ @Override
public int getNumberOfOperands()
{
return 2;
_sid = sid;
}
+ @Override
public boolean isBaseToken() {
return true;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(_sid);
}
return (byte)_sid;
}
+ @Override
public int getSize() {
return size;
}
+ @Override
public String toFormulaString() {
return "UNKNOWN";
}
+ @Override
public byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
protected ValueOperatorPtg() {}
/**
- * All Operator <tt>Ptg</tt>s are base tokens (i.e. are not RVA classified)
+ * All Operator {@code Ptg}s are base tokens (i.e. are not RVA classified)
*/
+ @Override
public final boolean isBaseToken() {
return true;
}
- public final byte getDefaultOperandClass() {
+ @Override
+ public final byte getDefaultOperandClass() {
return Ptg.CLASS_VALUE;
}
+ @Override
public void write(LittleEndianOutput out) {
out.writeByte(getSid());
}
+ @Override
public final int getSize() {
return 1;
}
+ @Override
public final String toFormulaString() {
// TODO - prune this method out of the hierarchy
throw new RuntimeException("toFormulaString(String[] operands) should be used for subclasses of OperationPtgs");
/**
* Collects add-in libraries and VB macro functions together into one UDF finder
- *
- * @author PUdalau
*/
public class AggregatingUDFFinder implements UDFFinder {
-
+
/**
* Default UDFFinder implementation
- */
+ */
public static final UDFFinder DEFAULT = new AggregatingUDFFinder(AnalysisToolPak.instance);
private final Collection<UDFFinder> _usedToolPacks;
/**
* Default UDF finder - for adding your own user defined functions.
- *
- * @author PUdalau
*/
public final class DefaultUDFFinder implements UDFFinder {
private final Map<String, FreeRefFunction> _functionsByName;
/**
* A UDFFinder that can retrieve functions both by name and by fake index.
- *
- * @author Yegor Kozlov
*/
@Internal
public class IndexedUDFFinder extends AggregatingUDFFinder {
/**
* Common implementation-independent logic shared by all implementations of {@link Cell}.
- * @author Vladislav "gallon" Galas gallon at apache dot org
*/
public abstract class CellBase implements Cell {
/**
/**
* Gets the number of cells in this range.
- * @return <tt>height * width </tt>
+ * @return {@code height * width }
*/
int size();
String getReferenceText();
/**
- * @return the cell at relative coordinates (0,0). Never <code>null</code>.
+ * @return the cell at relative coordinates (0,0). Never {@code null}.
*/
C getTopLeftCell();
/**
- * @param relativeRowIndex must be between <tt>0</tt> and <tt>height-1</tt>
- * @param relativeColumnIndex must be between <tt>0</tt> and <tt>width-1</tt>
- * @return the cell at the specified coordinates. Never <code>null</code>.
+ * @param relativeRowIndex must be between {@code 0} and {@code height-1}
+ * @param relativeColumnIndex must be between {@code 0} and {@code width-1}
+ * @return the cell at the specified coordinates. Never {@code null}.
*/
C getCell(int relativeRowIndex, int relativeColumnIndex);
/**
- * @return a flattened array of all the cells in this {@link CellRange}
+ * @return a flattened array of all the cells in this CellRange
*/
C[] getFlattenedCells();
/**
- * @return a 2-D array of all the cells in this {@link CellRange}. The first
- * array dimension is the row index (values <tt>0...height-1</tt>)
- * and the second dimension is the column index (values <tt>0...width-1</tt>)
+ * @return a 2-D array of all the cells in this CellRange. The first
+ * array dimension is the row index (values {@code 0...height-1})
+ * and the second dimension is the column index (values {@code 0...width-1})
*/
C[][] getCells();
* @return an {@link Iterator} over all cells in this range. Iteration starts
* with all cells in the first row followed by all cells in the next row, etc.
*/
+ @Override
Iterator<C> iterator();
}
/**
* The ConditionalFormatting class encapsulates all settings of Conditional Formatting.
*
- * The class can be used
- *
- * <UL>
- * <LI>
- * to make a copy ConditionalFormatting settings.
- * </LI>
- *
- *
+ * The class can be used to make a copy ConditionalFormatting settings.
+ * <p>
* For example:
- * <PRE>
+ * <pre>{@code
* ConditionalFormatting cf = sheet.getConditionalFormattingAt(index);
* newSheet.addConditionalFormatting(cf);
- * </PRE>
+ * }</pre>
*
- * <LI>
- * or to modify existing Conditional Formatting settings (formatting regions and/or rules).
- * </LI>
- * </UL>
+ * or to modify existing Conditional Formatting settings (formatting regions and/or rules).<p>
*
* Use {@link org.apache.poi.ss.usermodel.Sheet#getSheetConditionalFormatting()}
* to get access to an instance of this class.
- * <P>
+ * <p>
* To create a new Conditional Formatting set use the following approach:
*
- * <PRE>
+ * <pre>{@code
*
* // Define a Conditional Formatting rule, which triggers formatting
* // when cell's value is greater or equal than 100.0 and
*
* // Apply Conditional Formatting rule defined above to the regions
* sheet.addConditionalFormatting(regions, rule);
- * </PRE>
+ * }</pre>
*/
public interface ConditionalFormatting {
/**
- * @return array of <tt>CellRangeAddress</tt>s. Never <code>null</code>
+ * @return array of {@code CellRangeAddress}s. Never {@code null}
*/
CellRangeAddress[] getFormattingRanges();
/**
* Sets the cell ranges the rule conditional formatting must be applied to.
- * @param ranges non-null array of <tt>CellRangeAddress</tt>s
+ * @param ranges non-null array of {@code CellRangeAddress}s
*/
void setFormattingRanges(CellRangeAddress[] ranges);
* prefix or suffix.
* </p>
* <p>
- * For example the Excel pattern <code>"$#,##0.00 "USD"_);($#,##0.00 "USD")"
- * </code> will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)".
- * However the pattern <code>"00-00-00"</code> is incorrectly formatted by
+ * For example the Excel pattern {@code "$#,##0.00 "USD"_);($#,##0.00 "USD")"
+ * } will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)".
+ * However the pattern {@code "00-00-00"} is incorrectly formatted by
* DecimalFormat as "000000--". For Excel formats that are not compatible with
* DecimalFormat, you can provide your own custom {@link Format} implementation
- * via <code>DataFormatter.addFormat(String,Format)</code>. The following
+ * via {@code DataFormatter.addFormat(String,Format)}. The following
* custom formats are already provided by this class:
* </p>
- * <pre>
- * <ul><li>SSN "000-00-0000"</li>
- * <li>Phone Number "(###) ###-####"</li>
- * <li>Zip plus 4 "00000-0000"</li>
- * </ul>
- * </pre>
+ * <pre>{@code
+ * SSN "000-00-0000"
+ * Phone Number "(###) ###-####"
+ * Zip plus 4 "00000-0000"
+ * }</pre>
* <p>
* If the Excel format pattern cannot be parsed successfully, then a default
* format will be used. The default number format will mimic the Excel General
* format: "#" for whole numbers and "#.##########" for decimal numbers. You
- * can override the default format pattern with <code>
- * DataFormatter.setDefaultNumberFormat(Format)</code>. <b>Note:</b> the
+ * can override the default format pattern with {@code
+ * DataFormatter.setDefaultNumberFormat(Format)}. <b>Note:</b> the
* default format will only be used when a Format cannot be created from the
* cell's data format string.
*
* </p>
* <p>Example:</p>
* <p>
- * Consider a numeric cell with a value <code>12.343</code> and format <code>"##.##_ "</code>.
- * The trailing underscore and space ("_ ") in the format adds a space to the end and Excel formats this cell as <code>"12.34 "</code>,
- * but <code>DataFormatter</code> trims the formatted value and returns <code>"12.34"</code>.
+ * Consider a numeric cell with a value {@code 12.343} and format {@code "##.##_ "}.
+ * The trailing underscore and space ("_ ") in the format adds a space to the end and Excel formats this cell as {@code "12.34 "},
+ * but {@code DataFormatter} trims the formatted value and returns {@code "12.34"}.
* </p>
- * You can enable spaces by passing the <code>emulateCSV=true</code> flag in the <code>DateFormatter</code> cosntructor.
+ * You can enable spaces by passing the {@code emulateCSV=true} flag in the {@code DateFormatter} cosntructor.
* If set to true, then the output tries to conform to what you get when you take an xls or xlsx in Excel and Save As CSV file:
* <ul>
* <li>returned values are not trimmed</li>
* <li>Invalid dates are formatted as 255 pound signs ("#")</li>
* <li>simulate Excel's handling of a format string of all # when the value is 0.
- * Excel will output "", <code>DataFormatter</code> will output "0".
+ * Excel will output "", {@code DataFormatter} will output "0".
* </ul>
* <p>
* Some formats are automatically "localized" by Excel, eg show as mm/dd/yyyy when
* loaded in Excel in some Locales but as dd/mm/yyyy in others. These are always
* returned in the "default" (US) format, as stored in the file.
* Some format strings request an alternate locale, eg
- * <code>[$-809]d/m/yy h:mm AM/PM</code> which explicitly requests UK locale.
+ * {@code [$-809]d/m/yy h:mm AM/PM} which explicitly requests UK locale.
* These locale directives are (currently) ignored.
* You can use {@link DateFormatConverter} to do some of this localisation if
* you need it.
/**
* Return a Format for the given cell if one exists, otherwise try to
- * create one. This method will return <code>null</code> if any of the
+ * create one. This method will return {@code null} if any of the
* following is true:
* <ul>
* <li>the cell's style is null</li>
private static class InternalDecimalFormatWithScale extends Format {
private static final Pattern endsWithCommas = Pattern.compile("(,+)$");
- private BigDecimal divider;
+ private final BigDecimal divider;
private static final BigDecimal ONE_THOUSAND = new BigDecimal(1000);
private final DecimalFormat df;
private static String trimTrailingCommas(String s) {
}
/**
- * Returns the formatted value of an Excel date as a <tt>String</tt> based
- * on the cell's <code>DataFormat</code>. i.e. "Thursday, January 02, 2003"
+ * Returns the formatted value of an Excel date as a {@code String} based
+ * on the cell's {@code DataFormat}. i.e. "Thursday, January 02, 2003"
* , "01/02/2003" , "02-Jan" , etc.
* <p>
* If any conditional format rules apply, the highest priority with a number format is used.
}
/**
- * Returns the formatted value of an Excel number as a <tt>String</tt>
- * based on the cell's <code>DataFormat</code>. Supported formats include
+ * Returns the formatted value of an Excel number as a {@code String}
+ * based on the cell's {@code DataFormat}. Supported formats include
* currency, percents, decimals, phone number, SSN, etc.:
* "61.54%", "$100.00", "(800) 555-1234".
* <p>
/**
* <p>
- * Returns the formatted value of a cell as a <tt>String</tt> regardless
+ * Returns the formatted value of a cell as a {@code String} regardless
* of the cell type. If the Excel format pattern cannot be parsed then the
* cell value will be formatted using a default format.
* </p>
/**
* <p>
- * Returns the formatted value of a cell as a <tt>String</tt> regardless
+ * Returns the formatted value of a cell as a {@code String} regardless
* of the cell type. If the Excel number format pattern cannot be parsed then the
* cell value will be formatted using a default format.
* </p>
/**
* <p>
- * Returns the formatted value of a cell as a <tt>String</tt> regardless
+ * Returns the formatted value of a cell as a {@code String} regardless
* of the cell type. If the Excel number format pattern cannot be parsed then the
* cell value will be formatted using a default format.
* </p>
* </p>
* <p>
* The value that will be passed to the Format's format method (specified
- * by <code>java.text.Format#format</code>) will be a double value from a
+ * by {@code java.text.Format#format}) will be a double value from a
* numeric cell. Therefore the code in the format method should expect a
- * <code>Number</code> value.
+ * {@code Number} value.
* </p>
*
* @param format A Format instance to be used as a default
* Adds a new format to the available formats.
* <p>
* The value that will be passed to the Format's format method (specified
- * by <code>java.text.Format#format</code>) will be a double value from a
+ * by {@code java.text.Format#format}) will be a double value from a
* numeric cell. Therefore the code in the format method should expect a
- * <code>Number</code> value.
+ * {@code Number} value.
* </p>
* @param excelFormatStr The data format string
* @param format A Format instance
// Some custom formats
/**
- * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code>
+ * @return a {@code DecimalFormat} with parseIntegerOnly set {@code true}
*/
private static DecimalFormat createIntegerOnlyFormat(String fmt) {
DecimalFormatSymbols dsf = DecimalFormatSymbols.getInstance(Locale.ROOT);
/**
* Format class for Excel's SSN format. This class mimics Excel's built-in
* SSN formatting.
- *
- * @author James May
*/
@SuppressWarnings("serial")
private static final class SSNFormat extends Format {
/**
* Format class for Excel Zip + 4 format. This class mimics Excel's
* built-in formatting for Zip + 4.
- * @author James May
*/
@SuppressWarnings("serial")
private static final class ZipPlusFourFormat extends Format {
/**
* Format class for Excel phone number format. This class mimics Excel's
* built-in phone number formatting.
- * @author James May
*/
@SuppressWarnings("serial")
private static final class PhoneFormat extends Format {
private CellFormatResultWrapper(CellFormatResult result) {
this.result = result;
}
+ @Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
if (emulateCSV) {
return toAppendTo.append(result.text);
return toAppendTo.append(result.text.trim());
}
}
+ @Override
public Object parseObject(String source, ParsePosition pos) {
return null; // Not supported
}
import org.apache.poi.ss.util.CellRangeAddressList;
-/**
- * @author <a href="rjankiraman@emptoris.com">Radhakrishnan J</a>
- *
- */
public interface DataValidationHelper {
-
+
DataValidationConstraint createFormulaListConstraint(String listFormula);
DataValidationConstraint createExplicitListConstraint(String[] listOfValues);
DataValidationConstraint createNumericConstraint(int validationType,int operatorType, String formula1, String formula2);
-
+
DataValidationConstraint createTextLengthConstraint(int operatorType, String formula1, String formula2);
-
+
DataValidationConstraint createDecimalConstraint(int operatorType, String formula1, String formula2);
-
+
DataValidationConstraint createIntegerConstraint(int operatorType, String formula1, String formula2);
-
+
DataValidationConstraint createDateConstraint(int operatorType, String formula1, String formula2,String dateFormat);
-
+
DataValidationConstraint createTimeConstraint(int operatorType, String formula1, String formula2);
-
+
DataValidationConstraint createCustomConstraint(String formula);
-
+
DataValidation createValidation(DataValidationConstraint constraint,CellRangeAddressList cellRangeAddressList);
}
/**
* The font family this font belongs to. A font family is a set of fonts having common stroke width and serif
* characteristics. The font name overrides when there are conflicting values.
- *
- * @author Gisella Bronzetti
*/
public enum FontFamily {
* When a new theme is chosen, every font that is part of a theme definition is updated to use the new major or minor font definition for that
* theme.
* Usually major fonts are used for styles like headings, and minor fonts are used for body & paragraph text.
- *
- * @author Gisella Bronzetti
*/
public enum FontScheme {
/**
* the different types of possible underline formatting
- *
- * @author Gisella Bronzetti
*/
public enum FontUnderline {
/**
* Evaluates formula cells.<p>
- *
+ *
* For performance reasons, this class keeps a cache of all previously calculated intermediate
* cell values. Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between
* calls to evaluate~ methods on this class.
- *
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- * @author Josh Micich
*/
public interface FormulaEvaluator {
*/
void clearAllCachedResultValues();
/**
- * Should be called to tell the cell value cache that the specified (value or formula) cell
+ * Should be called to tell the cell value cache that the specified (value or formula) cell
* has changed.
* Failure to call this method after changing cell values will cause incorrect behaviour
* of the evaluate~ methods of this class
void notifySetFormula(Cell cell);
/**
* Should be called to tell the cell value cache that the specified cell has just become a
- * formula cell, or the formula text has changed
+ * formula cell, or the formula text has changed
*/
void notifyDeleteCell(Cell cell);
/**
* Loops over all cells in all sheets of the associated workbook.
- * For cells that contain formulas, their formulas are evaluated,
+ * For cells that contain formulas, their formulas are evaluated,
* and the results are saved. These cells remain as formula cells.
* For cells that do not contain formulas, no changes are made.
- * This is a helpful wrapper around looping over all cells, and
+ * This is a helpful wrapper around looping over all cells, and
* calling evaluateFormulaCell on each one.
*/
void evaluateAll();
-
+
/**
* If cell contains a formula, the formula is evaluated and returned,
* else the CellValue simply copies the appropriate cell value from
* and the result. If you want the cell replaced with
* the result of the formula, use {@link #evaluateInCell(Cell)}
* @param cell The cell to evaluate
- * @return The type of the formula result, i.e. -1 if the cell is not a formula,
+ * @return The type of the formula result, i.e. -1 if the cell is not a formula,
* or one of {@link CellType#NUMERIC}, {@link CellType#STRING},
* {@link CellType#BOOLEAN}, {@link CellType#ERROR}
* Note: the cell's type remains as CellType.FORMULA however.
* @param cell The {@link Cell} to evaluate and modify.
*/
Cell evaluateInCell(Cell cell);
-
+
/**
* Sets up the Formula Evaluator to be able to reference and resolve
* links to other workbooks, eg [Test.xls]Sheet1!A1.
* In some cases external workbooks referenced by formulas in the main workbook are not available.
* With this method you can control how POI handles such missing references:
* <ul>
- * <li>by default ignoreMissingWorkbooks=false and POI throws
+ * <li>by default ignoreMissingWorkbooks=false and POI throws
* {@link org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment.WorkbookNotFoundException}
* if an external reference cannot be resolved</li>
* <li>if ignoreMissingWorkbooks=true then POI uses cached formula result
* @param ignore whether to ignore missing references to external workbooks
*/
void setIgnoreMissingWorkbooks(boolean ignore);
-
+
/**
* Perform detailed output of formula evaluation for next evaluation only?
* Is for developer use only (also developers using POI for their XLS files).
* Log-Level WARN is for basic info, INFO for detailed information. These quite
* high levels are used because you have to explicitly enable this specific logging.
-
+
* @param value whether to perform detailed output
*/
void setDebugEvaluationOutputForNextEval(boolean value);
* Each element corresponds to a color index (zero-based). When using the default indexed color palette,
* the values are not written out, but instead are implied. When the color palette has been modified from default,
* then the entire color palette is used.
- * </p>
- *
- * @author Yegor Kozlov
*/
public enum IndexedColors {
_values[color.index] = color;
}
}
-
+
public final short index;
IndexedColors(int idx){
public short getIndex(){
return index;
}
-
+
/**
- *
+ *
*
* @param index the index of the color
* @return the corresponding IndexedColors enum
/**
* Specifies printed page order.
- *
- * @author Gisella Bronzetti
*/
public enum PageOrder {
/**
* The enumeration value indicating the possible paper size for a sheet
- *
- * @author Daniele Montagni
*/
public enum PaperSize {
LETTER_PAPER,
package org.apache.poi.ss.usermodel;
-/**
- * @author Yegor Kozlov
- */
public interface PatternFormatting {
/** No background */
public static final short NO_FILL = 0 ;
/**
* These enumerations specify how cell comments shall be displayed for paper printing purposes.
- *
- * @author Gisella Bronzetti
*/
public enum PrintCellComments {
/**
* The enumeration value indicating the print orientation for a sheet.
- *
- * @author Gisella Bronzetti
*/
public enum PrintOrientation {
package org.apache.poi.ss.usermodel;
/**
- * Rich text unicode string. These strings can have fonts
+ * Rich text unicode string. These strings can have fonts
* applied to arbitary parts of the string.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- * @author Jason Height (jheight at apache.org)
*/
public interface RichTextString {
-
+
/**
* Applies a font to the specified characters of a string.
*
/**
* All known types of automatic shapes in DrawingML
- *
- * @author Yegor Kozlov
*/
public class ShapeTypes {
public static final int LINE = 1;
* Get the hidden state for a given column
*
* @param columnIndex - the column to set (0-based)
- * @return hidden - <code>false</code> if the column is visible
+ * @return hidden - {@code false} if the column is visible
*/
boolean isColumnHidden(int columnIndex);
* in a cell that is formatted with the standard font (first font in the workbook).<p>
*
* Character width is defined as the maximum digit width
- * of the numbers <code>0, 1, 2, ... 9</code> as rendered
+ * of the numbers {@code 0, 1, 2, ... 9} as rendered
* using the default font (first font in the workbook).<p>
*
* Unless you are using a very special font, the default character is '0' (zero),
* To compute the actual number of visible characters,
* Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):<p>
*
- * <code>
+ * {@code
* width = Truncate([{Number of Visible Characters} *
* {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
- * </code>
+ * }
*
* Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi).
- * If you set a column width to be eight characters wide, e.g. <code>setColumnWidth(columnIndex, 8*256)</code>,
+ * If you set a column width to be eight characters wide, e.g. {@code setColumnWidth(columnIndex, 8*256)},
* then the actual value of visible characters (the value shown in Excel) is derived from the following equation:
- * <code>
+ * {@code
* Truncate([numChars*7+5]/7*256)/256 = 8;
- * </code>
+ * }
*
- * which gives <code>7.29</code>.
+ * which gives {@code 7.29}.
*
* @param columnIndex - the column to set (0-based)
* @param width - the width in units of 1/256th of a character width
*
* <p>
* Character width is defined as the maximum digit width
- * of the numbers <code>0, 1, 2, ... 9</code> as rendered
+ * of the numbers {@code 0, 1, 2, ... 9} as rendered
* using the default font (first font in the workbook)
* </p>
*
/**
* Flag indicating whether the sheet displays Automatic Page Breaks.
*
- * @param value <code>true</code> if the sheet displays Automatic Page Breaks.
+ * @param value {@code true} if the sheet displays Automatic Page Breaks.
*/
void setAutobreaks(boolean value);
/**
* Flag indicating whether the Fit to Page print option is enabled.
*
- * @param value <code>true</code> if the Fit to Page print option is enabled.
+ * @param value {@code true} if the Fit to Page print option is enabled.
*/
void setFitToPage(boolean value);
* When false a summary row is inserted above the detailed data being summarized and a new outline level
* is established on that row.
* </p>
- * @param value <code>true</code> if row summaries appear below detail in the outline
+ * @param value {@code true} if row summaries appear below detail in the outline
*/
void setRowSumsBelow(boolean value);
* When false a summary column is inserted to the left of the detailed data being
* summarized and a new outline level is established on that column.
* </p>
- * @param value <code>true</code> if col summaries appear right of the detail in the outline
+ * @param value {@code true} if col summaries appear right of the detail in the outline
*/
void setRowSumsRight(boolean value);
/**
* Flag indicating whether the sheet displays Automatic Page Breaks.
*
- * @return <code>true</code> if the sheet displays Automatic Page Breaks.
+ * @return {@code true} if the sheet displays Automatic Page Breaks.
*/
boolean getAutobreaks();
/**
* Flag indicating whether the Fit to Page print option is enabled.
*
- * @return <code>true</code> if the Fit to Page print option is enabled.
+ * @return {@code true} if the Fit to Page print option is enabled.
*/
boolean getFitToPage();
* When false a summary row is inserted above the detailed data being summarized and a new outline level
* is established on that row.
* </p>
- * @return <code>true</code> if row summaries appear below detail in the outline
+ * @return {@code true} if row summaries appear below detail in the outline
*/
boolean getRowSumsBelow();
* When false a summary column is inserted to the left of the detailed data being
* summarized and a new outline level is established on that column.
* </p>
- * @return <code>true</code> if col summaries appear right of the detail in the outline
+ * @return {@code true} if col summaries appear right of the detail in the outline
*/
boolean getRowSumsRight();
* Gets the flag indicating whether this sheet displays the lines
* between rows and columns to make editing and reading easier.
*
- * @return <code>true</code> if this sheet prints gridlines.
+ * @return {@code true} if this sheet prints gridlines.
* @see #isDisplayGridlines() to check if gridlines are displayed on screen
*/
boolean isPrintGridlines();
* Sets the flag indicating whether this sheet should print the lines
* between rows and columns to make editing and reading easier.
*
- * @param show <code>true</code> if this sheet should print gridlines.
+ * @param show {@code true} if this sheet should print gridlines.
* @see #setDisplayGridlines(boolean) to display gridlines on screen
*/
void setPrintGridlines(boolean show);
* Gets the flag indicating whether this sheet prints the
* row and column headings when printing.
*
- * @return <code>true</code> if this sheet prints row and column headings.
+ * @return {@code true} if this sheet prints row and column headings.
*/
boolean isPrintRowAndColumnHeadings();
* Sets the flag indicating whether this sheet should print
* row and columns headings when printing.
*
- * @param show <code>true</code> if this sheet should print row and column headings.
+ * @param show {@code true} if this sheet should print row and column headings.
*/
void setPrintRowAndColumnHeadings(boolean show);
*
* Note that XSSF offers more kinds of document headers than HSSF does
*
- * @return the document header. Never <code>null</code>
+ * @return the document header. Never {@code null}
*/
Header getHeader();
*
* Note that XSSF offers more kinds of document footers than HSSF does.
*
- * @return the document footer. Never <code>null</code>
+ * @return the document footer. Never {@code null}
*/
Footer getFooter();
*
* Note: multiple sheets can be selected, but only one sheet can be active at one time.
*
- * @param value <code>true</code> if this sheet is selected
+ * @param value {@code true} if this sheet is selected
* @see Workbook#setActiveSheet(int)
*/
void setSelected(boolean value);
/**
* Sets the protection enabled as well as the password
- * @param password to set for protection. Pass <code>null</code> to remove protection
+ * @param password to set for protection. Pass {@code null} to remove protection
*/
void protectSheet(String password);
* Sets a page break at the indicated row
* Breaks occur above the specified row and left of the specified column inclusive.
*
- * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
- * with columns A,B,C in the first and D,E,... in the second. Similar, <code>sheet.setRowBreak(2);</code>
+ * For example, {@code sheet.setColumnBreak(2);} breaks the sheet into two parts
+ * with columns A,B,C in the first and D,E,... in the second. Similar, {@code sheet.setRowBreak(2);}
* breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
* and rows starting with rownum=4 in the second.
*
* Sets a page break at the indicated column.
* Breaks occur above the specified row and left of the specified column inclusive.
*
- * For example, <code>sheet.setColumnBreak(2);</code> breaks the sheet into two parts
- * with columns A,B,C in the first and D,E,... in the second. Similar, <code>sheet.setRowBreak(2);</code>
+ * For example, {@code sheet.setColumnBreak(2);} breaks the sheet into two parts
+ * with columns A,B,C in the first and D,E,... in the second. Similar, {@code sheet.setRowBreak(2);}
* breaks the sheet into two parts with first three rows (rownum=1...3) in the first part
* and rows starting with rownum=4 in the second.
*
/**
* Returns cell comment for the specified location
*
- * @return cell comment or <code>null</code> if not found
+ * @return cell comment or {@code null} if not found
*/
Comment getCellComment(CellAddress ref);
/**
* Note - this is not the same as whether the sheet is focused (isActive)
- * @return <code>true</code> if this sheet is currently selected
+ * @return {@code true} if this sheet is currently selected
*/
boolean isSelected();
AutoFilter setAutoFilter(CellRangeAddress range);
/**
- * The 'Conditional Formatting' facet for this <tt>Sheet</tt>
+ * The 'Conditional Formatting' facet for this {@code Sheet}
*
* @return conditional formatting rule for this sheet
*/
List<? extends Hyperlink> getHyperlinkList();
/**
- * Return location of the active cell, e.g. <code>A1</code>.
+ * Return location of the active cell, e.g. {@code A1}.
*
* @return the location of the active cell.
* @since 3.14beta1
/**
* Sets location of the active cell
*
- * @param address the location of the active cell, e.g. <code>A1</code>.
+ * @param address the location of the active cell, e.g. {@code A1}.
* @since 3.14beta1
*/
void setActiveCell(CellAddress address);
import org.apache.poi.ss.util.CellRangeAddress;
/**
- * The 'Conditional Formatting' facet of <tt>Sheet</tt>
+ * The 'Conditional Formatting' facet of {@code Sheet}
*
* @since 3.8
*/
* </p>
*
* @param comparisonOperation - MUST be a constant value from
- * <tt>{@link ComparisonOperator}</tt>: <p>
+ * {@link ComparisonOperator}:
* <ul>
* <li>BETWEEN</li>
* <li>NOT_BETWEEN</li>
* <li>GE</li>
* <li>LE</li>
* </ul>
- * </p>
* @param formula1 - formula for the valued, compared with the cell
* @param formula2 - second formula (only used with
* {@link ComparisonOperator#BETWEEN}) and {@link ComparisonOperator#NOT_BETWEEN} operations)
* </p>
*
* @param comparisonOperation MUST be a constant value from
- * <tt>{@link ComparisonOperator}</tt> except BETWEEN and NOT_BETWEEN
+ * {@link ComparisonOperator} except BETWEEN and NOT_BETWEEN
*
* @param formula the formula to determine if the conditional formatting is applied
*/
/**
* Create a Databar conditional formatting rule.
- * <p>The thresholds and colour for it will be created, but will be
- * empty and require configuring with
+ * <p>The thresholds and colour for it will be created, but will be
+ * empty and require configuring with
* {@link ConditionalFormattingRule#getDataBarFormatting()}
* then
* {@link DataBarFormatting#getMinThreshold()}
- * and
+ * and
* {@link DataBarFormatting#getMaxThreshold()}
*/
ConditionalFormattingRule createConditionalFormattingRule(ExtendedColor color);
-
+
/**
* Create an Icon Set / Multi-State conditional formatting rule.
* <p>The thresholds for it will be created, but will be empty
- * and require configuring with
+ * and require configuring with
* {@link ConditionalFormattingRule#getMultiStateFormatting()}
* then
* {@link IconMultiStateFormatting#getThresholds()}
/**
* Create a Color Scale / Color Gradient conditional formatting rule.
- * <p>The thresholds and colours for it will be created, but will be
- * empty and require configuring with
+ * <p>The thresholds and colours for it will be created, but will be
+ * empty and require configuring with
* {@link ConditionalFormattingRule#getColorScaleFormatting()}
* then
* {@link ColorScaleFormatting#getThresholds()}
* {@link ColorScaleFormatting#getColors()}
*/
ConditionalFormattingRule createConditionalFormattingColorScaleRule();
-
+
/**
* Gets Conditional Formatting object at a particular index
*
* @param index 0-based index of the Conditional Formatting object to fetch
- * @return Conditional Formatting object or <code>null</code> if not found
+ * @return Conditional Formatting object or {@code null} if not found
* @throws IllegalArgumentException if the index is outside of the allowable range (0 ... numberOfFormats-1)
*/
ConditionalFormatting getConditionalFormattingAt(int index);
public class AreaReference {
- /** The character (!) that separates sheet names from cell references */
+ /** The character (!) that separates sheet names from cell references */
private static final char SHEET_NAME_DELIMITER = '!';
/** The character (:) that separates the two cell references in a multi-cell area reference */
private static final char CELL_DELIMITER = ':';
/** The character (') used to quote sheet names when they contain special characters */
private static final char SPECIAL_NAME_DELIMITER = '\'';
private static final SpreadsheetVersion DEFAULT_SPREADSHEET_VERSION = SpreadsheetVersion.EXCEL97;
-
+
private final CellReference _firstCell;
private final CellReference _lastCell;
private final boolean _isSingleCell;
private final SpreadsheetVersion _version; // never null
-
+
/**
* Create an area ref from a string representation. Sheet names containing special characters should be
- * delimited and escaped as per normal syntax rules for formulas.<br>
+ * delimited and escaped as per normal syntax rules for formulas.<br>
* The area reference must be contiguous (i.e. represent a single rectangle, not a union of rectangles)
*/
public AreaReference(String reference, SpreadsheetVersion version) {
// TODO - probably shouldn't initialize area ref when text is really a cell ref
// Need to fix some named range stuff to get rid of this
_firstCell = new CellReference(part0);
-
+
_lastCell = _firstCell;
_isSingleCell = true;
return;
if (parts.length != 2) {
throw new IllegalArgumentException("Bad area ref '" + reference + "'");
}
-
+
String part1 = parts[1];
if (isPlainColumn(part0)) {
if (!isPlainColumn(part1)) {
boolean firstIsAbs = CellReference.isPartAbsolute(part0);
boolean lastIsAbs = CellReference.isPartAbsolute(part1);
-
+
int col0 = CellReference.convertColStringToIndex(part0);
int col1 = CellReference.convertColStringToIndex(part1);
-
+
_firstCell = new CellReference(0, col0, true, firstIsAbs);
_lastCell = new CellReference(0xFFFF, col1, true, lastIsAbs);
_isSingleCell = false;
_isSingleCell = part0.equals(part1);
}
}
-
+
/**
* Creates an area ref from a pair of Cell References.
*/
}
_isSingleCell = false;
}
-
+
private static boolean isPlainColumn(String refPart) {
for(int i=refPart.length()-1; i>=0; i--) {
int ch = refPart.charAt(i);
*/
public static boolean isWholeColumnReference(SpreadsheetVersion version, CellReference topLeft, CellReference botRight) {
if (null == version) {
- version = DEFAULT_SPREADSHEET_VERSION; // how the code used to behave.
+ version = DEFAULT_SPREADSHEET_VERSION; // how the code used to behave.
}
-
+
// These are represented as something like
// C$1:C$65535 or D$1:F$0
// i.e. absolute from 1st row to 0th one
* Separates Area refs in two parts and returns them as separate elements in a String array,
* each qualified with the sheet name (if present)
*
- * @return array with one or two elements. never <code>null</code>
+ * @return array with one or two elements. never {@code null}
*/
private static String[] separateAreaRefs(String reference) {
// TODO - refactor cell reference parsing logic to one place.
}
return results.toArray(new String[0]);
}
-
+
public boolean isWholeColumnReference() {
return isWholeColumnReference(_version, _firstCell, _lastCell);
}
-
+
/**
- * @return <code>false</code> if this area reference involves more than one cell
+ * @return {@code false} if this area reference involves more than one cell
*/
public boolean isSingleCell() {
return _isSingleCell;
/**
* Note - if this area reference refers to a single cell, the return value of this method will
- * be identical to that of <tt>getFirstCell()</tt>
+ * be identical to that of {@code getFirstCell()}
* @return the second cell reference which defines this area. For multi-cell areas, this is
* cell diagonally opposite the 'first cell'. Usually this cell is in the lower right corner
* of the area (but this is not a requirement).
* It is barely a container for these two coordinates. The implementation
* of the Comparable interface sorts by "natural" order top left to bottom right.</p>
*
- * <p>Use <tt>CellAddress</tt> when you want to refer to the location of a cell in a sheet
+ * <p>Use {@code CellAddress} when you want to refer to the location of a cell in a sheet
* when the concept of relative/absolute does not apply (such as the anchor location
* of a cell comment). Use {@link CellReference} when the concept of
* relative/absolute does apply (such as a cell reference in a formula).
- * <tt>CellAddress</tt>es do not have a concept of "sheet", while <tt>CellReference</tt>s do.</p>
+ * {@code CellAddress}es do not have a concept of "sheet", while {@code CellReference}s do.</p>
*/
public class CellAddress implements Comparable<CellAddress> {
/** A constant for references to the first cell in a sheet. */
* Compare this CellAddress using the "natural" row-major, column-minor ordering.
* That is, top-left to bottom-right ordering.
*
- * @param other
* @return <ul>
* <li>-1 if this CellAddress is before (above/left) of other</li>
* <li>0 if addresses are the same</li>
@Override
public int compareTo(CellAddress other) {
int r = this._row-other._row;
- if (r!=0) {
- return r;
- }
-
- r = this._col-other._col;
- if (r!=0) {
- return r;
- }
+ return r != 0 ? r : this._col - other._col;
- return 0;
}
@Override
* Ref8U - see page 831 of version 1.0 of the documentation.
*
* Note - {@link SelectionRecord} uses the BIFF5 version of this structure
- * @author Dragos Buleandra (dragos.buleandra@trade2b.ro)
*/
public class CellRangeAddress extends CellRangeAddressBase {
public static final int ENCODED_SIZE = 8;
* several records (not formulas). A cell range address list consists of a field
* with the number of ranges and the list of the range addresses. Each cell
* range address (called an ADDR structure) contains 4 16-bit-values.
- * </p>
*/
public class CellRangeAddressList implements GenericRecord {
/**
- * List of <tt>CellRangeAddress</tt>es. Each structure represents a cell range
+ * List of {@code CellRangeAddress}es. Each structure represents a cell range
*/
protected final List<CellRangeAddress> _list = new ArrayList<>();
public CellRangeAddressList() {
}
/**
- * Convenience constructor for creating a <tt>CellRangeAddressList</tt> with a single
- * <tt>CellRangeAddress</tt>. Other <tt>CellRangeAddress</tt>es may be added later.
+ * Convenience constructor for creating a {@code CellRangeAddressList} with a single
+ * {@code CellRangeAddress}. Other {@code CellRangeAddress}es may be added later.
*/
public CellRangeAddressList(int firstRow, int lastRow, int firstCol, int lastCol) {
addCellRangeAddress(firstRow, firstCol, lastRow, lastCol);
}
/**
- * @return <tt>CellRangeAddress</tt> at the given index
+ * @return {@code CellRangeAddress} at the given index
*/
public CellRangeAddress getCellRangeAddress(int index) {
return _list.get(index);
* style references. Handles sheet-based and sheet-free references
* as well, eg "Sheet1!A1" and "$B$72"</p>
*
- * <p>Use <tt>CellReference</tt> when the concept of
+ * <p>Use {@code CellReference} when the concept of
* relative/absolute does apply (such as a cell reference in a formula).
* Use {@link CellAddress} when you want to refer to the location of a cell in a sheet
* when the concept of relative/absolute does not apply (such as the anchor location
* of a cell comment).
- * <tt>CellReference</tt>s have a concept of "sheet", while <tt>CellAddress</tt>es do not.</p>
+ * {@code CellReference}s have a concept of "sheet", while {@code CellAddress}es do not.</p>
*/
public class CellReference implements GenericRecord {
/**
public boolean isRowAbsolute(){return _isRowAbs;}
public boolean isColAbsolute(){return _isColAbs;}
/**
- * @return possibly <code>null</code> if this is a 2D reference. Special characters are not
+ * @return possibly {@code null} if this is a 2D reference. Special characters are not
* escaped or delimited
*/
public String getSheetName(){
/**
* Classifies an identifier as either a simple (2D) cell reference or a named range name
- * @return one of the values from <tt>NameType</tt>
+ * @return one of the values from {@code NameType}
*/
public static NameType classifyCellReference(String str, SpreadsheetVersion ssVersion) {
int len = str.length();
* reference is valid (in range) becomes important.
* <p>
* Note - that the maximum sheet size varies across Excel versions:
- * <p>
* <blockquote><table border="0" cellpadding="1" cellspacing="0"
* summary="Notable cases.">
* <tr><th>Version </th><th>File Format </th>
*
* @param colStr a string of only letter characters
* @param rowStr a string of only digit characters
- * @return <code>true</code> if the row and col parameters are within range of a BIFF8 spreadsheet.
+ * @return {@code true} if the row and col parameters are within range of a BIFF8 spreadsheet.
*/
public static boolean cellReferenceIsWithinRange(String colStr, String rowStr, SpreadsheetVersion ssVersion) {
if (!isColumnWithinRange(colStr, ssVersion)) {
* style change to a cell, the code will attempt to see if a style already exists that meets your
* needs. If not, then it will create a new style. This is to prevent creating too many styles.
* there is an upper limit in Excel on the number of styles that can be supported.
- *
- *@author Eric Pugh epugh@upstate.com
- *@author (secondary) Avinash Kewalramani akewalramani@accelrys.com
*/
public final class CellUtil {
-
+
private static final Logger LOGGER = LogManager.getLogger(CellUtil.class);
// FIXME: Move these constants into an enum
public static final String ROTATION = "rotation";
public static final String VERTICAL_ALIGNMENT = "verticalAlignment";
public static final String WRAP_TEXT = "wrapText";
-
+
private static final Set<String> shortValues = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
BOTTOM_BORDER_COLOR,
ROTATION
)));
private static final Set<String> intValues = Collections.unmodifiableSet(
- new HashSet<>(Arrays.asList(
- FONT
+ new HashSet<>(Collections.singletonList(
+ FONT
)));
private static final Set<String> booleanValues = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
)));
- private static UnicodeMapping[] unicodeMappings;
+ private static final UnicodeMapping[] unicodeMappings;
private static final class UnicodeMapping {
/**
* Take a cell, and align it.
- *
+ *
* This is superior to cell.getCellStyle().setAlignment(align) because
* this method will not modify the CellStyle object that may be referenced
* by multiple cells. Instead, this method will search for existing CellStyles
public static void setAlignment(Cell cell, HorizontalAlignment align) {
setCellStyleProperty(cell, ALIGNMENT, align);
}
-
+
/**
* Take a cell, and vertically align it.
- *
+ *
* This is superior to cell.getCellStyle().setVerticalAlignment(align) because
* this method will not modify the CellStyle object that may be referenced
* by multiple cells. Instead, this method will search for existing CellStyles
public static void setVerticalAlignment(Cell cell, VerticalAlignment align) {
setCellStyleProperty(cell, VERTICAL_ALIGNMENT, align);
}
-
+
/**
* Take a cell, and apply a font to it
*
* @param cell the cell to set the alignment for
* @param font The Font that you want to set.
- * @throws IllegalArgumentException if <tt>font</tt> and <tt>cell</tt> do not belong to the same workbook
+ * @throws IllegalArgumentException if {@code font} and {@code cell} do not belong to the same workbook
*/
public static void setFont(Cell cell, Font font) {
// Check if font belongs to workbook
}
/**
- * <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
- * current style plus styles properties in <code>properties</code>. A new style is created if the
+ * <p>This method attempts to find an existing CellStyle that matches the {@code cell}'s
+ * current style plus styles properties in {@code properties}. A new style is created if the
* workbook does not contain a matching style.</p>
- *
- * <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
+ *
+ * <p>Modifies the cell style of {@code cell} without affecting other cells that use the
* same style.</p>
- *
+ *
* <p>This is necessary because Excel has an upper limit on the number of styles that it supports.</p>
- *
+ *
* <p>This function is more efficient than multiple calls to
* {@link #setCellStyleProperty(Cell, String, Object)}
* if adding multiple cell styles.</p>
- *
+ *
* <p>For performance reasons, if this is the only cell in a workbook that uses a cell style,
* this method does NOT remove the old style from the workbook.
* <!-- NOT IMPLEMENTED: Unused styles should be
}
/**
- * <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
- * current style plus a single style property <code>propertyName</code> with value
- * <code>propertyValue</code>.
+ * <p>This method attempts to find an existing CellStyle that matches the {@code cell}'s
+ * current style plus a single style property {@code propertyName} with value
+ * {@code propertyValue}.
* A new style is created if the workbook does not contain a matching style.</p>
- *
- * <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
+ *
+ * <p>Modifies the cell style of {@code cell} without affecting other cells that use the
* same style.</p>
- *
+ *
* <p>If setting more than one cell style property on a cell, use
* {@link #setCellStyleProperties(Cell, Map)},
* which is faster and does not add unnecessary intermediate CellStyles to the workbook.</p>
- *
+ *
* @param cell The cell that is to be changed.
* @param propertyName The name of the property that is to be changed.
* @param propertyValue The value of the property that is to be changed.
/**
* Returns a map containing the format properties of the given cell style.
- * The returned map is not tied to <code>style</code>, so subsequent changes
- * to <code>style</code> will not modify the map, and changes to the returned
+ * The returned map is not tied to {@code style}, so subsequent changes
+ * to {@code style} will not modify the map, and changes to the returned
* map will not modify the cell style. The returned map is mutable.
*
* @param style cell style
put(properties, WRAP_TEXT, style.getWrapText());
return properties;
}
-
+
/**
* Copies the entries in src to dest, using the preferential data type
* so that maps can be compared for equality
}
return 0;
}
-
+
/**
* Utility method that returns the named BorderStyle value from the given map.
*
// @deprecated 3.15 beta 2. getBorderStyle will only work on BorderStyle enums instead of codes in the future.
else if (value instanceof Short) {
LOGGER.atWarn().log("Deprecation warning: CellUtil properties map uses Short values for {}. Should use BorderStyle enums instead.", name);
- short code = ((Short) value).shortValue();
+ short code = (Short) value;
border = BorderStyle.valueOf(code);
}
else if (value == null) {
}
return border;
}
-
+
/**
* Utility method that returns the named FillPatternType value from the given map.
*
// @deprecated 3.15 beta 2. getFillPattern will only work on FillPatternType enums instead of codes in the future.
else if (value instanceof Short) {
LOGGER.atWarn().log("Deprecation warning: CellUtil properties map uses Short values for {}. Should use FillPatternType enums instead.", name);
- short code = ((Short) value).shortValue();
+ short code = (Short) value;
pattern = FillPatternType.forInt(code);
}
else if (value == null) {
}
return pattern;
}
-
+
/**
* Utility method that returns the named HorizontalAlignment value from the given map.
*
// @deprecated 3.15 beta 2. getHorizontalAlignment will only work on HorizontalAlignment enums instead of codes in the future.
else if (value instanceof Short) {
LOGGER.atWarn().log("Deprecation warning: CellUtil properties map used a Short value for {}. Should use HorizontalAlignment enums instead.", name);
- short code = ((Short) value).shortValue();
+ short code = (Short) value;
align = HorizontalAlignment.forInt(code);
}
else if (value == null) {
}
return align;
}
-
+
/**
* Utility method that returns the named VerticalAlignment value from the given map.
*
// @deprecated 3.15 beta 2. getVerticalAlignment will only work on VerticalAlignment enums instead of codes in the future.
else if (value instanceof Short) {
LOGGER.atWarn().log("Deprecation warning: CellUtil properties map used a Short value for {}. Should use VerticalAlignment enums instead.", name);
- short code = ((Short) value).shortValue();
+ short code = (Short) value;
align = VerticalAlignment.forInt(code);
}
else if (value == null) {
Object value = properties.get(name);
//noinspection SimplifiableIfStatement
if (value instanceof Boolean) {
- return ((Boolean) value).booleanValue();
+ return (Boolean) value;
}
return false;
}
* <br>
* where:<br>
*
- * <tt>a</tt> = <i>significand</i><br>
- * <tt>b</tt> = <i>binaryExponent</i> - bitLength(significand) + 1<br>
- *
- * @author Josh Micich
+ * {@code a} = <i>significand</i><br>
+ * {@code b} = <i>binaryExponent</i> - bitLength(significand) + 1<br>
*/
final class ExpandedDouble {
private static final BigInteger BI_FRAC_MASK = BigInteger.valueOf(FRAC_MASK);
BigInteger frac = BigInteger.valueOf(rawBits).and(BI_FRAC_MASK);
int expAdj = 64 - frac.bitLength();
_significand = frac.shiftLeft(expAdj);
- _binaryExponent = (biasedExp & 0x07FF) - 1023 - expAdj;
+ _binaryExponent = -1023 - expAdj;
} else {
_significand = getFrac(rawBits);
_binaryExponent = (biasedExp & 0x07FF) - 1023;
/**
* For working with the internals of IEEE 754-2008 'binary64' (double precision) floating point numbers
- *
- * @author Josh Micich
*/
final class IEEEDouble {
private static final long EXPONENT_MASK = 0x7FF0000000000000L;
* <br>
* where:<br>
*
- * <tt>significand</tt> = wholePart + fractionalPart / 2<sup>24</sup><br>
- *
- * @author Josh Micich
+ * {@code significand} = wholePart + fractionalPart / 2<sup>24</sup><br>
*/
final class NormalisedDecimal {
/**
* The resulting transformed object is easily converted to a 64 bit IEEE double:
* <ul>
* <li>bits 2-53 of the {@link #composeFrac()} become the 52 bit 'fraction'.</li>
- * <li>{@link #getBinaryExponent()} is biased by 1023 to give the 'exponent'.</li>
+ * <li>{@link #getDecimalExponent()} is biased by 1023 to give the 'exponent'.</li>
* </ul>
* The sign bit must be obtained from somewhere else.
- * @return a new {@link NormalisedDecimal} normalised to base 2 representation.
+ * @return a new NormalisedDecimal normalised to base 2 representation.
*/
public ExpandedDouble normaliseBaseTwo() {
MutableFPNumber cc = new MutableFPNumber(composeFrac(), 39);
/**
* Excel compares numbers using different rules to those of java, so
* {@link Double#compare(double, double)} won't do.
- *
- *
- * @author Josh Micich
*/
public final class NumberComparer {
* decimal digits of precision and a decimal exponent, before completing the comparison.
* <p>
* In Excel formula evaluation, expressions like "(0.06-0.01)=0.05" evaluate to "TRUE" even
- * though the equivalent java expression is <code>false</code>. In examples like this,
+ * though the equivalent java expression is {@code false}. In examples like this,
* Excel achieves the effect by having additional logic for comparison operations.
* <p>
- * <p>
* Note - Excel also gives special treatment to expressions like "0.06-0.01-0.05" which
* evaluates to "0" (in java, rounding anomalies give a result of 6.9E-18). The special
* behaviour here is for different reasons to the example above: If the last operator in a
* This rule (for rounding the result of a final addition or subtraction), has not been
* implemented in POI (as of Jul-2009).
*
- * @return <code>negative, 0, or positive</code> according to the standard Excel comparison
- * of values <tt>a</tt> and <tt>b</tt>.
+ * @return {@code negative, 0, or positive} according to the standard Excel comparison
+ * of values {@code a} and {@code b}.
*/
public static int compare(double a, double b) {
long rawBitsA = Double.doubleToLongBits(a);
* Usually any normal number is greater (in magnitude) than any subnormal number.
* However there are some anomalous cases around the threshold where Excel produces screwy results
* @param isNegative both values are either negative or positive. This parameter affects the sign of the comparison result
- * @return usually <code>isNegative ? -1 : +1</code>
+ * @return usually {@code isNegative ? -1 : +1}
*/
private static int compareAcrossSubnormalThreshold(long normalRawBitsA, long subnormalRawBitsB, boolean isNegative) {
long fracB = subnormalRawBitsB & FRAC_MASK;
/**
* Excel converts numbers to text with different rules to those of java, so
- * <code>Double.toString(value)</tt> won't do.
+ * {@code Double.toString(value)} won't do.
* <ul>
* <li>No more than 15 significant figures are output (java does 18).</li>
* <li>The sign char for the exponent is included even if positive</li>
- * <li>Special values (<tt>NaN</tt> and <tt>Infinity</tt>) get rendered like the ordinary
+ * <li>Special values ({@code NaN} and {@code Infinity}) get rendered like the ordinary
* number that the bit pattern represents.</li>
* <li>Denormalised values (between ±2<sup>-1074</sup> and ±2<sup>-1022</sup>
- * are displayed as "0"</sup>
+ * are displayed as "0"</li>
* </ul>
* IEEE 64-bit Double Rendering Comparison
*
* Excel's text to number conversion is not a true <i>inverse</i> of this operation. The
* allowable ranges are different. Some numbers that don't correctly convert to text actually
* <b>do</b> get handled properly when used in arithmetic evaluations.
- *
- * @author Josh Micich
*/
public final class NumberToTextConverter {
}
/**
- * Converts the supplied <tt>value</tt> to the text representation that Excel would give if
+ * Converts the supplied {@code value} to the text representation that Excel would give if
* the value were to appear in an unformatted cell, or as a literal number in a formula.<br>
- * Note - the results from this method differ slightly from those of <tt>Double.toString()</tt>
+ * Note - the results from this method differ slightly from those of {@code Double.toString()}
* In some special cases Excel behaves quite differently. This function attempts to reproduce
* those results.
*/
return new SSCellRange<>(firstRow, firstColumn, height, width, flattenedArray);
}
- public int getHeight() {
+ @Override
+ public int getHeight() {
return _height;
}
+ @Override
public int getWidth() {
return _width;
}
+ @Override
public int size() {
return _height*_width;
}
+ @Override
public String getReferenceText() {
CellRangeAddress cra = new CellRangeAddress(_firstRow, _firstRow+_height-1, _firstColumn, _firstColumn+_width-1);
return cra.formatAsString();
}
+ @Override
public K getTopLeftCell() {
return _flattenedArray[0];
}
+ @Override
public K getCell(int relativeRowIndex, int relativeColumnIndex) {
if (relativeRowIndex < 0 || relativeRowIndex >= _height) {
throw new ArrayIndexOutOfBoundsException("Specified row " + relativeRowIndex
int flatIndex = _width * relativeRowIndex + relativeColumnIndex;
return _flattenedArray[flatIndex];
}
+ @Override
public K[] getFlattenedCells() {
return _flattenedArray.clone();
}
+ @Override
public K[][] getCells() {
Class<?> itemCls = _flattenedArray.getClass();
@SuppressWarnings("unchecked")
return result;
}
+ @Override
public Iterator<K> iterator() {
return Stream.of(_flattenedArray).iterator();
}
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* Class {@code SheetBuilder} provides an easy way of building workbook sheets
* from 2D array of Objects. It can be used in test cases to improve code
* readability or in Swing applications with tables.
- *
- * @author Roman Kashitsyn
*/
public class SheetBuilder {
/**
* Helper methods for when working with Usermodel sheets
- *
- * @author Yegor Kozlov
*/
public class SheetUtil {
* Helper methods for when working with Usermodel Workbooks
*/
public class WorkbookUtil {
-
+
/**
* Creates a valid sheet name, which is conform to the rules.
- * In any case, the result safely can be used for
+ * In any case, the result safely can be used for
* {@link org.apache.poi.ss.usermodel.Workbook#setSheetName(int, String)}.
* <br>
* Rules:
* <li>Sheet names must not begin or end with ' (apostrophe)</li>
* </ul>
* Invalid characters are replaced by one space character ' '.
- *
+ *
* @param nameProposal can be any string, will be truncated if necessary,
* allowed to be null
- * @return a valid string, "empty" if to short, "null" if null
+ * @return a valid string, "empty" if to short, "null" if null
*/
public static String createSafeSheetName(final String nameProposal) {
return createSafeSheetName(nameProposal, ' ');
* Validates sheet name.
*
* <p>
- * The character count <tt>MUST</tt> be greater than or equal to 1 and less than or equal to 31.
+ * The character count {@code MUST} be greater than or equal to 1 and less than or equal to 31.
* The string MUST NOT contain the any of the following characters:
* <ul>
* <li> 0x0000 </li>
* <li> closing square bracket (]) </li>
* </ul>
* The string MUST NOT begin or end with the single quote (') character.
- * </p>
*
* @param sheetName the name to validate
* @throws IllegalArgumentException if validation fails
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.apache.poi.ss.usermodel.Cell;
/**
- * Represents callback for CellWalk traverse method.
- * @author Roman Kashitsyn
+ * Represents callback for CellWalk traverse method.
*/
public interface CellHandler {
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.apache.poi.ss.util.cellwalk;
-/**
- * @author Roman Kashitsyn
- */
public interface CellWalkContext {
/**
/**
* Manage operations dealing with bit-mapped fields.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @author Andrew C. Oliver (acoliver at apache dot org)
*/
@Internal(since="POI 3.15 beta 3")
public class BitField
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
/**
* representation of a byte (8-bit) field at a fixed location within a
* byte array
- *
- * @author Marc Johnson (mjohnson at apache dot org
*/
public class ByteField
* the header has been written. The client code can call {@link #createDelayedOutput(int)}
* to reserve two bytes of the output for the 'ushort size' header field. The delayed output can
* be written at any stage.
- *
- * @author Josh Micich
*/
public interface DelayableLittleEndianOutput extends LittleEndianOutput {
/**
- * Creates an output stream intended for outputting a sequence of <tt>size</tt> bytes.
+ * Creates an output stream intended for outputting a sequence of {@code size} bytes.
*/
LittleEndianOutput createDelayedOutput(int size);
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
/**
* behavior of a field at a fixed location within a byte array
- *
- * @author Marc Johnson (mjohnson at apache dot org
*/
public interface FixedField
}
/**
- * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
+ * Helper method, just calls {@code readFully(in, b, 0, b.length)}
*
* @param in the stream from which the data is read.
* @param b the buffer into which the data is read.
* <p>Same as the normal {@link InputStream#read(byte[], int, int)}, but tries to ensure
* that the entire len number of bytes is read.</p>
*
- * <p>If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
+ * <p>If the end of file is reached before any bytes are read, returns {@code -1}. If
* the end of the file is reached after some bytes are read, returns the
- * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
- * bytes have been read, will return <tt>len</tt> bytes.</p>
+ * number of bytes read. If the end of the file isn't reached before {@code len}
+ * bytes have been read, will return {@code len} bytes.</p>
*
* @param in the stream from which the data is read.
* @param b the buffer into which the data is read.
- * @param off the start offset in array <tt>b</tt> at which the data is written.
+ * @param off the start offset in array {@code b} at which the data is written.
* @param len the maximum number of bytes to read.
*
* @return the number of bytes read or -1 if no bytes were read
}
/**
- * Same as the normal <tt>channel.read(b)</tt>, but tries to ensure
+ * Same as the normal {@code channel.read(b)}, but tries to ensure
* that the buffer is filled completely if possible, i.e. b.remaining()
* returns 0.
* <p>
/**
* Quietly (no exceptions) close Closable resource. In case of error it will
- * be printed to {@link IOUtils} class logger.
+ * be printed to IOUtils class logger.
*
* @param closeable
* resource to close
* than delegating to {@link InputStream#skip(long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of bytes are skipped.
- * </p>
* <p>
* This mimics POI's {@link #readFully(InputStream, byte[])}.
- * If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
+ * If the end of file is reached before any bytes are read, returns {@code -1}. If
* the end of the file is reached after some bytes are read, returns the
- * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
- * bytes have been read, will return <tt>len</tt> bytes.</p>
+ * number of bytes read. If the end of the file isn't reached before {@code len}
+ * bytes have been read, will return {@code len} bytes.
- * </p>
* <p>
* Copied nearly verbatim from commons-io 41a3e9c
- * </p>
*
* @param input byte stream to skip
* @param toSkip number of bytes to skip.
* remove(int index)
* <li> subList is not supported
* </ul>
- *
- * @author Marc Johnson
*/
public class IntList
{
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
/**
* representation of an integer (32-bit) field at a fixed location
* within a byte array
- *
- * @author Marc Johnson (mjohnson at apache dot org
*/
public class IntegerField
* not subject to the POI project policy of deprecating an element for 2 major
* releases before removing.
*
- * @author Yegor Kozlov
* @since POI-3.6
*/
@Documented
/**
* Exception to handle buffer underruns
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
public static final class BufferUnderrunException extends IOException {
/**
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
/**
* a repository for constants shared by classes within this package
- *
- * @author Marc Johnson
- * @author Andrew C. Oliver (acoliver at apache dot org)
*/
public interface LittleEndianConsts {
==================================================================== */
package org.apache.poi.util;
-/**
- *
- * @author Josh Micich
- */
+
public interface LittleEndianOutput {
void writeByte(int v);
void writeShort(int v);
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
/**
* representation of a long (16-bit) field at a fixed location within
* a byte array
- *
- * @author Marc Johnson (mjohnson at apache dot org
*/
public class LongField
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
/**
* representation of a short (16-bit) field at a fixed location within
* a byte array
- *
- * @author Marc Johnson (mjohnson at apache dot org
*/
public class ShortField
* byte array. it is assumed that string[ offset ] and string[ offset +
* 1 ] contain the first 16-bit unicode character
* @param len the length of the final string
- * @return the converted string, never <code>null</code>.
+ * @return the converted string, never {@code null}.
* @throws ArrayIndexOutOfBoundsException if offset is out of bounds for
* the byte array (i.e., is negative or is greater than or equal to
* string.length)
* { 0x16, 0x00 } -0x16
*
* @param string the byte array to be converted
- * @return the converted string, never <code>null</code>
+ * @return the converted string, never {@code null}
*/
public static String getFromUnicodeLE(byte[] string) {
if (string.length == 0) {
}
/**
- * InputStream <tt>in</tt> is expected to contain:
+ * InputStream {@code in} is expected to contain:
* <ol>
* <li>ushort nChars</li>
* <li>byte is16BitFlag</li>
}
/**
- * InputStream <tt>in</tt> is expected to contain:
+ * InputStream {@code in} is expected to contain:
* <ol>
* <li>byte is16BitFlag</li>
* <li>byte[]/char[] characterData</li>
}
/**
- * OutputStream <tt>out</tt> will get:
+ * OutputStream {@code out} will get:
* <ol>
* <li>ushort nChars</li>
* <li>byte is16BitFlag</li>
}
/**
- * OutputStream <tt>out</tt> will get:
+ * OutputStream {@code out} will get:
* <ol>
* <li>byte is16BitFlag</li>
* <li>byte[]/char[] characterData</li>
* byte array. it is assumed that string[ offset ] and string[ offset +
* 1 ] contain the first 16-bit unicode character
* @param len the max. length of the final string
- * @return the converted string, never <code>null</code>.
+ * @return the converted string, never {@code null}.
* @throws ArrayIndexOutOfBoundsException if offset is out of bounds for
* the byte array (i.e., is negative or is greater than or equal to
* string.length)
private static POIDataSamples _instXmlDSign;
private File _resolvedDataDir;
- /** <code>true</code> if standard system propery is not set,
+ /** {@code true} if standard system propery is not set,
* but the data is available on the test runtime classpath */
private boolean _sampleDataIsAvaliableOnClassPath;
private final String _moduleDir;
* Opens a sample file from the test data directory
*
* @param sampleFileName the file to open
- * @return an open <tt>InputStream</tt> for the specified sample file
+ * @return an open {@code InputStream} for the specified sample file
*/
public InputStream openResourceAsStream(String sampleFileName) {
* Opens a test sample file from the 'data' sub-package of this class's package.
*
* @param sampleFileName the file to open
- * @return <code>null</code> if the sample file is not deployed on the classpath.
+ * @return {@code null} if the sample file is not deployed on the classpath.
*/
private InputStream openClasspathResource(String sampleFileName) {
return getClass().getResourceAsStream("/" + _moduleDir + "/" + sampleFileName);
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
-/**
- * @author Yegor Kozlov
- */
public final class HSSFITestDataProvider implements ITestDataProvider {
public static final HSSFITestDataProvider instance = new HSSFITestDataProvider();
private HSSFITestDataProvider(){
// enforce singleton
}
-
+
@Override
public HSSFWorkbook openSampleWorkbook(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
-
+
public InputStream openWorkbookStream(String sampleFileName) {
return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
}
-
+
@Override
public HSSFWorkbook writeOutAndReadBack(Workbook original) {
if(!(original instanceof HSSFWorkbook)) {
}
return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)original);
}
-
+
@Override
public HSSFWorkbook createWorkbook(){
return new HSSFWorkbook();
}
-
+
//************ SXSSF-specific methods ***************//
@Override
public HSSFWorkbook createWorkbook(int rowAccessWindowSize) {
return createWorkbook();
}
-
+
@Override
public void trackAllColumnsForAutosizing(Sheet sheet) {}
//************ End SXSSF-specific methods ***************//
-
+
@Override
public FormulaEvaluator createFormulaEvaluator(Workbook wb) {
return new HSSFFormulaEvaluator((HSSFWorkbook) wb);
public byte[] getTestDataFileContent(String fileName) {
return POIDataSamples.getSpreadSheetInstance().readFile(fileName);
}
-
+
@Override
public SpreadsheetVersion getSpreadsheetVersion(){
return SpreadsheetVersion.EXCEL97;
}
-
+
@Override
public String getStandardFileNameExtension() {
return "xls";
/**
* Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder.
- *
- * @author Josh Micich
*/
public final class HSSFTestDataSamples {
}
}
/**
- * Writes a spreadsheet to a <tt>ByteArrayOutputStream</tt> and reads it back
- * from a <tt>ByteArrayInputStream</tt>.<p>
+ * Writes a spreadsheet to a {@code ByteArrayOutputStream} and reads it back
+ * from a {@code ByteArrayInputStream}.<p>
* Useful for verifying that the serialisation round trip
*/
public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
import org.junit.jupiter.api.Test;
/**
- * Tests <tt>FormulaParser</tt> specifically with respect to IF() functions
+ * Tests {@code FormulaParser} specifically with respect to IF() functions
*/
final class TestFormulaParserIf {
private static Ptg[] parseFormula(String formula) {
import org.junit.jupiter.api.Test;
/**
- * Tests specific formula examples in <tt>OperandClassTransformer</tt>.
+ * Tests specific formula examples in {@code OperandClassTransformer}.
*/
final class TestOperandClassTransformer {
}
/**
- * In the example: <code>INDEX(PI(),1)</code>, Excel encodes PI() as 'array'. It is not clear
+ * In the example: {@code INDEX(PI(),1)}, Excel encodes PI() as 'array'. It is not clear
* what rule justifies this. POI currently encodes it as 'value' which Excel(2007) seems to
* tolerate. Changing the metadata for INDEX to have first parameter as 'array' class breaks
* other formulas involving INDEX. It seems like a special case needs to be made. Perhaps an
/**
* Tests 'operand class' transformation performed by
- * <tt>OperandClassTransformer</tt> by comparing its results with those
+ * {@code OperandClassTransformer} by comparing its results with those
* directly produced by Excel (in a sample spreadsheet).
*/
final class TestRVA {
/**
* Tests for {@link RowBlocksReader}
- *
- * @author Josh Micich
*/
final class TestRowBlocksReader {
@Test
/**
* Prior to bug 45066, POI would get the estimated sheet size wrong
- * when an <tt>UncalcedRecord</tt> was present.<p>
+ * when an {@code UncalcedRecord} was present.
*/
@Test
void testUncalcSize_bug45066() {
}
/**
- * Prior to bug 45145 <tt>RowRecordsAggregate</tt> and <tt>ValueRecordsAggregate</tt> could
+ * Prior to bug 45145 {@code RowRecordsAggregate} and {@code ValueRecordsAggregate} could
* sometimes occur in reverse order. This test reproduces one of those situations and makes
* sure that RRA comes before VRA.<br>
*
import org.junit.jupiter.api.Test;
/**
- * Tests for <tt>FeatRecord</tt>
+ * Tests for {@code FeatRecord}
*/
final class TestFeatRecord {
@Test
import org.junit.jupiter.api.Test;
/**
- * Tests for <tt>LabelRecord</tt>
+ * Tests for {@code LabelRecord}
*/
final class TestLabelRecord {
/**
* Tests for {@link RecordFactoryInputStream}
- *
- * @author Josh Micich
*/
final class TestRecordFactoryInputStream {
/**
/**
* Exercise the SSTDeserializer class.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
final class TestSSTDeserializer {
private static final int FAKE_SID = -5555;
};
/**
- * The method <tt>SharedFormulaRecord.convertSharedFormulas()</tt> converts formulas from
+ * The method {@code SharedFormulaRecord.convertSharedFormulas()} converts formulas from
* 'shared formula' to 'single cell formula' format. It is important that token operand
* classes are preserved during this transformation, because Excel may not tolerate the
* incorrect encoding. The formula here is one such example (Excel displays #VALUE!).
/**
* Tests that serialization and deserialization of the TextObjectRecord .
* Test data taken directly from a real Excel file.
- *
- * @author Yegor Kozlov
*/
final class TestTextObjectRecord {
* A Record Input Stream derivative that makes access to byte arrays used in the
* test cases work a bit easier.
* <p> Creates the stream and moves to the first record.
- *
- * @author Jason Height (jheight at apache.org)
*/
public final class TestcaseRecordInputStream {
return create(mergeDataAndSid(sid, data.length, data));
}
/**
- * First 4 bytes of <tt>data</tt> are assumed to be record identifier and length. The supplied
- * <tt>data</tt> can contain multiple records (sequentially encoded in the same way)
+ * First 4 bytes of {@code data} are assumed to be record identifier and length. The supplied
+ * {@code data} can contain multiple records (sequentially encoded in the same way)
*/
public static RecordInputStream create(byte[] data) {
InputStream is = new ByteArrayInputStream(data);
}
/**
- * Sometimes the 'shared formula' flag (<tt>FormulaRecord.isSharedFormula()</tt>) is set when
+ * Sometimes the 'shared formula' flag ({@code FormulaRecord.isSharedFormula()}) is set when
* there is no corresponding SharedFormulaRecord available. SharedFormulaRecord definitions do
* not span multiple sheets. They are are only defined within a sheet, and thus they do not
* have a sheet index field (only row and column range fields).<br>
* So it is important that the code which locates the SharedFormulaRecord for each
- * FormulaRecord does not allow matches across sheets.</br>
+ * FormulaRecord does not allow matches across sheets.<p>
*
- * Prior to bugzilla 44449 (Feb 2008), POI <tt>ValueRecordsAggregate.construct(int, List)</tt>
- * allowed <tt>SharedFormulaRecord</tt>s to be erroneously used across sheets. That incorrect
+ * Prior to bugzilla 44449 (Feb 2008), POI {@code ValueRecordsAggregate.construct(int, List)}
+ * allowed {@code SharedFormulaRecord}s to be erroneously used across sheets. That incorrect
* behaviour is shown by this test.<p>
*
* <b>Notes on how to produce the test spreadsheet</b>:</p>
* <li>Four rows on Sheet1 "5" through "8" were deleted ('delete rows' alt-E D, not 'clear' Del).</li>
* <li>The spreadsheet was saved as AbnormalSharedFormulaFlag.xls.</li>
* </ol>
- * Prior to the row delete action the spreadsheet has two <tt>SharedFormulaRecord</tt>s. One
+ * Prior to the row delete action the spreadsheet has two {@code SharedFormulaRecord}s. One
* for each sheet. To expose the bug, the shared formulas have been made to overlap.<br>
* The row delete action (as described here) seems to to delete the
- * <tt>SharedFormulaRecord</tt> from Sheet1 (but not clear the 'shared formula' flags.<br>
+ * {@code SharedFormulaRecord} from Sheet1 (but not clear the 'shared formula' flags.<br>
* There are other variations on this theme to create the same effect.
*
*/
biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell,
};
- /** cross-reference of <tt>contains()</tt> operations for sampleRanges against itself */
+ /** cross-reference of {@code contains()} operations for sampleRanges against itself */
private static final boolean [][] containsExpectedResults =
{
// biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell
/**
* Tests that {@link UnicodeString} record size calculates correctly. The record size
* is used when serializing {@link SSTRecord}s.
- *
- * @author Jason Height (jheight at apache.org)
*/
final class TestUnicodeString {
private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE;
}
/**
- * Note - a value of zero for <tt>amountUsedInCurrentRecord</tt> would only ever occur just
+ * Note - a value of zero for {@code amountUsedInCurrentRecord} would only ever occur just
* after a {@link ContinueRecord} had been started. In the initial {@link SSTRecord} this
* value starts at 8 (for the first {@link UnicodeString} written). In general, it can be
* any value between 0 and {@link #MAX_DATA_SIZE}
}
/**
- * @param is16Bit if <code>true</code> the created string will have characters > 0x00FF
+ * @param is16Bit if {@code true} the created string will have characters > 0x00FF
* @return a string of the specified number of characters
*/
private static UnicodeString makeUnicodeString(int numChars, boolean is16Bit) {
import org.apache.poi.ss.formula.ptg.Ptg;
/**
- * Test utility class to get <tt>Ptg</tt> arrays out of formula cells
- *
- * @author Josh Micich
+ * Test utility class to get {@code Ptg} arrays out of formula cells
*/
public final class FormulaExtractor {
private FormulaExtractor() {
// no instances of this class
}
-
+
public static Ptg[] getPtgs(HSSFCell cell) {
CellValueRecordInterface vr = cell.getCellValueRecord();
if (!(vr instanceof FormulaRecordAggregate)) {
import org.apache.poi.ss.formula.EvaluationCell;
/**
- * Raises visibility of some internal functionality for test purposes
- *
- * @author Josh Micich
+ * Raises visibility of some internal functionality for test purposes
*/
public final class HSSFEvaluationTestHelper {
* any significant detail. Normally this task would be simple except for the presence of artifacts
* in the file that change every time it is generated. Usually these volatile artifacts are
* time-stamps, user names, or other machine dependent parameters.
- *
- * @author Josh Micich
*/
public final class StreamUtility {
* Test the ability to clone a sheet.
* If adding new records that belong to a sheet (as opposed to a book)
* add that record to the sheet in the testCloneSheetBasic method.
- * @author avik
*/
final class TestCloneSheet extends BaseTestCloneSheet {
public TestCloneSheet() {
/**
* Class for testing Excel's data validation mechanism
- *
- * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro )
*/
final class TestDataValidation extends BaseTestDataValidation {
/**
* Tests TestHSSFCellComment.
- *
- * @author Yegor Kozlov
*/
final class TestHSSFComment extends BaseTestCellComment {
/**
* Tests HSSFHyperlink.
- *
- * @author Yegor Kozlov
*/
final class TestHSSFHyperlink extends BaseTestHyperlink {
/**
* Test HSSFRow is okay.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
final class TestHSSFRow extends BaseTestRow {
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows;
-/**
- * @author Yegor Kozlov
- */
final class TestHSSFSheetShiftRows extends BaseTestSheetShiftRows {
public TestHSSFSheetShiftRows() {
import org.apache.poi.util.LocaleUtil;
import org.junit.jupiter.api.Test;
-/**
- * @author Glen Stampoultzis (glens at apache.org)
- */
final class TestReadWriteChart {
/**
/**
* A Test case for a test utility class.<br>
* Okay, this may seem strange but I need to test my test logic.
- *
- * @author Glen Stampoultzis (glens at apache.org)
*/
final class TestSanityChecker {
private static final Record INTERFACEHDR = new InterfaceHdrRecord(InterfaceHdrRecord.CODEPAGE);
import org.apache.poi.hssf.record.TextObjectRecord;
import org.junit.jupiter.api.Test;
-/**
- * @author Evgeniy Berlog
- * @date 25.06.12
- */
class TestText {
@Test
import org.junit.jupiter.api.Test;
/**
- * @author aviks
- *
* This testcase contains tests for bugs that are yet to be fixed. Therefore,
* the standard ant test target does not run these tests. Run this testcase with
* the single-test target. The names of the tests usually correspond to the
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.eventfilesystem;
/**
* Class Listener
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
-
-class Listener
- implements POIFSReaderListener
-{
+class Listener implements POIFSReaderListener {
/**
* Process a POIFSReaderEvent that this listener had registered
/**
* Class to test POIFSReaderRegistry functionality
- *
- * @author Marc Johnson
*/
final class TestPOIFSReaderRegistry {
private final POIFSReaderListener[] listeners =
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
/**
* Test (Proof of concept) program that employs the
* POIFSReaderListener and POIFSWriterListener interfaces
- *
- * @author Marc Johnson (mjohnson at apache dot org)
*/
-
-public final class ReaderWriter
- implements POIFSReaderListener, POIFSWriterListener
-{
+public final class ReaderWriter implements POIFSReaderListener, POIFSWriterListener {
private final DirectoryEntry root;
// keys are DocumentDescriptors, values are byte[]s
/**
* Class to test RootProperty functionality
- *
- * @author Marc Johnson
*/
final class TestRootProperty {
private RootProperty _property;
/**
* Date: 10/24/11
- *
- * @author Yegor Kozlov
*/
class TestFormulaParser {
@Test
* @return an instance of Workbook
*/
Workbook createWorkbook();
-
-
+
+
//************ SXSSF-specific methods ***************//
/**
* Provides way of creating a SXSSFWorkbook with a specific row access window size.
* @return an instance of Workbook
*/
Workbook createWorkbook(int rowAccessWindowSize);
-
+
/**
* Only matters for SXSSF - enables tracking of the column
* widths so that autosizing can work. No-op on others.
/**
* Creates the corresponding {@link FormulaEvaluator} for the
- * type of Workbook handled by this Provider.
+ * type of Workbook handled by this Provider.
*
* @param wb The workbook to base the formula evaluator on.
- * @return A new instance of a matching type of formula evaluator.
+ * @return A new instance of a matching type of formula evaluator.
*/
FormulaEvaluator createFormulaEvaluator(Workbook wb);
/**
* Opens a sample file from the standard HSSF test data directory
*
- * @return an open <tt>InputStream</tt> for the specified sample file
+ * @return an open {@code InputStream} for the specified sample file
*/
byte[] getTestDataFileContent(String fileName);
* Tests should extend this class if they need to track the internal working of the {@link WorkbookEvaluator}.<br>
*
* Default method implementations all do nothing
- *
- * @author Josh Micich
*/
public abstract class EvaluationListener implements IEvaluationListener {
@Override
/**
* Tests for {@link SheetNameFormatter}
- *
- * @author Josh Micich
*/
final class TestSheetNameFormatter {
/**
/**
* Tests {@link WorkbookEvaluator}.
- *
- * @author Josh Micich
*/
class TestWorkbookEvaluator {
/**
* Allows tests to execute {@link WorkbookEvaluator}s and track the internal workings.
- *
- * @author Josh Micich
*/
public final class WorkbookEvaluatorTestHelper {
/**
* Collects eval instances for easy access by tests in this package
- *
- * @author Josh Micich
*/
final class EvalInstances {
private EvalInstances() {
import org.junit.jupiter.api.Test;
/**
- * Tests for <tt>AreaEval</tt>
+ * Tests for {@code AreaEval}
*/
final class TestAreaEval {
/**
* Tests formulas and operators as loaded from a test data spreadsheet.<p>
- * This class does not test implementors of <tt>Function</tt> and <tt>OperationEval</tt> in
- * isolation. Much of the evaluation engine (i.e. <tt>HSSFFormulaEvaluator</tt>, ...) gets
+ * This class does not test implementors of {@code Function} and {@code OperationEval} in
+ * isolation. Much of the evaluation engine (i.e. {@code HSSFFormulaEvaluator}, ...) gets
* exercised as well. Tests for bug fixes and specific/tricky behaviour can be found in the
- * corresponding test class (<tt>TestXxxx</tt>) of the target (<tt>Xxxx</tt>) implementor,
+ * corresponding test class ({@code TestXxxx}) of the target ({@code Xxxx}) implementor,
* where execution can be observed more easily.
*/
public final class TestFormulasFromSpreadsheet {
/**
* @param startRowIndex row index in the spreadsheet where the first function/operator is found
- * Typically pass <code>null</code> to test all functions
+ * Typically pass {@code null} to test all functions
*/
private static void processFunctionGroup(List<Arguments> data, int startRowIndex) {
for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) {
}
}
/**
- * @return <code>null</code> if cell is missing, empty or blank
+ * @return {@code null} if cell is missing, empty or blank
*/
private static String getTargetFunctionName(Row r) {
if(r == null) {
/**
* Tests HSSFFormulaEvaluator for its handling of cell formula circular references.
- *
- * @author Josh Micich
*/
final class TestHSSFCircularReferences extends BaseTestCircularReferences {
public TestHSSFCircularReferences() {
import org.junit.jupiter.api.Test;
/**
- * Tests for <tt>OperandResolver</tt>
+ * Tests for {@code OperandResolver}
*/
final class TestOperandResolver {
@Test
import static org.junit.jupiter.api.Assertions.assertTrue;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public abstract class BaseTestNumeric {
public static final double POS_ZERO = 1E-4;
import org.apache.poi.ss.util.AreaReference;
/**
- * Test helper class for creating mock <code>Eval</code> objects
- *
- * @author Josh Micich
+ * Test helper class for creating mock {@code Eval} objects
*/
public final class EvalFactory {
/**
* Tests for {@link Bin2Dec}
- *
- * @author cedric dot walter @ gmail dot com
*/
final class TestBin2Dec {
/**
* Tests for {@link Code}
- *
- * @author cedric dot walter @ gmail dot com
*/
class TestCode {
private static ValueEval invokeValue(String number1) {
/**
* Tests for {@link Complex}
- *
- * @author cedric dot walter @ gmail dot com
*/
class TestComplex {
private static ValueEval invokeValue(String real_num, String i_num, String suffix) {
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
-/**
- * @author Pavel Krupets (pkrupets at palmtreebusiness dot com)
- */
final class TestDate {
private HSSFCell cell11;
/**
* Tests for Excel function DATEVALUE()
- *
- * @author Milosz Rembisz
*/
final class TestDateValue {
}
/**
- * The <tt>method</tt> parameter only makes a difference when the second parameter
+ * The {@code method} parameter only makes a difference when the second parameter
* is the last day of the month that does <em>not</em> have 30 days.
*/
@Test
/**
* Tests for {@link Dec2Bin}
- *
- * @author cedric dot walter @ gmail dot com
*/
final class TestDec2Bin {
/**
* Tests for {@link Dec2Hex}
- *
- * @author cedric dot walter @ gmail dot com
*/
final class TestDec2Hex {
/**
* Tests for {@link org.apache.poi.ss.formula.functions.Delta}
- *
- * @author cedric dot walter @ gmail dot com
*/
final class TestDelta {
import org.junit.jupiter.api.Test;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
class TestFinanceLib extends BaseTestNumeric {
@Test
f = FinanceLib.fv(r, n, y, p, t);
x = -2;
assertDouble("fv ", x, f);
-
+
r = 0.12/12; n = 12; y = -1000; p = 0; t = false;
f = FinanceLib.fv(r, n, y, p, t);
x = 12682.50301319;
/**
* Testcase for the function FREQUENCY(data, bins)
- *
- * @author Yegor Kozlov
*/
class TestFrequency {
/**
* Tests for {@link Hex2Dec}
- *
- * @author cedric dot walter @ gmail dot com
*/
final class TestHex2Dec {
/**
* Confirms that the result is an area ref with the specified coordinates
- * @return <tt>ve</tt> cast to {@link AreaEval} if it is valid
+ * @return {@code ve} cast to {@link AreaEval} if it is valid
*/
private static AreaEval confirmAreaEval(String refText, ValueEval ve) {
CellRangeAddress cra = CellRangeAddress.valueOf(refText);
* Tests INDIRECT() as loaded from a test data spreadsheet.<p>
*
* Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class
- * (<tt>TestXxxx</tt>) of the target (<tt>Xxxx</tt>) implementor, where execution can be observed
+ * ({@code TestXxxx}) of the target ({@code Xxxx}) implementor, where execution can be observed
* more easily.
*/
final class TestIndirectFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet {
/**
* Test for Excel function INTERCEPT()
- *
- * @author Johan Karlsteen
*/
final class TestIntercept {
private static final Function INTERCEPT = new Intercept();
/**
* Tests for Excel function ISBLANK()
- *
- * @author Josh Micich
*/
final class TestIsBlank {
*
* Test cases for {@link TextFunction#LEFT} and {@link TextFunction#RIGHT}
*
- * @author Brendan Nolan
- *
*/
class TestLeftRight {
/**
* Tests for Excel function LEN()
- *
- * @author Josh Micich
*/
final class TestLen {
* functions have more complex test cases and test data setup.
*
* Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class
- * (<tt>TestXxxx</tt>) of the target (<tt>Xxxx</tt>) implementor, where execution can be observed
+ * ({@code TestXxxx}) of the target ({@code Xxxx}) implementor, where execution can be observed
* more easily.
*/
final class TestLookupFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet {
/**
- * Ensures that the match_type argument can be an <tt>AreaEval</tt>.<br>
+ * Ensures that the match_type argument can be an {@code AreaEval}.<br>
* Bugzilla 44421
*/
@Test
* Tests Match functions as loaded from a test data spreadsheet.<p>
*
* Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class
- * (<tt>TestXxxx</tt>) of the target (<tt>Xxxx</tt>) implementor, where execution can be observed
+ * ({@code TestXxxx}) of the target ({@code Xxxx}) implementor, where execution can be observed
* more easily.
*/
final class TestMatchFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet {
import org.junit.jupiter.api.Test;
-/**
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- *
- */
public class TestMathX extends BaseTestNumeric {
@Test
/**
* Tests for Excel function MID()
- *
- * @author Josh Micich
*/
final class TestMid {
/**
* Tests for {@link org.apache.poi.ss.formula.functions.Mirr}
*
- * @author Carlos Delgado (carlos dot del dot est at gmail dot com)
- * @author Cedric Walter (cedric dot walter at gmail dot com)
* @see org.apache.poi.ss.formula.functions.TestIrr
*/
final class TestMirr {
/**
* Tests for {@link org.apache.poi.ss.formula.functions.Oct2Dec}
- *
- * @author cedric dot walter @ gmail dot com
*/
final class TestOct2Dec {
/**
* Tests for OFFSET function implementation
- *
- * @author Josh Micich
*/
final class TestOffset {
/**
* Tests for Excel function POISSON(x,mean,cumulative)
- * @author Kalpesh Parmar
*/
class TestPoisson {
/**
* Tests for {@link Quotient}
- *
- * @author cedric dot walter @ gmail dot com
*/
class TestQuotient {
private static ValueEval invokeValue(String numerator, String denominator) {
/**
* Test cases for ROUND(), ROUNDUP(), ROUNDDOWN()
- *
- * @author Josh Micich
*/
final class TestRoundFuncs {
// github-43
/**
* Test for Excel function SLOPE()
- *
- * @author Johan Karlsteen
*/
final class TestSlope {
private static final Function SLOPE = new Slope();
/**
* Test cases for SUMPRODUCT()
- *
- * @author Josh Micich
*/
final class TestSumproduct {
/**
* Test cases for Excel function T()
- *
- * @author Josh Micich
*/
final class TestTFunc {
/**
* Tests for Excel function TRIM()
- *
- * @author Josh Micich
*/
final class TestTrim {
/**
* Test case for TRUNC()
- *
- * @author Stephen Wolke (smwolke at geistig.com)
*/
final class TestTrunc extends BaseTestNumeric {
private static final NumericFunction F = null;
/**
* Tests for Excel functions SUMX2MY2(), SUMX2PY2(), SUMXMY2()
- *
- * @author Josh Micich
*/
final class TestXYNumericFunction {
private static final Function SUM_SQUARES = new Sumx2py2();
import org.junit.jupiter.api.Test;
/**
- * Tests for <tt>ArrayPtg</tt>
+ * Tests for {@code ArrayPtg}
*/
final class TestArrayPtg {
final class TestExternalFunctionFormulas {
/**
- * tests <tt>NameXPtg.toFormulaString(Workbook)</tt> and logic in Workbook below that
+ * tests {@code NameXPtg.toFormulaString(Workbook)} and logic in Workbook below that
*/
@Test
void testReadFormulaContainingExternalFunction() throws Exception {
double NEW_QUANT = 7.0d;
double NEW_PART_COST = 15.3d;
/**
- * tests <tt>NameXPtg for external cell reference by name</tt> and logic in Workbook below that
+ * tests {@code NameXPtg for external cell reference by name} and logic in Workbook below that
*/
@Test
void testReadCalcSheet() {
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.jupiter.api.Test;
-/**
- * @author Josh Micich
- */
final class TestFuncVarPtg {
/**
* The first fix for bugzilla 44675 broke the encoding of SUM formulas (and probably others).
* The operand classes of the parameters to SUM() should be coerced to 'reference' not 'value'.
* In the case of SUM, Excel evaluates the formula to '#VALUE!' if a parameter operand class is
- * wrong. In other cases Excel seems to tolerate bad operand classes.</p>
- * This functionality is related to the setParameterRVA() methods of <tt>FormulaParser</tt>
+ * wrong. In other cases Excel seems to tolerate bad operand classes.<p>
+ *
+ * This functionality is related to the setParameterRVA() methods of {@code FormulaParser}
*/
@Test
void testOperandClass() {
/**
* Class for testing Excel's data validation mechanism
- *
- * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro )
*/
public abstract class BaseTestDataValidation {
private final ITestDataProvider _testDataProvider;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
-/**
- * @author Yegor Kozlov
- */
public abstract class BaseTestFont {
private final ITestDataProvider _testDataProvider;
import org.junit.jupiter.api.Test;
/**
- * Test diffrent types of Excel hyperlinks
- *
- * @author Yegor Kozlov
+ * Test different types of Excel hyperlinks
*/
public abstract class BaseTestHyperlink {
/**
* Common superclass for testing automatic sizing of sheet columns
- *
- * @author Yegor Kozlov
*/
public abstract class BaseTestSheetAutosizeColumn {
/**
* Tests row shifting capabilities.
- *
- * @author Shawn Laubach (slaubach at apache dot com)
- * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/
public abstract class BaseTestSheetShiftRows {
import org.apache.poi.hssf.HSSFITestDataProvider;
-/**
- * @author Yegor Kozlov
- */
final class TestHSSFBorderStyle extends BaseTestBorderStyle {
public TestHSSFBorderStyle() {
import org.junit.jupiter.api.Test;
-/**
- * @author Yegor Kozlov
- */
final class TestIndexedColors {
@Test
* (along with their expected results) that get encoded into rows of the spreadsheet.
* Each example is checked with a formula (in column I) that displays either "OK" or
* "ERROR" depending on whether actual results match those expected.
- *
- * @author Josh Micich
*/
public class NumberComparingSpreadsheetGenerator {
import java.util.List;
/**
- * Contains specific examples of <tt>double</tt> value pairs and their comparison result according to Excel.
- *
- * @author Josh Micich
+ * Contains specific examples of {@code double} value pairs and their comparison result according to Excel.
*/
final class NumberComparisonExamples {
addStepTransition(temp, 0x001000000000001BL);
addStepTransition(temp, 0x001000000000002FL);
- Collections.addAll(temp, new ComparisonExample[]{
- // negative, and exponents differ by more than 1
- ce(0xBF30000000000000L, 0xBE60000000000000L, -1),
-
- // negative zero *is* less than positive zero, but not easy to get out of calculations
- ce(0x0000000000000000L, 0x8000000000000000L, +1),
- // subnormal numbers compare without rounding for some reason
- ce(0x0000000000000000L, 0x0000000000000001L, -1),
- ce(0x0008000000000000L, 0x0008000000000001L, -1),
- ce(0x000FFFFFFFFFFFFFL, 0x000FFFFFFFFFFFFEL, +1),
- ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFCL, -1),
- ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFEL, -1),
-
- // across subnormal threshold (some mistakes when close)
- ce(0x000FFFFFFFFFFFFFL, 0x0010000000000000L, +1),
- ce(0x000FFFFFFFFFFFFBL, 0x0010000000000007L, +1),
- ce(0x000FFFFFFFFFFFFAL, 0x0010000000000007L, 0),
-
- // when a bit further apart - normal results
- ce(0x000FFFFFFFFFFFF9L, 0x0010000000000007L, -1),
- ce(0x000FFFFFFFFFFFFAL, 0x0010000000000008L, -1),
- ce(0x000FFFFFFFFFFFFBL, 0x0010000000000008L, -1),
- });
+ Collections.addAll(temp, // negative, and exponents differ by more than 1
+ ce(0xBF30000000000000L, 0xBE60000000000000L, -1),
+
+ // negative zero *is* less than positive zero, but not easy to get out of calculations
+ ce(0x0000000000000000L, 0x8000000000000000L, +1),
+ // subnormal numbers compare without rounding for some reason
+ ce(0x0000000000000000L, 0x0000000000000001L, -1),
+ ce(0x0008000000000000L, 0x0008000000000001L, -1),
+ ce(0x000FFFFFFFFFFFFFL, 0x000FFFFFFFFFFFFEL, +1),
+ ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFCL, -1),
+ ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFEL, -1),
+
+ // across subnormal threshold (some mistakes when close)
+ ce(0x000FFFFFFFFFFFFFL, 0x0010000000000000L, +1),
+ ce(0x000FFFFFFFFFFFFBL, 0x0010000000000007L, +1),
+ ce(0x000FFFFFFFFFFFFAL, 0x0010000000000007L, 0),
+
+ // when a bit further apart - normal results
+ ce(0x000FFFFFFFFFFFF9L, 0x0010000000000007L, -1),
+ ce(0x000FFFFFFFFFFFFAL, 0x0010000000000008L, -1),
+ ce(0x000FFFFFFFFFFFFBL, 0x0010000000000008L, -1));
ComparisonExample[] result = new ComparisonExample[temp.size()];
temp.toArray(result);
}
private static void addStepTransition(List<ComparisonExample> temp, long rawBits) {
- Collections.addAll(temp, new ComparisonExample[]{
- ce(rawBits - 1, rawBits + 0, 0),
- ce(rawBits + 0, rawBits + 1, -1),
- ce(rawBits + 1, rawBits + 2, 0),
- });
+ Collections.addAll(temp,
+ ce(rawBits - 1, rawBits + 0, 0),
+ ce(rawBits + 0, rawBits + 1, -1),
+ ce(rawBits + 1, rawBits + 2, 0));
}
/**
* Creates a spreadsheet that demonstrates Excel's rendering of various IEEE double values.
- *
- * @author Josh Micich
*/
public class NumberRenderingSpreadsheetGenerator {
}
/** 0x7ff8000000000000 encoded in little endian order */
private static final byte[] JAVA_NAN_BYTES = HexRead.readFromString("00 00 00 00 00 00 F8 7F");
-
+
private static void writeHeaderCell(HSSFRow row, int i, String text, HSSFCellStyle style) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(new HSSFRichTextString(text));
writeHeaderCell(row, 2, "JDK Double Rendering", style);
writeHeaderCell(row, 3, "Actual Rendering", style);
writeHeaderCell(row, 4, "Expected Rendering", style);
- writeHeaderCell(row, 5, "Match", style);
+ writeHeaderCell(row, 5, "Match", style);
writeHeaderCell(row, 6, "Java Metadata", style);
}
static void writeDataRow(HSSFSheet sheet, int rowIx, long rawLongBits, String expectedExcelRendering) {
double d = Double.longBitsToDouble(rawLongBits);
HSSFRow row = sheet.createRow(rowIx);
-
+
int rowNum = rowIx + 1;
String cel0ref = "A" + rowNum;
String rawBitsText = formatLongAsHex(rawLongBits);
String jmExpr = "'ec(" + rawBitsText + ", ''\" & C" + rowNum + " & \"'', ''\" & D" + rowNum + " & \"''),'";
-
+
// The 'Match' column will contain 'OK' if the metadata (from NumberToTextConversionExamples)
// matches Excel's rendering.
String matchExpr = "if(D" + rowNum + "=E" + rowNum + ", \"OK\", \"ERROR\")";
-
+
row.createCell(0).setCellValue(d);
row.createCell(1).setCellValue(new HSSFRichTextString(rawBitsText));
row.createCell(2).setCellValue(new HSSFRichTextString(Double.toString(d)));
// row.createCell(8).setCellFormula(cel0ref + " / 1.0001");
// }
}
-
+
private static String formatLongAsHex(long l) {
return HexDump.longToHex(l) + 'L';
}
public static void main(String[] args) {
writeJavaDoc();
-
+
HSSFWorkbook wb = new HSSFWorkbook();
SheetWriter sw = new SheetWriter(wb);
-
+
ExampleConversion[] exampleValues = NumberToTextConversionExamples.getExampleConversions();
for (ExampleConversion example : exampleValues) {
sw.addTestRow(example.getRawDoubleBits(), example.getExcelRendering());
}
-
+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
wb.write(baos);
}
byte[] fileContent = baos.toByteArray();
replaceNaNs(fileContent, sw.getReplacementNaNs());
-
-
+
+
File outputFile = new File("ExcelNumberRendering.xls");
-
+
try {
FileOutputStream os = new FileOutputStream(outputFile);
os.write(fileContent);
}
public static void writeJavaDoc() {
-
+
ExampleConversion[] exampleConversions = NumberToTextConversionExamples.getExampleConversions();
for (ExampleConversion ec : exampleConversions) {
- String line = " * <tr><td>"
+ String line = " * <tr><td>"
+ formatLongAsHex(ec.getRawDoubleBits())
- + "</td><td>" + Double.toString(ec.getDoubleValue())
+ + "</td><td>" + Double.toString(ec.getDoubleValue())
+ "</td><td>" + ec.getExcelRendering() + "</td></tr>";
-
+
System.out.println(line);
}
}
-
-
+
+
private static void replaceNaNs(byte[] fileContent, long[] replacementNaNs) {
int countFound = 0;
for(int i=0; i<fileContent.length; i++) {
if (countFound < replacementNaNs.length) {
throw new RuntimeException("wrong repl count");
}
-
+
}
private static void writeLong(byte[] bb, int i, long val) {
// String newVal = interpretLong(bb, i);
// System.out.println("changed offset " + i + " from " + oldVal + " to " + newVal);
// }
-
+
}
private static String interpretLong(byte[] fileContent, int offset) {
import java.util.Locale;
/**
- * Contains specific examples of <tt>double</tt> values and their rendering in Excel.
+ * Contains specific examples of {@code double} values and their rendering in Excel.
*/
final class NumberToTextConversionExamples {
/**
* Test for {@link AreaReference} handling of max rows.
- *
- * @author David North
*/
class TestAreaReference {
@Test
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.apache.poi.hssf.record.FormulaRecord;
+import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.ss.formula.constant.ConstantValueParser;
import org.apache.poi.ss.formula.ptg.NumberPtg;
import org.apache.poi.ss.util.NumberToTextConversionExamples.ExampleConversion;
*/
final class TestNumberToTextConverter {
/**
- * Confirms that <tt>ExcelNumberToTextConverter.toText(d)</tt> produces the right results.
- * As part of preparing this test class, the <tt>ExampleConversion</tt> instances should be set
+ * Confirms that {@code ExcelNumberToTextConverter.toText(d)} produces the right results.
+ * As part of preparing this test class, the {@code ExampleConversion} instances should be set
* up to contain the rendering as produced by Excel.
*/
@Test
* values as a plain number. That is the unusual functionality that this method is testing.<p>
*
* There are multiple encodings (bit patterns) for NaN, and CPUs and applications can convert
- * to a preferred NaN encoding (Java prefers <tt>0x7FF8000000000000L</tt>). Besides the
- * special encoding in {@link FormulaRecord.SpecialCachedValue}, it is not known how/whether
+ * to a preferred NaN encoding (Java prefers {@code 0x7FF8000000000000L}). Besides the
+ * special encoding in {@code FormulaRecord.SpecialCachedValue}, it is not known how/whether
* Excel attempts to encode NaN values.
*
* Observed NaN behaviour on HotSpot/Windows:
- * <tt>Double.longBitsToDouble()</tt> will set one bit 51 (the NaN signaling flag) if it isn't
- * already. <tt>Double.doubleToLongBits()</tt> will return a double with bit pattern
- * <tt>0x7FF8000000000000L</tt> for any NaN bit pattern supplied.<br>
+ * {@code Double.longBitsToDouble()} will set one bit 51 (the NaN signaling flag) if it isn't
+ * already. {@code Double.doubleToLongBits()} will return a double with bit pattern
+ * {@code 0x7FF8000000000000L} for any NaN bit pattern supplied.<br>
* Differences are likely to be observed with other architectures.<p>
*
* <p>
/**
* Class to test IntList
- *
- * @author Marc Johnson
*/
final class TestIntList {
@Test