diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2021-03-27 14:03:16 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2021-03-27 14:03:16 +0000 |
commit | 37791e4bdfc706aa5684745594260f243b4be7ee (patch) | |
tree | a8dd8d0976fc478074d52cd3de79e0e6b5e6a33a /src/java/org/apache/poi/ss/usermodel | |
parent | 2bb3839bfe3e3bacff79f8157465633e311239ce (diff) | |
download | poi-37791e4bdfc706aa5684745594260f243b4be7ee.tar.gz poi-37791e4bdfc706aa5684745594260f243b4be7ee.zip |
65206 - Migrate ant / maven to gradle build
update gradle files and project structure along https://github.com/centic9/poi/tree/gradle_build
remove eclipse IDE project files
remove obsolete record generator files
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1888111 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/java/org/apache/poi/ss/usermodel')
91 files changed, 0 insertions, 14978 deletions
diff --git a/src/java/org/apache/poi/ss/usermodel/AutoFilter.java b/src/java/org/apache/poi/ss/usermodel/AutoFilter.java deleted file mode 100644 index 2b8c2446c5..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/AutoFilter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -/** - * Represents autofiltering for the specified worksheet. - * - * <p> - * Filtering data is a quick and easy way to find and work with a subset of data in a range of cells or table. - * For example, you can filter to see only the values that you specify, filter to see the top or bottom values, - * or filter to quickly see duplicate values. - * </p> - * - * TODO YK: For now (Aug 2010) POI only supports setting a basic autofilter on a range of cells. - * In future, when we support more auto-filter functions like custom criteria, sort, etc. we will add - * corresponding methods to this interface. - */ -public interface AutoFilter { - /** - * Apply a custom filter - * - * <p> - * A custom AutoFilter specifies an operator and a value. - * There can be at most two customFilters specified, and in that case the parent element - * specifies whether the two conditions are joined by 'and' or 'or'. For any cells whose - * values do not meet the specified criteria, the corresponding rows shall be hidden from - * view when the filter is applied. - * </p> - * - * <p> - * Example: - * <blockquote><pre> - * AutoFilter filter = sheet.setAutoFilter(CellRangeAddress.valueOf("A1:F200")); - * filter.applyFilter(0, FilterOperator.GreaterThanOrEqual", "0.2"); - * filter.applyFilter(1, FilterOperator.LessThanOrEqual"", "0.5"); - * </pre></blockquote> - * </p> - * - * @param columnIndex 0-based column index - * @param operator the operator to apply - * @param criteria top or bottom value used in the filter criteria. - * - * TODO YK: think how to combine AutoFilter with with DataValidationConstraint, they are really close relatives - * void applyFilter(int columnIndex, FilterOperator operator, String criteria); - */ - - - /** - * Apply a filter against a list of values - * - * <p> - * Example: - * <blockquote><pre> - * AutoFilter filter = sheet.setAutoFilter(CellRangeAddress.valueOf("A1:F200")); - * filter.applyFilter(0, "apache", "poi", "java", "api"); - * </pre></blockquote> - * </p> - * - * @param columnIndex 0-based column index - * @param values the filter values - * - * void applyFilter(int columnIndex, String ... values); - */ - -} diff --git a/src/java/org/apache/poi/ss/usermodel/BorderExtent.java b/src/java/org/apache/poi/ss/usermodel/BorderExtent.java deleted file mode 100644 index 7115883b35..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/BorderExtent.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating which borders to draw in a Property Template - */ -public enum BorderExtent { - /** - * No properties defined. This can be used to remove existing properties - * from the PropertyTemplate. - */ - NONE, - - /** - * All borders, that is top, bottom, left and right, including interior - * borders for the range. Does not include diagonals which are different - * and not implemented here. - */ - ALL, - - /** - * All inside borders. This is top, bottom, left, and right borders, but - * restricted to the interior borders for the range. For a range of one - * cell, this will produce no borders. - */ - INSIDE, - - /** - * All outside borders. That is top, bottom, left and right borders that - * bound the range only. - */ - OUTSIDE, - - /** - * This is just the top border for the range. No interior borders will - * be produced. - */ - TOP, - - /** - * This is just the bottom border for the range. No interior borders - * will be produced. - */ - BOTTOM, - - /** - * This is just the left border for the range, no interior borders will - * be produced. - */ - LEFT, - - /** - * This is just the right border for the range, no interior borders will - * be produced. - */ - RIGHT, - - /** - * This is all horizontal borders for the range, including interior and - * outside borders. - */ - HORIZONTAL, - - /** - * This is just the interior horizontal borders for the range. - */ - INSIDE_HORIZONTAL, - - /** - * This is just the outside horizontal borders for the range. - */ - OUTSIDE_HORIZONTAL, - - /** - * This is all vertical borders for the range, including interior and - * outside borders. - */ - VERTICAL, - - /** - * This is just the interior vertical borders for the range. - */ - INSIDE_VERTICAL, - - /** - * This is just the outside vertical borders for the range. - */ - OUTSIDE_VERTICAL -} diff --git a/src/java/org/apache/poi/ss/usermodel/BorderFormatting.java b/src/java/org/apache/poi/ss/usermodel/BorderFormatting.java deleted file mode 100644 index 985a215409..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/BorderFormatting.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * High level representation for Border Formatting component - * of Conditional Formatting settings - */ -public interface BorderFormatting { - - /** @since POI 4.0.0 */ - BorderStyle getBorderBottom(); - - /** @since POI 4.0.0 */ - BorderStyle getBorderDiagonal(); - - /** @since POI 4.0.0 */ - BorderStyle getBorderLeft(); - - /** @since POI 4.0.0 */ - BorderStyle getBorderRight(); - - /** @since POI 4.0.0 */ - BorderStyle getBorderTop(); - - /** - * Only valid for range borders, such as table styles - * @since 4.0.0 - * @return border style - */ - BorderStyle getBorderVertical(); - /** - * Only valid for range borders, such as table styles - * @since 4.0.0 - * @return border style - */ - BorderStyle getBorderHorizontal(); - - short getBottomBorderColor(); - Color getBottomBorderColorColor(); - - short getDiagonalBorderColor(); - Color getDiagonalBorderColorColor(); - - short getLeftBorderColor(); - Color getLeftBorderColorColor(); - - short getRightBorderColor(); - Color getRightBorderColorColor(); - - short getTopBorderColor(); - Color getTopBorderColorColor(); - - /** - * Range internal borders. Only relevant for range styles, such as table formatting - * @since 3.17 beta 1 - * @return color index - */ - short getVerticalBorderColor(); - /** - * Range internal borders. Only relevant for range styles, such as table formatting - * @since 3.17 beta 1 - * @return color - */ - Color getVerticalBorderColorColor(); - - /** - * Range internal borders. Only relevant for range styles, such as table formatting - * @since 3.17 beta 1 - * @return color index - */ - short getHorizontalBorderColor(); - /** - * Range internal borders. Only relevant for range styles, such as table formatting - * @since 3.17 beta 1 - * @return color - */ - Color getHorizontalBorderColorColor(); - - /** - * Set bottom border. - * - * @param border The style of border to set. - */ - void setBorderBottom(BorderStyle border); - - /** - * Set diagonal border. - * - * @param border The style of border to set. - */ - void setBorderDiagonal(BorderStyle border); - - /** - * Set left border. - * - * @param border The style of border to set. - */ - void setBorderLeft(BorderStyle border); - - /** - * Set right border. - * - * @param border The style of border to set. - */ - void setBorderRight(BorderStyle border); - - /** - * Set top border. - * - * @param border The style of border to set. - */ - void setBorderTop(BorderStyle border); - - /** - * Set range internal horizontal borders. - * - * @since 3.17 beta 1 - * @param border The style of border to set. - */ - void setBorderHorizontal(BorderStyle border); - - /** - * Set range internal vertical borders. - * - * @since 3.17 beta 1 - * @param border The style of border to set. - */ - void setBorderVertical(BorderStyle border); - - void setBottomBorderColor(short color); - void setBottomBorderColor(Color color); - - void setDiagonalBorderColor(short color); - void setDiagonalBorderColor(Color color); - - void setLeftBorderColor(short color); - void setLeftBorderColor(Color color); - - void setRightBorderColor(short color); - void setRightBorderColor(Color color); - - void setTopBorderColor(short color); - void setTopBorderColor(Color color); - - /** - * Range internal border color, such as table styles - * @since 3.17 beta 1 - * @param color index - */ - void setHorizontalBorderColor(short color); - /** - * Range internal border color, such as table styles - * @since 3.17 beta 1 - * @param color index - */ - void setHorizontalBorderColor(Color color); - - /** - * Range internal border color, such as table styles - * @since 3.17 beta 1 - * @param color index - */ - void setVerticalBorderColor(short color); - /** - * Range internal border color, such as table styles - * @since 3.17 beta 1 - * @param color index - */ - void setVerticalBorderColor(Color color); -} diff --git a/src/java/org/apache/poi/ss/usermodel/BorderStyle.java b/src/java/org/apache/poi/ss/usermodel/BorderStyle.java deleted file mode 100644 index 9fd5d15cbd..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/BorderStyle.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating the line style of a border in a cell, - * i.e., whether it is bordered dash dot, dash dot dot, dashed, dotted, double, hair, medium, - * medium dash dot, medium dash dot dot, medium dashed, none, slant dash dot, thick or thin. - */ - public enum BorderStyle { - - /** - * No border (default) - */ - NONE(0x0), - - /** - * Thin border - */ - THIN(0x1), - - /** - * Medium border - */ - MEDIUM(0x2), - - /** - * dash border - */ - DASHED(0x3), - - /** - * dot border - */ - DOTTED(0x4), - - /** - * Thick border - */ - THICK(0x5), - - /** - * double-line border - */ - DOUBLE(0x6), - - /** - * hair-line border - */ - HAIR(0x7), - - /** - * Medium dashed border - */ - MEDIUM_DASHED(0x8), - - /** - * dash-dot border - */ - DASH_DOT(0x9), - - /** - * medium dash-dot border - */ - MEDIUM_DASH_DOT(0xA), - - /** - * dash-dot-dot border - */ - DASH_DOT_DOT(0xB), - - /** - * medium dash-dot-dot border - */ - MEDIUM_DASH_DOT_DOT(0xC), - - /** - * slanted dash-dot border - */ - SLANTED_DASH_DOT(0xD); - - private final short code; - - private BorderStyle(int code) { - this.code = (short)code; - } - - public short getCode() { - return code; - } - - private static final BorderStyle[] _table = new BorderStyle[0xD + 1]; - static { - for (BorderStyle c : values()) { - _table[c.getCode()] = c; - } - } - - public static BorderStyle valueOf(short code) { - return _table[code]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/BuiltinFormats.java b/src/java/org/apache/poi/ss/usermodel/BuiltinFormats.java deleted file mode 100644 index c430888178..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/BuiltinFormats.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -/** - * Utility to identify built-in formats. The following is a list of the formats as - * returned by this class.<p> - *<p> - * 0, "General"<br> - * 1, "0"<br> - * 2, "0.00"<br> - * 3, "#,##0"<br> - * 4, "#,##0.00"<br> - * 5, "$#,##0_);($#,##0)"<br> - * 6, "$#,##0_);[Red]($#,##0)"<br> - * 7, "$#,##0.00);($#,##0.00)"<br> - * 8, "$#,##0.00_);[Red]($#,##0.00)"<br> - * 9, "0%"<br> - * 0xa, "0.00%"<br> - * 0xb, "0.00E+00"<br> - * 0xc, "# ?/?"<br> - * 0xd, "# ??/??"<br> - * 0xe, "m/d/yy"<br> - * 0xf, "d-mmm-yy"<br> - * 0x10, "d-mmm"<br> - * 0x11, "mmm-yy"<br> - * 0x12, "h:mm AM/PM"<br> - * 0x13, "h:mm:ss AM/PM"<br> - * 0x14, "h:mm"<br> - * 0x15, "h:mm:ss"<br> - * 0x16, "m/d/yy h:mm"<br> - *<p> - * // 0x17 - 0x24 reserved for international and undocumented - * 0x25, "#,##0_);(#,##0)"<br> - * 0x26, "#,##0_);[Red](#,##0)"<br> - * 0x27, "#,##0.00_);(#,##0.00)"<br> - * 0x28, "#,##0.00_);[Red](#,##0.00)"<br> - * 0x29, "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)"<br> - * 0x2a, "_($* #,##0_);_($* (#,##0);_($* \"-\"_);_(@_)"<br> - * 0x2b, "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)"<br> - * 0x2c, "_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)"<br> - * 0x2d, "mm:ss"<br> - * 0x2e, "[h]:mm:ss"<br> - * 0x2f, "mm:ss.0"<br> - * 0x30, "##0.0E+0"<br> - * 0x31, "@" - This is text format.<br> - * 0x31 "text" - Alias for "@"<br> - * <p> - */ -public final class BuiltinFormats { - /** - * The first user-defined number format starts at 164. - */ - public static final int FIRST_USER_DEFINED_FORMAT_INDEX = 164; - - private static final String[] _formats = { - "General", - "0", - "0.00", - "#,##0", - "#,##0.00", - "\"$\"#,##0_);(\"$\"#,##0)", - "\"$\"#,##0_);[Red](\"$\"#,##0)", - "\"$\"#,##0.00_);(\"$\"#,##0.00)", - "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)", - "0%", - "0.00%", - "0.00E+00", - "# ?/?", - "# ??/??", - "m/d/yy", - "d-mmm-yy", - "d-mmm", - "mmm-yy", - "h:mm AM/PM", - "h:mm:ss AM/PM", - "h:mm", - "h:mm:ss", - "m/d/yy h:mm", - - // 0x17 - 0x24 reserved for international and undocumented - // TODO - one junit relies on these values which seems incorrect - "reserved-0x17", - "reserved-0x18", - "reserved-0x19", - "reserved-0x1A", - "reserved-0x1B", - "reserved-0x1C", - "reserved-0x1D", - "reserved-0x1E", - "reserved-0x1F", - "reserved-0x20", - "reserved-0x21", - "reserved-0x22", - "reserved-0x23", - "reserved-0x24", - - "#,##0_);(#,##0)", - "#,##0_);[Red](#,##0)", - "#,##0.00_);(#,##0.00)", - "#,##0.00_);[Red](#,##0.00)", - "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", - "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)", - "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", - "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)", - "mm:ss", - "[h]:mm:ss", - "mm:ss.0", - "##0.0E+0", - "@" - }; - - /** - * @return array of built-in data formats - */ - public static String[] getAll() { - return _formats.clone(); - } - - /** - * Get the format string that matches the given format index - * - * @param index of a built in format - * @return string represented at index of format or <code>null</code> if there is not a built-in format at that index - */ - public static String getBuiltinFormat(int index) { - if (index < 0 || index >=_formats.length) { - return null; - } - return _formats[index]; - } - - /** - * Get the format index that matches the given format string.<br> - * Automatically converts "text" to excel's format string to represent text. - * - * @param pFmt string matching a built-in format - * @return index of format or -1 if undefined. - */ - public static int getBuiltinFormat(String pFmt) { - String fmt = "TEXT".equalsIgnoreCase(pFmt) ? "@" : pFmt; - - int i = -1; - for (String f : _formats) { - i++; - if (f.equals(fmt)) { - return i; - } - } - - return -1; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/Cell.java b/src/java/org/apache/poi/ss/usermodel/Cell.java deleted file mode 100644 index 5e3918f3d3..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Cell.java +++ /dev/null @@ -1,445 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; -import java.util.Map; - -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.Removal; - -/** - * High level representation of a cell in a row of a spreadsheet. - * <p> - * Cells can be numeric, formula-based or string-based (text). The cell type - * specifies this. String cells cannot conatin numbers and numeric cells cannot - * contain strings (at least according to our model). Client apps should do the - * conversions themselves. Formula cells have the formula string, as well as - * the formula result, which can be numeric or string. - * </p> - * <p> - * Cells should have their number (0 based) before being added to a row. - * </p> - */ -public interface Cell { - - /** - * Returns column index of this cell - * - * @return zero-based column index of a column in a sheet. - */ - int getColumnIndex(); - - /** - * Returns row index of a row in the sheet that contains this cell - * - * @return zero-based row index of a row in the sheet that contains this cell - */ - int getRowIndex(); - - /** - * Returns the sheet this cell belongs to - * - * @return the sheet this cell belongs to - */ - Sheet getSheet(); - - /** - * Returns the Row this cell belongs to - * - * @return the Row that owns this cell - */ - Row getRow(); - - /** - * Set the cells type (blank, numeric, boolean, error or string). - * <p>If the cell currently contains a value, the value will - * be converted to match the new type, if possible. Formatting - * is generally lost in the process however.</p> - * <p>Conversion rules:</p> - * <p>to NUMERIC: numeric value is left as is. True converts to 1.0, false converts to 0. otherwise, the - * value is set to 0. Formula is removed.</p> - * <p>If what you want to do is get a String value for your - * numeric cell, <i>stop!</i> This is not the way to do it. - * Instead, for fetching the string value of a numeric or boolean - * or date cell, use {@link DataFormatter} instead.</p> - * <p>If cell is a member of an array formula group containing more than 1 cell, an {@link IllegalStateException} - * is thrown. If the array formula group contains only this cell, it is removed.</p> - * <p>Passing {@link CellType#FORMULA} is illegal and will result in an {@link IllegalArgumentException}.</p> - * - * @deprecated This method is deprecated and will be removed in POI 5.0. - * Use explicit {@link #setCellFormula(String)}, <code>setCellValue(...)</code> or {@link #setBlank()} - * to get the desired result. - * @throws IllegalArgumentException if the specified cell type is invalid (null, _NONE or FORMULA) - * @throws IllegalStateException if the current value cannot be converted to the new type or - * if the cell is a part of an array formula group containing other cells - */ - @Deprecated - @Removal(version = "5.0") - void setCellType(CellType cellType); - - /** - * Removes formula and value from the cell, and sets its type to {@link CellType#BLANK}. - * Preserves comments and hyperlinks. - * While {@link #setCellType(CellType)} exists, is an alias for {@code setCellType(CellType.BLANK)}. - */ - void setBlank(); - - /** - * Return the cell type. - * - * @return the cell type - */ - CellType getCellType(); - - /** - * Only valid for formula cells - * - * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, - * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending - * on the cached value of the formula - */ - CellType getCachedFormulaResultType(); - - /** - * Set a numeric value for the cell. - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numeric cell and set its value. - */ - void setCellValue(double value); - - /** - * <p>Converts the supplied date to its equivalent Excel numeric value and sets - * that into the cell.</p> - * - * <p><b>Note</b> - There is actually no 'DATE' cell type in Excel. In many - * cases (when entering date values), Excel automatically adjusts the - * <i>cell style</i> to some date format, creating the illusion that the cell - * data type is now something besides {@link CellType#NUMERIC}. POI - * does not attempt to replicate this behaviour. To make a numeric cell - * display as a date, use {@link #setCellStyle(CellStyle)} etc.</p> - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numerics cell and set its value. - */ - void setCellValue(Date value); - - /** - * <p>Converts the supplied date to its equivalent Excel numeric value and sets - * that into the cell.</p> - * - * <p><b>Note</b> - There is actually no 'DATE' cell type in Excel. In many - * cases (when entering date values), Excel automatically adjusts the - * <i>cell style</i> to some date format, creating the illusion that the cell - * data type is now something besides {@link CellType#NUMERIC}. POI - * does not attempt to replicate this behaviour. To make a numeric cell - * display as a date, use {@link #setCellStyle(CellStyle)} etc.</p> - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numerics cell and set its value. - */ - void setCellValue(LocalDateTime value); - - /** - * <p>Converts the supplied date to its equivalent Excel numeric value and sets - * that into the cell.</p> - * - * <p><b>Note</b> - There is actually no 'DATE' cell type in Excel. In many - * cases (when entering date values), Excel automatically adjusts the - * <i>cell style</i> to some date format, creating the illusion that the cell - * data type is now something besides {@link CellType#NUMERIC}. POI - * does not attempt to replicate this behaviour. To make a numeric cell - * display as a date, use {@link #setCellStyle(CellStyle)} etc.</p> - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numerics cell and set its value. - */ - default void setCellValue(LocalDate value) { - setCellValue(value == null ? null : value.atStartOfDay()); - } - - /** - * <p>Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as - * a date.</p> - * <p> - * This will set the cell value based on the Calendar's timezone. As Excel - * does not support timezones this means that both 20:00+03:00 and - * 20:00-03:00 will be reported as the same value (20:00) even that there - * are 6 hours difference between the two times. This difference can be - * preserved by using <code>setCellValue(value.getTime())</code> which will - * automatically shift the times to the default timezone. - * </p> - * - * @param value the date value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For othertypes we - * will change the cell to a numeric cell and set its value. - */ - void setCellValue(Calendar value); - - /** - * Set a rich string value for the cell. - * - * @param value value to set the cell to. For formulas we'll set the formula - * string, for String cells we'll set its value. For other types we will - * change the cell to a string cell and set its value. - * If value is null then we will change the cell to a Blank cell. - */ - void setCellValue(RichTextString value); - - /** - * Set a string value for the cell. - * - * @param value value to set the cell to. For formulas we'll set the formula - * string, for String cells we'll set its value. For other types we will - * change the cell to a string cell and set its value. - * If value is null then we will change the cell to a Blank cell. - */ - void setCellValue(String value); - - - /** - * Sets formula for this cell. - * <p>If {@code formula} is not null, sets or updates the formula. If {@code formula} is null, removes the formula. - * Or use {@link #removeFormula()} to remove the formula.</p> - * - * <p>Note, this method only sets the formula string and does not calculate the formula value. - * To set the precalculated value use {@link #setCellValue}.</p> - * - * <p>If the cell was blank, sets value to 0. Otherwise, preserves the value as precalculated.</p> - * - * @param formula the formula to set, e.g. <code>"SUM(C4:E4)"</code>. - * If the argument is <code>null</code> then the current formula is removed. - * - * @see Cell#removeFormula - * @throws IllegalStateException if this cell is a part of an array formula group containing other cells - * @throws FormulaParseException if the formula has incorrect syntax or is otherwise invalid - */ - void setCellFormula(String formula) throws FormulaParseException, IllegalStateException; - - /** - * Removes formula, if any. - * - * If cell was blank, leaves it as is. - * If it is a part of an array formula group, blanks the cell. - * If has a regular formula, removes the formula preserving the "cached" value. - * @throws IllegalStateException if cell is a part of an array formula group containing other cells - */ - void removeFormula() throws IllegalStateException; - - /** - * Return a formula for the cell, for example, <code>SUM(C4:E4)</code> - * - * @return a formula for the cell - * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is not {@link CellType#FORMULA} - */ - String getCellFormula(); - - /** - * Get the value of the cell as a number. - * <p> - * For strings we throw an exception. For blank cells we return a 0. - * For formulas or error cells we return the precalculated value; - * </p> - * @return the value of the cell as a number - * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is {@link CellType#STRING} - * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>. - * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as. - */ - double getNumericCellValue(); - - /** - * Get the value of the cell as a date. - * <p> - * For strings we throw an exception. For blank cells we return a null. - * </p> - * @return the value of the cell as a date - * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is {@link CellType#STRING} - * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>. - * @see DataFormatter for formatting this date into a string similar to how excel does. - */ - Date getDateCellValue(); - - /** - * Get the value of the cell as a LocalDateTime. - * <p> - * For strings we throw an exception. For blank cells we return a null. - * </p> - * @return the value of the cell as a LocalDateTime - * @throws IllegalStateException if the cell type returned by {@link #getCellType()} is {@link CellType#STRING} - * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>. - * @see DataFormatter for formatting this date into a string similar to how excel does. - */ - LocalDateTime getLocalDateTimeCellValue(); - - /** - * Get the value of the cell as a XSSFRichTextString - * <p> - * For numeric cells we throw an exception. For blank cells we return an empty string. - * For formula cells we return the pre-calculated value if a string, otherwise an exception. - * </p> - * @return the value of the cell as a XSSFRichTextString - */ - RichTextString getRichStringCellValue(); - - /** - * Get the value of the cell as a string - * <p> - * For numeric cells we throw an exception. For blank cells we return an empty string. - * For formulaCells that are not string Formulas, we throw an exception. - * </p> - * @return the value of the cell as a string - */ - String getStringCellValue(); - - /** - * Set a boolean value for the cell - * - * @param value the boolean value to set this cell to. For formulas we'll set the - * precalculated value, for booleans we'll set its value. For other types we - * will change the cell to a boolean cell and set its value. - */ - void setCellValue(boolean value); - - /** - * Set a error value for the cell - * - * @param value the error value to set this cell to. For formulas we'll set the - * precalculated value , for errors we'll set - * its value. For other types we will change the cell to an error - * cell and set its value. - * @see FormulaError - */ - void setCellErrorValue(byte value); - - /** - * Get the value of the cell as a boolean. - * <p> - * For strings, numbers, and errors, we throw an exception. For blank cells we return a false. - * </p> - * @return the value of the cell as a boolean - * @throws IllegalStateException if the cell type returned by {@link #getCellType()} - * is not {@link CellType#BOOLEAN}, {@link CellType#BLANK} or {@link CellType#FORMULA} - */ - boolean getBooleanCellValue(); - - /** - * Get the value of the cell as an error code. - * <p> - * For strings, numbers, and booleans, we throw an exception. - * For blank cells we return a 0. - * </p> - * - * @return the value of the cell as an error code - * @throws IllegalStateException if the cell type returned by {@link #getCellType()} isn't {@link CellType#ERROR} - * @see FormulaError for error codes - */ - byte getErrorCellValue(); - - /** - * <p>Set the style for the cell. The style should be an CellStyle created/retrieved from - * the Workbook.</p> - * - * <p>To change the style of a cell without affecting other cells that use the same style, - * use {@link org.apache.poi.ss.util.CellUtil#setCellStyleProperties(Cell, Map)}</p> - * - * @param style reference contained in the workbook. - * If the value is null then the style information is removed causing the cell to used the default workbook style. - * @see org.apache.poi.ss.usermodel.Workbook#createCellStyle() - */ - void setCellStyle(CellStyle style); - - /** - * Return the cell's style. - * - * @return the cell's style. Always not-null. Default cell style has zero index and can be obtained as - * <code>workbook.getCellStyleAt(0)</code> - * @see Workbook#getCellStyleAt(int) - */ - CellStyle getCellStyle(); - - /** - * Sets this cell as the active cell for the worksheet - */ - void setAsActiveCell(); - - /** - * Gets the address of this cell - * - * @return <code>A1</code> style address of this cell - * @since 3.14beta1 - */ - CellAddress getAddress(); - - /** - * Assign a comment to this cell - * - * @param comment comment associated with this cell - */ - void setCellComment(Comment comment); - - /** - * Returns comment associated with this cell - * - * @return comment associated with this cell or <code>null</code> if not found - */ - Comment getCellComment(); - - /** - * Removes the comment for this cell, if there is one. - */ - void removeCellComment(); - - /** - * @return hyperlink associated with this cell or <code>null</code> if not found - */ - Hyperlink getHyperlink(); - - /** - * Assign a hyperlink to this cell - * - * @param link hyperlink associated with this cell - */ - void setHyperlink(Hyperlink link); - - /** - * Removes the hyperlink for this cell, if there is one. - */ - void removeHyperlink(); - - /** - * Only valid for array formula cells - * - * @return range of the array formula group that the cell belongs to. - */ - CellRangeAddress getArrayFormulaRange(); - - /** - * @return <code>true</code> if this cell is part of group of cells having a common array formula. - */ - boolean isPartOfArrayFormulaGroup(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/CellBase.java b/src/java/org/apache/poi/ss/usermodel/CellBase.java deleted file mode 100644 index 726c9bd82b..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CellBase.java +++ /dev/null @@ -1,327 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Removal; - -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -/** - * 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 { - /** - * {@inheritDoc} - */ - @Override - public final void setCellType(CellType cellType) { - if (cellType == null || cellType == CellType._NONE) { - throw new IllegalArgumentException("cellType shall not be null nor _NONE"); - } - - if (cellType == CellType.FORMULA) { - if (getCellType() != CellType.FORMULA){ - throw new IllegalArgumentException("Calling Cell.setCellType(CellType.FORMULA) is illegal. " + - "Use setCellFormula(String) directly."); - } else { - return; - } - } - - tryToDeleteArrayFormulaIfSet(); - - setCellTypeImpl(cellType); - } - - /** - * {@inheritDoc} - */ - @Override - public void setBlank() { - setCellType(CellType.BLANK); - } - - /** - * {@inheritDoc} - */ - @Override - public CellAddress getAddress() { - return new CellAddress(this); - } - - /** - * Implementation-specific logic - * @param cellType new cell type. Guaranteed non-null, not _NONE. - */ - protected abstract void setCellTypeImpl(CellType cellType); - - /** - * Called when this an array formula in this cell is deleted. - * <p>The purpose of this method is to validate the cell state prior to modification.</p> - * - * @param message a customized exception message for the case if deletion of the cell is impossible. If null, a - * default message will be generated - * @see #setCellType(CellType) - * @see #setCellFormula(String) - * @see Row#removeCell(org.apache.poi.ss.usermodel.Cell) - * @see org.apache.poi.ss.usermodel.Sheet#removeRow(org.apache.poi.ss.usermodel.Row) - * @see org.apache.poi.ss.usermodel.Sheet#shiftRows(int, int, int) - * @see org.apache.poi.ss.usermodel.Sheet#addMergedRegion(org.apache.poi.ss.util.CellRangeAddress) - * @throws IllegalStateException if modification is not allowed - * - * Note. Exposing this to public is ugly. Needed for methods like Sheet#shiftRows. - */ - public final void tryToDeleteArrayFormula(String message) { - assert isPartOfArrayFormulaGroup(); - - CellRangeAddress arrayFormulaRange = getArrayFormulaRange(); - if(arrayFormulaRange.getNumberOfCells() > 1) { - if (message == null) { - message = "Cell " + new CellReference(this).formatAsString() + " is part of a multi-cell array formula. " + - "You cannot change part of an array."; - } - throw new IllegalStateException(message); - } - //un-register the single-cell array formula from the parent sheet through public interface - getRow().getSheet().removeArrayFormula(this); - } - - /** - * {@inheritDoc} - */ - @Override - public final void setCellFormula(String formula) throws FormulaParseException, IllegalStateException { - // todo validate formula here, before changing the cell? - tryToDeleteArrayFormulaIfSet(); - - if (formula == null) { - removeFormula(); - return; - } - - setCellFormulaImpl(formula); - } - - /** - * Implementation-specific setting the formula. Formula is not null. - * Shall not change the value. - * @param formula - */ - protected abstract void setCellFormulaImpl(String formula); - - /** - * Get value type of this cell. Can return BLANK, NUMERIC, STRING, BOOLEAN or ERROR. - * For current implementations where type is strongly coupled with formula, is equivalent to - * <code>getCellType() == CellType.FORMULA ? getCachedFormulaResultType() : getCellType()</code> - * - * <p>This is meant as a temporary helper method until the time when value type is decoupled from the formula.</p> - * @return value type - */ - protected final CellType getValueType() { - CellType type = getCellType(); - if (type != CellType.FORMULA) { - return type; - } - return getCachedFormulaResultType(); - } - - /** - * {@inheritDoc} - */ - @Override - public final void removeFormula() { - if (getCellType() == CellType.BLANK) { - return; - } - - if (isPartOfArrayFormulaGroup()) { - tryToDeleteArrayFormula(null); - return; - } - - removeFormulaImpl(); - } - - /** - * Implementation-specific removal of the formula. - * The cell is guaranteed to have a regular formula set. - * Shall preserve the "cached" value. - */ - protected abstract void removeFormulaImpl(); - - private void tryToDeleteArrayFormulaIfSet() { - if (isPartOfArrayFormulaGroup()) { - tryToDeleteArrayFormula(null); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setCellValue(double value) { - if(Double.isInfinite(value)) { - // Excel does not support positive/negative infinities, - // rather, it gives a #DIV/0! error in these cases. - setCellErrorValue(FormulaError.DIV0.getCode()); - } else if (Double.isNaN(value)){ - setCellErrorValue(FormulaError.NUM.getCode()); - } else { - setCellValueImpl(value); - } - } - - /** - * Implementation-specific way to set a numeric value. - * <code>value</code> is guaranteed to be a valid (non-NaN) double. - * The implementation is expected to adjust the cell type accordingly, so that after this call - * getCellType() or getCachedFormulaResultType() would return {@link CellType#NUMERIC}. - * @param value the new value to set - */ - protected abstract void setCellValueImpl(double value); - - @Override - public void setCellValue(Date value) { - if(value == null) { - setBlank(); - return; - } - setCellValueImpl(value); - } - - @Override - public void setCellValue(LocalDateTime value) { - if(value == null) { - setBlank(); - return; - } - setCellValueImpl(value); - } - - /** - * Implementation-specific way to set a date value. - * <code>value</code> is guaranteed to be non-null. - * The implementation is expected to adjust the cell type accordingly, so that after this call - * getCellType() or getCachedFormulaResultType() would return {@link CellType#NUMERIC}. - * @param value the new date to set - */ - protected abstract void setCellValueImpl(Date value); - - /** - * Implementation-specific way to set a date value. - * <code>value</code> is guaranteed to be non-null. - * The implementation is expected to adjust the cell type accordingly, so that after this call - * getCellType() or getCachedFormulaResultType() would return {@link CellType#NUMERIC}. - * @param value the new date to set - */ - protected abstract void setCellValueImpl(LocalDateTime value); - - /** - * {@inheritDoc} - */ - @Override - public void setCellValue(Calendar value) { - if(value == null) { - setBlank(); - return; - } - setCellValueImpl(value); - } - - /** - * Implementation-specific way to set a calendar value. - * <code>value</code> is guaranteed to be non-null. - * The implementation is expected to adjust the cell type accordingly, so that after this call - * getCellType() or getCachedFormulaResultType() would return {@link CellType#NUMERIC}. - * @param value the new calendar value to set - */ - protected abstract void setCellValueImpl(Calendar value); - - /** - * {@inheritDoc} - */ - @Override - public void setCellValue(String value) { - if(value == null){ - setBlank(); - return; - } - - checkLength(value); - - setCellValueImpl(value); - } - - /** - * Implementation-specific way to set a string value. - * The value is guaranteed to be non-null and to satisfy the length limitation imposed by the spreadsheet version. - * The implementation is expected to adjust cell type accordingly, so that after this call - * getCellType() or getCachedFormulaResultType() (whichever appropriate) would return {@link CellType#STRING}. - * @param value the new value to set. - */ - protected abstract void setCellValueImpl(String value); - - private void checkLength(String value) { - if(value.length() > getSpreadsheetVersion().getMaxTextLength()){ - final String message = String.format(Locale.ROOT, - "The maximum length of cell contents (text) is %d characters", - getSpreadsheetVersion().getMaxTextLength()); - throw new IllegalArgumentException(message); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setCellValue(RichTextString value) { - if(value == null || value.getString() == null){ - setBlank(); - return; - } - - checkLength(value.getString()); - - setCellValueImpl(value); - } - - /** - * Implementation-specific way to set a RichTextString value. - * The value is guaranteed to be non-null, having non-null value, and to satisfy the length limitation imposed - * by the spreadsheet version. - * The implementation is expected to adjust cell type accordingly, so that after this call - * getCellType() or getCachedFormulaResultType() (whichever appropriate) would return {@link CellType#STRING}. - * @param value the new value to set. - */ - protected abstract void setCellValueImpl(RichTextString value); - - /** - * Get the spreadsheet version for the given implementation. - * @return the spreadsheet version - */ - protected abstract SpreadsheetVersion getSpreadsheetVersion(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/CellCopyPolicy.java b/src/java/org/apache/poi/ss/usermodel/CellCopyPolicy.java deleted file mode 100644 index 8aea65ad23..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CellCopyPolicy.java +++ /dev/null @@ -1,293 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Beta; - -@Beta -public class CellCopyPolicy { - // cell-level policies - public static final boolean DEFAULT_COPY_CELL_VALUE_POLICY = true; - public static final boolean DEFAULT_COPY_CELL_STYLE_POLICY = true; - public static final boolean DEFAULT_COPY_CELL_FORMULA_POLICY = true; - public static final boolean DEFAULT_COPY_HYPERLINK_POLICY = true; - public static final boolean DEFAULT_MERGE_HYPERLINK_POLICY = false; - - // row-level policies - public static final boolean DEFAULT_COPY_ROW_HEIGHT_POLICY = true; - public static final boolean DEFAULT_CONDENSE_ROWS_POLICY = false; - - // sheet-level policies - public static final boolean DEFAULT_COPY_MERGED_REGIONS_POLICY = true; - - // cell-level policies - private boolean copyCellValue = DEFAULT_COPY_CELL_VALUE_POLICY; - private boolean copyCellStyle = DEFAULT_COPY_CELL_STYLE_POLICY; - private boolean copyCellFormula = DEFAULT_COPY_CELL_FORMULA_POLICY; - private boolean copyHyperlink = DEFAULT_COPY_HYPERLINK_POLICY; - private boolean mergeHyperlink = DEFAULT_MERGE_HYPERLINK_POLICY; - - // row-level policies - private boolean copyRowHeight = DEFAULT_COPY_ROW_HEIGHT_POLICY; - private boolean condenseRows = DEFAULT_CONDENSE_ROWS_POLICY; - - // sheet-level policies - private boolean copyMergedRegions = DEFAULT_COPY_MERGED_REGIONS_POLICY; - - /** - * Default CellCopyPolicy, uses default policy - * For custom CellCopyPolicy, use {@link Builder} class - */ - public CellCopyPolicy() { } - - /** - * Copy constructor - * - * @param other policy to copy - */ - public CellCopyPolicy(CellCopyPolicy other) { - copyCellValue = other.isCopyCellValue(); - copyCellStyle = other.isCopyCellStyle(); - copyCellFormula = other.isCopyCellFormula(); - copyHyperlink = other.isCopyHyperlink(); - mergeHyperlink = other.isMergeHyperlink(); - - copyRowHeight = other.isCopyRowHeight(); - condenseRows = other.isCondenseRows(); - - copyMergedRegions = other.isCopyMergedRegions(); - } - - // should builder be replaced with CellCopyPolicy setters that return the object - // to allow setters to be chained together? - // policy.setCopyCellValue(true).setCopyCellStyle(true) - private CellCopyPolicy(Builder builder) { - copyCellValue = builder.copyCellValue; - copyCellStyle = builder.copyCellStyle; - copyCellFormula = builder.copyCellFormula; - copyHyperlink = builder.copyHyperlink; - mergeHyperlink = builder.mergeHyperlink; - - copyRowHeight = builder.copyRowHeight; - condenseRows = builder.condenseRows; - - copyMergedRegions = builder.copyMergedRegions; - } - - public static class Builder { - // cell-level policies - private boolean copyCellValue = DEFAULT_COPY_CELL_VALUE_POLICY; - private boolean copyCellStyle = DEFAULT_COPY_CELL_STYLE_POLICY; - private boolean copyCellFormula = DEFAULT_COPY_CELL_FORMULA_POLICY; - private boolean copyHyperlink = DEFAULT_COPY_HYPERLINK_POLICY; - private boolean mergeHyperlink = DEFAULT_MERGE_HYPERLINK_POLICY; - - // row-level policies - private boolean copyRowHeight = DEFAULT_COPY_ROW_HEIGHT_POLICY; - private boolean condenseRows = DEFAULT_CONDENSE_ROWS_POLICY; - - // sheet-level policies - private boolean copyMergedRegions = DEFAULT_COPY_MERGED_REGIONS_POLICY; - - /** - * Builder class for CellCopyPolicy - */ - public Builder() { - } - - // cell-level policies - public Builder cellValue(boolean copyCellValue) { - this.copyCellValue = copyCellValue; - return this; - } - public Builder cellStyle(boolean copyCellStyle) { - this.copyCellStyle = copyCellStyle; - return this; - } - public Builder cellFormula(boolean copyCellFormula) { - this.copyCellFormula = copyCellFormula; - return this; - } - public Builder copyHyperlink(boolean copyHyperlink) { - this.copyHyperlink = copyHyperlink; - return this; - } - public Builder mergeHyperlink(boolean mergeHyperlink) { - this.mergeHyperlink = mergeHyperlink; - return this; - } - - // row-level policies - public Builder rowHeight(boolean copyRowHeight) { - this.copyRowHeight = copyRowHeight; - return this; - } - public Builder condenseRows(boolean condenseRows) { - this.condenseRows = condenseRows; - return this; - } - - // sheet-level policies - public Builder mergedRegions(boolean copyMergedRegions) { - this.copyMergedRegions = copyMergedRegions; - return this; - } - public CellCopyPolicy build() { - return new CellCopyPolicy(this); - } - } - - public Builder createBuilder() { - return new Builder() - .cellValue(copyCellValue) - .cellStyle(copyCellStyle) - .cellFormula(copyCellFormula) - .copyHyperlink(copyHyperlink) - .mergeHyperlink(mergeHyperlink) - .rowHeight(copyRowHeight) - .condenseRows(condenseRows) - .mergedRegions(copyMergedRegions); - } - -/* - * Cell-level policies - */ - /** - * @return the copyCellValue - */ - public boolean isCopyCellValue() { - return copyCellValue; - } - - /** - * @param copyCellValue the copyCellValue to set - */ - public void setCopyCellValue(boolean copyCellValue) { - this.copyCellValue = copyCellValue; - } - - /** - * @return the copyCellStyle - */ - public boolean isCopyCellStyle() { - return copyCellStyle; - } - - /** - * @param copyCellStyle the copyCellStyle to set - */ - public void setCopyCellStyle(boolean copyCellStyle) { - this.copyCellStyle = copyCellStyle; - } - - /** - * @return the copyCellFormula - */ - public boolean isCopyCellFormula() { - return copyCellFormula; - } - - /** - * @param copyCellFormula the copyCellFormula to set - */ - public void setCopyCellFormula(boolean copyCellFormula) { - this.copyCellFormula = copyCellFormula; - } - - /** - * @return the copyHyperlink - */ - public boolean isCopyHyperlink() { - return copyHyperlink; - } - - /** - * @param copyHyperlink the copyHyperlink to set - */ - public void setCopyHyperlink(boolean copyHyperlink) { - this.copyHyperlink = copyHyperlink; - } - - /** - * @return the mergeHyperlink - */ - public boolean isMergeHyperlink() { - return mergeHyperlink; - } - - /** - * @param mergeHyperlink the mergeHyperlink to set - */ - public void setMergeHyperlink(boolean mergeHyperlink) { - this.mergeHyperlink = mergeHyperlink; - } - -/* - * Row-level policies - */ - /** - * @return the copyRowHeight - */ - public boolean isCopyRowHeight() { - return copyRowHeight; - } - - /** - * @param copyRowHeight the copyRowHeight to set - */ - public void setCopyRowHeight(boolean copyRowHeight) { - this.copyRowHeight = copyRowHeight; - } - - /** - * If condenseRows is true, a discontinuities in srcRows will be removed when copied to destination - * For example: - * Sheet.copyRows({Row(1), Row(2), Row(5)}, 11, policy) results in rows 1, 2, and 5 - * being copied to rows 11, 12, and 13 if condenseRows is True, or rows 11, 11, 15 if condenseRows is false - * @return the condenseRows - */ - public boolean isCondenseRows() { - return condenseRows; - } - - /** - * @param condenseRows the condenseRows to set - */ - public void setCondenseRows(boolean condenseRows) { - this.condenseRows = condenseRows; - } - - -/* - * Sheet-level policies - */ - /** - * @return the copyMergedRegions - */ - public boolean isCopyMergedRegions() { - return copyMergedRegions; - } - - /** - * @param copyMergedRegions the copyMergedRegions to set - */ - public void setCopyMergedRegions(boolean copyMergedRegions) { - this.copyMergedRegions = copyMergedRegions; - } - -} diff --git a/src/java/org/apache/poi/ss/usermodel/CellRange.java b/src/java/org/apache/poi/ss/usermodel/CellRange.java deleted file mode 100644 index 4868dd8e81..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CellRange.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.util.Iterator; - - -/** - * Represents a rectangular region of a {@link Sheet} - */ -public interface CellRange<C extends Cell> extends Iterable<C> { - int getWidth(); - int getHeight(); - - /** - * Gets the number of cells in this range. - * @return <tt>height * width </tt> - */ - int size(); - - /** - * @return the text format of this range. Single cell ranges are formatted - * like single cell references (e.g. 'A1' instead of 'A1:A1'). - */ - String getReferenceText(); - - /** - * @return the cell at relative coordinates (0,0). Never <code>null</code>. - */ - 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>. - */ - C getCell(int relativeRowIndex, int relativeColumnIndex); - /** - * @return a flattened array of all the cells in this {@link 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>) - */ - 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. - */ - Iterator<C> iterator(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/CellStyle.java b/src/java/org/apache/poi/ss/usermodel/CellStyle.java deleted file mode 100644 index 8417887f5f..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CellStyle.java +++ /dev/null @@ -1,382 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Removal; - -public interface CellStyle { - - /** - * get the index within the Workbook (sequence within the collection of ExtnededFormat objects) - * @return unique index number of the underlying record this style represents (probably you don't care - * unless you're comparing which one is which) - */ - short getIndex(); - - /** - * set the data format (must be a valid format). Built in formats are defined at {@link BuiltinFormats}. - * @see DataFormat - */ - void setDataFormat(short fmt); - - /** - * get the index of the data format. Built in formats are defined at {@link BuiltinFormats}. - * @see DataFormat - */ - short getDataFormat(); - - /** - * Get the format string - */ - String getDataFormatString(); - - /** - * set the font for this style - * @param font a font object created or retrieved from the Workbook object - * @see Workbook#createFont() - * @see Workbook#getFontAt(int) - */ - void setFont(Font font); - - /** - * gets the index of the font for this style - * @see Workbook#getFontAt(int) - * @since 5.0.0 (used to return a short value) - */ - int getFontIndex(); - - /** - * gets the index of the font for this style - * @see Workbook#getFontAt(int) - * @deprecated use {@link #getFontIndex()} instead - * @since 4.0.0 - */ - @Deprecated - @Removal(version = "6.0.0") - int getFontIndexAsInt(); - - /** - * set the cell's using this style to be hidden - * @param hidden - whether the cell using this style should be hidden - */ - void setHidden(boolean hidden); - - /** - * get whether the cell's using this style are to be hidden - * @return hidden - whether the cell using this style should be hidden - */ - boolean getHidden(); - - /** - * set the cell's using this style to be locked - * @param locked - whether the cell using this style should be locked - */ - void setLocked(boolean locked); - - /** - * get whether the cell's using this style are to be locked - * @return hidden - whether the cell using this style should be locked - */ - boolean getLocked(); - - /** - * Turn on or off "Quote Prefix" or "123 Prefix" for the style, - * which is used to tell Excel that the thing which looks like - * a number or a formula shouldn't be treated as on. - * Turning this on is somewhat (but not completely, see {@link IgnoredErrorType}) - * like prefixing the cell value with a ' in Excel - */ - void setQuotePrefixed(boolean quotePrefix); - - /** - * Is "Quote Prefix" or "123 Prefix" enabled for the cell? - * Having this on is somewhat (but not completely, see {@link IgnoredErrorType}) - * like prefixing the cell value with a ' in Excel - */ - boolean getQuotePrefixed(); - - /** - * set the type of horizontal alignment for the cell - * @param align - the type of alignment - */ - void setAlignment(HorizontalAlignment align); - - /** - * get the type of horizontal alignment for the cell - * @return align - the type of alignment - */ - HorizontalAlignment getAlignment(); - - /** - * Set whether the text should be wrapped. - * Setting this flag to <code>true</code> make all content visible - * within a cell by displaying it on multiple lines - * - * @param wrapped wrap text or not - */ - void setWrapText(boolean wrapped); - - /** - * get whether the text should be wrapped - * @return wrap text or not - */ - boolean getWrapText(); - - /** - * set the type of vertical alignment for the cell - * @param align the type of alignment - */ - void setVerticalAlignment(VerticalAlignment align); - - /** - * get the type of vertical alignment for the cell - * @return align the type of alignment - */ - VerticalAlignment getVerticalAlignment(); - - /** - * set the degree of rotation for the text in the cell. - * - * Note: HSSF uses values from -90 to 90 degrees, whereas XSSF - * uses values from 0 to 180 degrees. The implementations of this method will map between these two value-ranges - * accordingly, however the corresponding getter is returning values in the range mandated by the current type - * of Excel file-format that this CellStyle is applied to. - * - * @param rotation degrees (see note above) - */ - void setRotation(short rotation); - - /** - * get the degree of rotation for the text in the cell. - * - * Note: HSSF uses values from -90 to 90 degrees, whereas XSSF - * uses values from 0 to 180 degrees. The implementations of this method will map between these two value-ranges - * value-range as used by the type of Excel file-format that this CellStyle is applied to. - * - * @return rotation degrees (see note above) - */ - short getRotation(); - - /** - * set the number of spaces to indent the text in the cell - * @param indent - number of spaces - */ - void setIndention(short indent); - - /** - * get the number of spaces to indent the text in the cell - * @return indent - number of spaces - */ - short getIndention(); - - /** - * set the type of border to use for the left border of the cell - * @param border type - * @since POI 3.15 - */ - void setBorderLeft(BorderStyle border); - - /** - * get the type of border to use for the left border of the cell - * @return border type - * @since POI 4.0.0 - */ - BorderStyle getBorderLeft(); - - /** - * set the type of border to use for the right border of the cell - * @param border type - * @since POI 3.15 - */ - void setBorderRight(BorderStyle border); - - /** - * get the type of border to use for the right border of the cell - * @return border type - * @since POI 4.0.0 - */ - BorderStyle getBorderRight(); - - /** - * set the type of border to use for the top border of the cell - * @param border type - * @since POI 3.15 - */ - void setBorderTop(BorderStyle border); - - /** - * get the type of border to use for the top border of the cell - * @return border type - * @since POI 4.0.0 - */ - BorderStyle getBorderTop(); - - /** - * set the type of border to use for the bottom border of the cell - * @param border type - * @since POI 3.15 - */ - void setBorderBottom(BorderStyle border); - - /** - * get the type of border to use for the bottom border of the cell - * @return border type - * @since POI 4.0.0 - */ - BorderStyle getBorderBottom(); - - /** - * set the color to use for the left border - * @param color The index of the color definition - */ - void setLeftBorderColor(short color); - - /** - * get the color to use for the left border - */ - short getLeftBorderColor(); - - /** - * set the color to use for the right border - * @param color The index of the color definition - */ - void setRightBorderColor(short color); - - /** - * get the color to use for the left border - * @return the index of the color definition - */ - short getRightBorderColor(); - - /** - * set the color to use for the top border - * @param color The index of the color definition - */ - void setTopBorderColor(short color); - - /** - * get the color to use for the top border - * @return the index of the color definition - */ - short getTopBorderColor(); - - /** - * set the color to use for the bottom border - * @param color The index of the color definition - */ - void setBottomBorderColor(short color); - - /** - * get the color to use for the left border - * @return the index of the color definition - */ - short getBottomBorderColor(); - - /** - * setting to one fills the cell with the foreground color... No idea about - * other values - * - * @param fp fill pattern (set to {@link FillPatternType#SOLID_FOREGROUND} to fill w/foreground color) - * @since POI 3.15 beta 3 - */ - void setFillPattern(FillPatternType fp); - - /** - * Get the fill pattern - * - * @return the fill pattern, default value is {@link FillPatternType#NO_FILL} - * @since POI 4.0.0 - */ - FillPatternType getFillPattern(); - - /** - * set the background fill color. - * - * @param bg color - */ - void setFillBackgroundColor(short bg); - - /** - * get the background fill color, if the fill - * is defined with an indexed color. - * @return fill color index, or 0 if not indexed (XSSF only) - */ - short getFillBackgroundColor(); - - /** - * Gets the color object representing the current - * background fill, resolving indexes using - * the supplied workbook. - * This will work for both indexed and rgb - * defined colors. - */ - Color getFillBackgroundColorColor(); - - /** - * set the foreground fill color - * <i>Note: Ensure Foreground color is set prior to background color.</i> - * @param bg color - */ - void setFillForegroundColor(short bg); - - /** - * get the foreground fill color, if the fill - * is defined with an indexed color. - * @return fill color, or 0 if not indexed (XSSF only) - */ - short getFillForegroundColor(); - - /** - * Gets the color object representing the current - * foreground fill, resolving indexes using - * the supplied workbook. - * This will work for both indexed and rgb - * defined colors. - */ - Color getFillForegroundColorColor(); - - /** - * Clones all the style information from another - * CellStyle, onto this one. This - * CellStyle will then have all the same - * properties as the source, but the two may - * be edited independently. - * Any stylings on this CellStyle will be lost! - * - * The source CellStyle could be from another - * Workbook if you like. This allows you to - * copy styles from one Workbook to another. - * - * However, both of the CellStyles will need - * to be of the same type (HSSFCellStyle or - * XSSFCellStyle) - */ - void cloneStyleFrom(CellStyle source); - - /** - * Controls if the Cell should be auto-sized - * to shrink to fit if the text is too long - */ - void setShrinkToFit(boolean shrinkToFit); - - /** - * Should the Cell be auto-sized by Excel to shrink - * it to fit if this text is too long? - */ - boolean getShrinkToFit(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/CellType.java b/src/java/org/apache/poi/ss/usermodel/CellType.java deleted file mode 100644 index c8e81c9c1a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CellType.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.util.Internal; - -/** - * @since POI 3.15 beta 3 - */ -public enum CellType { - /** - * Unknown type, used to represent a state prior to initialization or the - * lack of a concrete type. - * For internal use only. - */ - @Internal(since="POI 3.15 beta 3") - _NONE(-1), - - /** - * Numeric cell type (whole numbers, fractional numbers, dates) - */ - NUMERIC(0), - - /** String (text) cell type */ - STRING(1), - - /** - * Formula cell type - * @see FormulaType - */ - FORMULA(2), - - /** - * Blank cell type - */ - BLANK(3), - - /** - * Boolean cell type - */ - BOOLEAN(4), - - /** - * Error cell type - * @see FormulaError - */ - ERROR(5); - - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3 - */ - private final int code; - - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3 - */ - private CellType(int code) { - this.code = code; - } - - /** - * @since POI 3.15 beta 3. - * @deprecated POI 3.15 beta 3. Used to transition code from <code>int</code>s to <code>CellType</code>s. - */ - public static CellType forInt(int code) { - for (CellType type : values()) { - if (type.code == code) { - return type; - } - } - throw new IllegalArgumentException("Invalid CellType code: " + code); - } - - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3 - */ - public int getCode() { - return code; - } - -} diff --git a/src/java/org/apache/poi/ss/usermodel/CellValue.java b/src/java/org/apache/poi/ss/usermodel/CellValue.java deleted file mode 100644 index da8b0cc502..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CellValue.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.formula.eval.ErrorEval; - -/** - * Mimics the 'data view' of a cell. This allows formula evaluator - * to return a CellValue instead of precasting the value to String - * or Number or boolean type. - */ -public final class CellValue { - public static final CellValue TRUE = new CellValue(CellType.BOOLEAN, 0.0, true, null, 0); - public static final CellValue FALSE = new CellValue(CellType.BOOLEAN, 0.0, false, null, 0); - - private final CellType _cellType; - private final double _numberValue; - private final boolean _booleanValue; - private final String _textValue; - private final int _errorCode; - - private CellValue(CellType cellType, double numberValue, boolean booleanValue, - String textValue, int errorCode) { - _cellType = cellType; - _numberValue = numberValue; - _booleanValue = booleanValue; - _textValue = textValue; - _errorCode = errorCode; - } - - - public CellValue(double numberValue) { - this(CellType.NUMERIC, numberValue, false, null, 0); - } - - public static CellValue valueOf(boolean booleanValue) { - return booleanValue ? TRUE : FALSE; - } - - public CellValue(String stringValue) { - this(CellType.STRING, 0.0, false, stringValue, 0); - } - - public static CellValue getError(int errorCode) { - return new CellValue(CellType.ERROR, 0.0, false, null, errorCode); - } - - - /** - * @return Returns the booleanValue. - */ - public boolean getBooleanValue() { - return _booleanValue; - } - - /** - * @return Returns the numberValue. - */ - public double getNumberValue() { - return _numberValue; - } - - /** - * @return Returns the stringValue. - */ - public String getStringValue() { - return _textValue; - } - - /** - * Return the cell type. - * - * @return the cell type - */ - public CellType getCellType() { - return _cellType; - } - - /** - * @return Returns the errorValue. - */ - public byte getErrorValue() { - return (byte) _errorCode; - } - - public String toString() { - return getClass().getName() + " [" + - formatAsString() + - "]"; - } - - public String formatAsString() { - switch (_cellType) { - case NUMERIC: - return String.valueOf(_numberValue); - case STRING: - return '"' + _textValue + '"'; - case BOOLEAN: - return _booleanValue ? "TRUE" : "FALSE"; - case ERROR: - return ErrorEval.getText(_errorCode); - default: - return "<error unexpected cell type " + _cellType + ">"; - } - - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/ChildAnchor.java b/src/java/org/apache/poi/ss/usermodel/ChildAnchor.java deleted file mode 100644 index 92a0469e52..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ChildAnchor.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Common interface for anchors.<p> - * - * An anchor is what specifics the position of a shape within a client object - * or within another containing shape. - * - * @since POI 3.16-beta2 - */ -public interface ChildAnchor { - /** - * @return x coordinate of the left up corner - */ - int getDx1(); - - /** - * @param dx1 x coordinate of the left up corner - */ - void setDx1(int dx1); - - /** - * @return y coordinate of the left up corner - */ - int getDy1(); - - /** - * @param dy1 y coordinate of the left up corner - */ - void setDy1(int dy1); - - /** - * @return y coordinate of the right down corner - */ - int getDy2(); - - /** - * @param dy2 y coordinate of the right down corner - */ - void setDy2(int dy2); - - /** - * @return x coordinate of the right down corner - */ - int getDx2(); - - /** - * @param dx2 x coordinate of the right down corner - */ - void setDx2(int dx2); -} diff --git a/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java b/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java deleted file mode 100644 index 77c09c17b0..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java +++ /dev/null @@ -1,274 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Internal; - -/** - * A client anchor is attached to an excel worksheet. It anchors against - * absolute coordinates, a top-left cell and fixed height and width, or - * a top-left and bottom-right cell, depending on the {@link AnchorType}: - * <ol> - * <li> {@link AnchorType#DONT_MOVE_AND_RESIZE} == absolute top-left coordinates and width/height, no cell references - * <li> {@link AnchorType#MOVE_DONT_RESIZE} == fixed top-left cell reference, absolute width/height - * <li> {@link AnchorType#MOVE_AND_RESIZE} == fixed top-left and bottom-right cell references, dynamic width/height - * </ol> - * Note this class only reports the current values for possibly calculated positions and sizes. - * If the sheet row/column sizes or positions shift, this needs updating via external calculations. - * - */ -public interface ClientAnchor { - - /** - * @since POI 3.14beta1 - */ - public static enum AnchorType { - /** - * Move and Resize With Anchor Cells (0) - * <p> - * Specifies that the current drawing shall move and - * resize to maintain its row and column anchors (i.e. the - * object is anchored to the actual from and to row and column) - * </p> - */ - MOVE_AND_RESIZE(0), - - /** - * Don't Move but do Resize With Anchor Cells (1) - * <p> - * Specifies that the current drawing shall not move with its - * row and column, but should be resized. This option is not normally - * used, but is included for completeness. - * </p> - * Note: Excel has no setting for this combination, nor does the ECMA standard. - */ - DONT_MOVE_DO_RESIZE(1), - - /** - * Move With Cells but Do Not Resize (2) - * <p> - * Specifies that the current drawing shall move with its - * row and column (i.e. the object is anchored to the - * actual from row and column), but that the size shall remain absolute. - * </p> - * <p> - * If additional rows/columns are added between the from and to locations of the drawing, - * the drawing shall move its to anchors as needed to maintain this same absolute size. - * </p> - */ - MOVE_DONT_RESIZE(2), - - /** - * Do Not Move or Resize With Underlying Rows/Columns (3) - * <p> - * Specifies that the current start and end positions shall - * be maintained with respect to the distances from the - * absolute start point of the worksheet. - * </p> - * <p> - * If additional rows/columns are added before the - * drawing, the drawing shall move its anchors as needed - * to maintain this same absolute position. - * </p> - */ - DONT_MOVE_AND_RESIZE(3); - - public final short value; - - // disallow non-sequential enum instance creation - private AnchorType(int value) { - this.value = (short) value; - } - - /** - * return the AnchorType corresponding to the code - * - * @param value the anchor type code - * @return the anchor type enum - */ - @Internal - public static AnchorType byId(int value) { - return values()[value]; - } - } - - /** - * Returns the column (0 based) of the first cell, or -1 if there is no top-left anchor cell. - * This is the case for absolute positioning {@link AnchorType#MOVE_AND_RESIZE} - * - * @return 0-based column of the first cell or -1 if none. - */ - public short getCol1(); - - /** - * Sets the column (0 based) of the first cell. - * - * @param col1 0-based column of the first cell. - */ - public void setCol1(int col1); - - /** - * Returns the column (0 based) of the second cell, or -1 if there is no bottom-right anchor cell. - * This is the case for absolute positioning ({@link AnchorType#DONT_MOVE_AND_RESIZE}) - * and absolute sizing ({@link AnchorType#MOVE_DONT_RESIZE}. - * - * @return 0-based column of the second cell or -1 if none. - */ - public short getCol2(); - - /** - * Returns the column (0 based) of the second cell. - * - * @param col2 0-based column of the second cell. - */ - public void setCol2(int col2); - - /** - * Returns the row (0 based) of the first cell, or -1 if there is no bottom-right anchor cell. - * This is the case for absolute positioning ({@link AnchorType#DONT_MOVE_AND_RESIZE}). - * - * @return 0-based row of the first cell or -1 if none. - */ - public int getRow1(); - - /** - * Returns the row (0 based) of the first cell. - * - * @param row1 0-based row of the first cell. - */ - public void setRow1(int row1); - - /** - * Returns the row (0 based) of the second cell, or -1 if there is no bottom-right anchor cell. - * This is the case for absolute positioning ({@link AnchorType#DONT_MOVE_AND_RESIZE}) - * and absolute sizing ({@link AnchorType#MOVE_DONT_RESIZE}. - * - * @return 0-based row of the second cell or -1 if none. - */ - public int getRow2(); - - /** - * Returns the row (0 based) of the first cell. - * - * @param row2 0-based row of the first cell. - */ - public void setRow2(int row2); - - /** - * Returns the x coordinate within the first cell. - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @return the x coordinate within the first cell - */ - public int getDx1(); - - /** - * Sets the x coordinate within the first cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @param dx1 the x coordinate within the first cell - */ - public void setDx1(int dx1); - - /** - * Returns the y coordinate within the first cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @return the y coordinate within the first cell - */ - public int getDy1(); - - /** - * Sets the y coordinate within the first cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @param dy1 the y coordinate within the first cell - */ - public void setDy1(int dy1); - - /** - * Sets the y coordinate within the second cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @return the y coordinate within the second cell - */ - public int getDy2(); - - /** - * Sets the y coordinate within the second cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @param dy2 the y coordinate within the second cell - */ - public void setDy2(int dy2); - - /** - * Returns the x coordinate within the second cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @return the x coordinate within the second cell - */ - public int getDx2(); - - /** - * Sets the x coordinate within the second cell - * - * Note - XSSF and HSSF have a slightly different coordinate - * system, values in XSSF are larger by a factor of - * {@link org.apache.poi.util.Units#EMU_PER_PIXEL} - * - * @param dx2 the x coordinate within the second cell - */ - public void setDx2(int dx2); - - - /** - * Sets the anchor type - * @param anchorType the anchor type to set - * @since POI 3.14 - */ - public void setAnchorType( AnchorType anchorType ); - - /** - * Gets the anchor type - * Changed from returning an int to an enum in POI 3.14 beta 1. - * @return the anchor type - */ - public AnchorType getAnchorType(); - -} diff --git a/src/java/org/apache/poi/ss/usermodel/Color.java b/src/java/org/apache/poi/ss/usermodel/Color.java deleted file mode 100644 index 29555a1849..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Color.java +++ /dev/null @@ -1,21 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -public interface Color { -} diff --git a/src/java/org/apache/poi/ss/usermodel/ColorScaleFormatting.java b/src/java/org/apache/poi/ss/usermodel/ColorScaleFormatting.java deleted file mode 100644 index 8bdbb07355..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ColorScaleFormatting.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.hssf.record.cf.Threshold; - -/** - * High level representation for the Color Scale / Colour Scale / - * Color Gradient Formatting component of Conditional Formatting settings - */ -public interface ColorScaleFormatting { - /** - * How many control points should be used to map - * the colours? Normally 2 or 3 - */ - int getNumControlPoints(); - /** - * Sets the number of control points to use to map - * the colours. Should normally be 2 or 3. - * <p>After updating, you need to ensure that the - * {@link Threshold} count and Color count match - */ - void setNumControlPoints(int num); - - /** - * Gets the list of colours that are interpolated - * between. - */ - Color[] getColors(); - /** - * Sets the list of colours that are interpolated - * between. The number must match {@link #getNumControlPoints()} - */ - void setColors(Color[] colors); - - /** - * Gets the list of thresholds - */ - ConditionalFormattingThreshold[] getThresholds(); - /** - * Sets the of thresholds. The number must match - * {@link #getNumControlPoints()} - */ - void setThresholds(ConditionalFormattingThreshold[] thresholds); - /** - * Creates a new, empty Threshold - */ - ConditionalFormattingThreshold createThreshold(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/Comment.java b/src/java/org/apache/poi/ss/usermodel/Comment.java deleted file mode 100644 index c39040cfe3..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Comment.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.util.CellAddress; - -public interface Comment { - - /** - * Sets whether this comment is visible. - * - * @param visible <code>true</code> if the comment is visible, <code>false</code> otherwise - */ - void setVisible(boolean visible); - - /** - * Returns whether this comment is visible. - * - * @return <code>true</code> if the comment is visible, <code>false</code> otherwise - */ - boolean isVisible(); - - /** - * Get the address of the cell that this comment is attached to - * - * @return comment cell address - * @since 3.15-beta1 - */ - CellAddress getAddress(); - - /** - * Set the address of the cell that this comment is attached to - * - * @param addr - * @since 3.15-beta1 - */ - void setAddress(CellAddress addr); - - /** - * Set the address of the cell that this comment is attached to - * - * @param row - * @param col - * @since 3.15-beta1 - */ - void setAddress(int row, int col); - - /** - * Return the row of the cell that contains the comment - * - * @return the 0-based row of the cell that contains the comment - */ - int getRow(); - - /** - * Set the row of the cell that contains the comment - * - * @param row the 0-based row of the cell that contains the comment - */ - void setRow(int row); - - /** - * Return the column of the cell that contains the comment - * - * @return the 0-based column of the cell that contains the comment - */ - int getColumn(); - - /** - * Set the column of the cell that contains the comment - * - * @param col the 0-based column of the cell that contains the comment - */ - void setColumn(int col); - - /** - * Name of the original comment author - * - * @return the name of the original author of the comment - */ - String getAuthor(); - - /** - * Name of the original comment author - * - * @param author the name of the original author of the comment - */ - void setAuthor(String author); - - /** - * Fetches the rich text string of the comment - */ - public RichTextString getString(); - - /** - * Sets the rich text string used by this comment. - * - * @param string Sets the rich text string used by this object. - */ - void setString(RichTextString string); - - /** - * Return defines position of this anchor in the sheet. - * The anchor is the yellow box/balloon that is rendered on top of the sheets - * when the comment is visible. - * - * To associate a comment with a different cell, use {@link #setAddress}. - * - * @return defines position of this anchor in the sheet - */ - public ClientAnchor getClientAnchor(); -}
\ No newline at end of file diff --git a/src/java/org/apache/poi/ss/usermodel/ComparisonOperator.java b/src/java/org/apache/poi/ss/usermodel/ComparisonOperator.java deleted file mode 100644 index 80f70d315a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ComparisonOperator.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * The conditional format operators used for "Highlight Cells That Contain..." rules. - * <p> - * For example, "highlight cells that begin with "M2" and contain "Mountain Gear". - * </p> - */ -public final class ComparisonOperator { - public static final byte NO_COMPARISON = 0; - - /** - * 'Between' operator - */ - public static final byte BETWEEN = 1; - - /** - * 'Not between' operator - */ - public static final byte NOT_BETWEEN = 2; - - /** - * 'Equal to' operator - */ - public static final byte EQUAL = 3; - - /** - * 'Not equal to' operator - */ - public static final byte NOT_EQUAL = 4; - - /** - * 'Greater than' operator - */ - public static final byte GT = 5; - - /** - * 'Less than' operator - */ - public static final byte LT = 6; - - /** - * 'Greater than or equal to' operator - */ - public static final byte GE = 7; - - /** - * 'Less than or equal to' operator - */ - public static final byte LE = 8; -} diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionFilterData.java b/src/java/org/apache/poi/ss/usermodel/ConditionFilterData.java deleted file mode 100644 index 2d532e31fc..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionFilterData.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * These values are needed by various conditional formatting evaluation filter types - */ -public interface ConditionFilterData { - - /** - * @return true if the flag is missing or set to true - */ - boolean getAboveAverage(); - - /** - * @return true if the flag is set - */ - boolean getBottom(); - - /** - * @return true if the flag is set - */ - boolean getEqualAverage(); - - /** - * @return true if the flag is set - */ - boolean getPercent(); - - /** - * @return value, or 0 if not used/defined - */ - long getRank(); - - /** - * @return value, or 0 if not used/defined - */ - int getStdDev(); - -} diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionFilterType.java b/src/java/org/apache/poi/ss/usermodel/ConditionFilterType.java deleted file mode 100644 index 5f68e689d9..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionFilterType.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * Used primarily for XSSF conditions, which defines a multitude of additional "filter" types - * for conditional formatting. HSSF rules will always be null (not a filter type) or #FILTER. - * XSSF conditions will be null (not a filter type) or any value other than #FILTER. - * <p> - * Instance names match the constants from <code>STCfType</code> for convenience. - */ -public enum ConditionFilterType { - /** This is the only value valid for HSSF rules */ - FILTER, - TOP_10, - UNIQUE_VALUES, - DUPLICATE_VALUES, - CONTAINS_TEXT, - NOT_CONTAINS_TEXT, - BEGINS_WITH, - ENDS_WITH, - CONTAINS_BLANKS, - NOT_CONTAINS_BLANKS, - CONTAINS_ERRORS, - NOT_CONTAINS_ERRORS, - TIME_PERIOD, - ABOVE_AVERAGE, - ; -} diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionType.java b/src/java/org/apache/poi/ss/usermodel/ConditionType.java deleted file mode 100644 index a5681cd4b9..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionType.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Represents a type of a conditional formatting rule - */ -public class ConditionType { - private static Map<Integer,ConditionType> lookup = new HashMap<>(); - - /** - * This conditional formatting rule compares a cell value - * to a formula calculated result, using an operator - */ - public static final ConditionType CELL_VALUE_IS = - new ConditionType(1, "cellIs"); - - /** - * This conditional formatting rule contains a formula to evaluate. - * When the formula result is true, the cell is highlighted. - */ - public static final ConditionType FORMULA = - new ConditionType(2, "expression"); - - /** - * This conditional formatting rule contains a color scale, - * with the cell background set according to a gradient. - */ - public static final ConditionType COLOR_SCALE = - new ConditionType(3, "colorScale"); - - /** - * This conditional formatting rule sets a data bar, with the - * cell populated with bars based on their values - */ - public static final ConditionType DATA_BAR = - new ConditionType(4, "dataBar"); - - /** - * This conditional formatting rule that files the values - */ - public static final ConditionType FILTER = - new ConditionType(5, null); - - /** - * This conditional formatting rule sets a data bar, with the - * cell populated with bars based on their values - */ - public static final ConditionType ICON_SET = - new ConditionType(6, "iconSet"); - - - public final byte id; - public final String type; - - public String toString() { - return id + " - " + type; - } - - - public static ConditionType forId(byte id) { - return forId((int)id); - } - public static ConditionType forId(int id) { - return lookup.get(id); - } - - private ConditionType(int id, String type) { - this.id = (byte)id; this.type = type; - lookup.put(id, this); - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionalFormatting.java b/src/java/org/apache/poi/ss/usermodel/ConditionalFormatting.java deleted file mode 100644 index d7789e14ea..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionalFormatting.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * The ConditionalFormatting class encapsulates all settings of Conditional Formatting. - * - * The class can be used - * - * <UL> - * <LI> - * to make a copy ConditionalFormatting settings. - * </LI> - * - * - * For example: - * <PRE> - * ConditionalFormatting cf = sheet.getConditionalFormattingAt(index); - * newSheet.addConditionalFormatting(cf); - * </PRE> - * - * <LI> - * or to modify existing Conditional Formatting settings (formatting regions and/or rules). - * </LI> - * </UL> - * - * Use {@link org.apache.poi.ss.usermodel.Sheet#getSheetConditionalFormatting()} - * to get access to an instance of this class. - * <P> - * To create a new Conditional Formatting set use the following approach: - * - * <PRE> - * - * // Define a Conditional Formatting rule, which triggers formatting - * // when cell's value is greater or equal than 100.0 and - * // applies patternFormatting defined below. - * ConditionalFormattingRule rule = sheet.createConditionalFormattingRule( - * ComparisonOperator.GE, - * "100.0", // 1st formula - * null // 2nd formula is not used for comparison operator GE - * ); - * - * // Create pattern with red background - * PatternFormatting patternFmt = rule.cretePatternFormatting(); - * patternFormatting.setFillBackgroundColor(IndexedColor.RED.getIndex()); - * - * // Define a region containing first column - * Region [] regions = - * { - * new Region(1,(short)1,-1,(short)1) - * }; - * - * // Apply Conditional Formatting rule defined above to the regions - * sheet.addConditionalFormatting(regions, rule); - * </PRE> - */ -public interface ConditionalFormatting { - - /** - * @return array of <tt>CellRangeAddress</tt>s. Never <code>null</code> - */ - CellRangeAddress[] getFormattingRanges(); - - /** - * Sets the cell ranges the rule conditional formatting must be applied to. - * @param ranges non-null array of <tt>CellRangeAddress</tt>s - */ - void setFormattingRanges(CellRangeAddress[] ranges); - - /** - * Replaces an existing Conditional Formatting rule at position idx. - * Excel pre-2007 allows to create up to 3 Conditional Formatting rules, - * 2007 and later allow unlimited numbers. - * This method can be useful to modify existing Conditional Formatting rules. - * - * @param idx position of the rule. Should be between 0 and 2 for Excel before 2007, otherwise 0+. - * @param cfRule - Conditional Formatting rule - */ - void setRule(int idx, ConditionalFormattingRule cfRule); - - /** - * Add a Conditional Formatting rule. - * Excel pre-2007 allows to create up to 3 Conditional Formatting rules. - * - * @param cfRule - Conditional Formatting rule - */ - void addRule(ConditionalFormattingRule cfRule); - - /** - * @return the Conditional Formatting rule at position idx. - */ - ConditionalFormattingRule getRule(int idx); - - /** - * @return number of Conditional Formatting rules. - */ - int getNumberOfRules(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingRule.java b/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingRule.java deleted file mode 100644 index 2f19d9e3e5..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingRule.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * Represents a description of a conditional formatting rule - */ -public interface ConditionalFormattingRule extends DifferentialStyleProvider { - /** - * Create a new border formatting structure if it does not exist, - * otherwise just return existing object. - * - * @return - border formatting object, never returns <code>null</code>. - */ - BorderFormatting createBorderFormatting(); - - /** - * @return - border formatting object if defined, <code>null</code> otherwise - */ - BorderFormatting getBorderFormatting(); - - /** - * Create a new font formatting structure if it does not exist, - * otherwise just return existing object. - * - * @return - font formatting object, never returns <code>null</code>. - */ - FontFormatting createFontFormatting(); - - /** - * @return - font formatting object if defined, <code>null</code> otherwise - */ - FontFormatting getFontFormatting(); - - /** - * Create a new pattern formatting structure if it does not exist, - * otherwise just return existing object. - * - * @return - pattern formatting object, never returns <code>null</code>. - */ - PatternFormatting createPatternFormatting(); - - /** - * @return - pattern formatting object if defined, <code>null</code> otherwise - */ - PatternFormatting getPatternFormatting(); - - /** - * @return - databar / data-bar formatting object if defined, <code>null</code> otherwise - */ - DataBarFormatting getDataBarFormatting(); - - /** - * @return - icon / multi-state formatting object if defined, <code>null</code> otherwise - */ - IconMultiStateFormatting getMultiStateFormatting(); - - /** - * @return color scale / color grate formatting object if defined, <code>null</code> otherwise - */ - ColorScaleFormatting getColorScaleFormatting(); - - /** - * - * @return number format defined for this rule, or null if the cell default should be used - */ - ExcelNumberFormat getNumberFormat(); - - /** - * Type of conditional formatting rule. - * - * @return the type of condition - */ - ConditionType getConditionType(); - - /** - * This is null if - * <p> - * <code>{@link #getConditionType()} != {@link ConditionType#FILTER}</code> - * <p> - * This is always {@link ConditionFilterType#FILTER} for HSSF rules of type {@link ConditionType#FILTER}. - * <p> - * For XSSF filter rules, this will indicate the specific type of filter. - * - * @return filter type for filter rules, or null if not a filter rule. - */ - ConditionFilterType getConditionFilterType(); - - /** - * This is null if - * <p> - * <code>{@link #getConditionFilterType()} == null</code> - * <p> - * This means it is always null for HSSF, which does not define the extended condition types. - * <p> - * This object contains the additional configuration information for XSSF filter conditions. - * - * @return the Filter Configuration Data, or null if there isn't any - */ - public ConditionFilterData getFilterConfiguration(); - - /** - * The comparison function used when the type of conditional formatting is set to - * {@link ConditionType#CELL_VALUE_IS} - * <p> - * MUST be a constant from {@link ComparisonOperator} - * </p> - * - * @return the conditional format operator - */ - byte getComparisonOperation(); - - /** - * The formula used to evaluate the first operand for the conditional formatting rule. - * <p> - * If the condition type is {@link ConditionType#CELL_VALUE_IS}, - * this field is the first operand of the comparison. - * If type is {@link ConditionType#FORMULA}, this formula is used - * to determine if the conditional formatting is applied. - * </p> - * <p> - * If comparison type is {@link ConditionType#FORMULA} the formula MUST be a Boolean function - * </p> - * - * @return the first formula - */ - String getFormula1(); - - /** - * The formula used to evaluate the second operand of the comparison when - * comparison type is {@link ConditionType#CELL_VALUE_IS} and operator - * is either {@link ComparisonOperator#BETWEEN} or {@link ComparisonOperator#NOT_BETWEEN} - * - * @return the second formula - */ - String getFormula2(); - - /** - * XSSF rules store textual condition values as an attribute and also as a formula that needs shifting. Using the attribute is simpler/faster. - * HSSF rules don't have this and return null. We can fall back on the formula for those (AFAIK). - * @return condition text if it exists, or null - */ - String getText(); - - /** - * The priority of the rule, if defined, otherwise 0. - * <p> - * If priority is 0, just use definition order, as that's how older HSSF rules - * are evaluated. - * <p> - * For XSSF, this should always be set. For HSSF, only newer style rules - * have this set, older ones will return 0. - * <p> - * If a rule is created but not yet added to a sheet, this value may not be valid. - * @return rule priority - */ - int getPriority(); - - /** - * Always true for HSSF rules, optional flag for XSSF rules. - * See Excel help for more. - * - * @return true if conditional formatting rule processing stops when this one is true, false if not - * @see <a href="https://support.office.com/en-us/article/Manage-conditional-formatting-rule-precedence-063cde21-516e-45ca-83f5-8e8126076249">Microsoft Excel help</a> - */ - boolean getStopIfTrue(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingRule.java.svntmp b/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingRule.java.svntmp deleted file mode 100644 index 5e534442e0..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingRule.java.svntmp +++ /dev/null @@ -1,169 +0,0 @@ -/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * 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.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ====================================================================
- */
-
-package org.apache.poi.ss.usermodel;
-
-/**
- * Represents a description of a conditional formatting rule
- */
-public interface ConditionalFormattingRule {
- /**
- * Create a new border formatting structure if it does not exist,
- * otherwise just return existing object.
- *
- * @return - border formatting object, never returns <code>null</code>.
- */
- BorderFormatting createBorderFormatting();
-
- /**
- * @return - border formatting object if defined, <code>null</code> otherwise
- */
- BorderFormatting getBorderFormatting();
-
- /**
- * Create a new font formatting structure if it does not exist,
- * otherwise just return existing object.
- *
- * @return - font formatting object, never returns <code>null</code>.
- */
- FontFormatting createFontFormatting();
-
- /**
- * @return - font formatting object if defined, <code>null</code> otherwise
- */
- FontFormatting getFontFormatting();
-
- /**
- * Create a new pattern formatting structure if it does not exist,
- * otherwise just return existing object.
- *
- * @return - pattern formatting object, never returns <code>null</code>.
- */
- PatternFormatting createPatternFormatting();
-
- /**
- * @return - pattern formatting object if defined, <code>null</code> otherwise
- */
- PatternFormatting getPatternFormatting();
-
- /**
- * @return - databar / data-bar formatting object if defined, <code>null</code> otherwise
- */
- DataBarFormatting getDataBarFormatting();
-
- /**
- * @return - icon / multi-state formatting object if defined, <code>null</code> otherwise
- */
- IconMultiStateFormatting getMultiStateFormatting();
-
- /**
- * @return color scale / color grate formatting object if defined, <code>null</code> otherwise
- */
- ColorScaleFormatting getColorScaleFormatting();
-
- /**
- * Type of conditional formatting rule.
- *
- * @return the type of condition
- */
- ConditionType getConditionType();
-
- /**
- * This is null if
- * <p>
- * <code>{@link #getConditionType()} != {@link ConditionType#FILTER}</code>
- * <p>
- * This is always {@link ConditionFilterType#FILTER} for HSSF rules of type {@link ConditionType#FILTER}.
- * <p>
- * For XSSF filter rules, this will indicate the specific type of filter.
- *
- * @return filter type for filter rules, or null if not a filter rule.
- */
- ConditionFilterType getConditionFilterType();
-
- /**
- * This is null if
- * <p>
- * <code>{@link #getConditionFilterType()} == null</code>
- * <p>
- * This means it is always null for HSSF, which does not define the extended condition types.
- * <p>
- * This object contains the additional configuration information for XSSF filter conditions.
- *
- * @return
- */
- public ConditionFilterData getFilterConfiguration();
-
- /**
- * The comparison function used when the type of conditional formatting is set to
- * {@link ConditionType#CELL_VALUE_IS}
- * <p>
- * MUST be a constant from {@link ComparisonOperator}
- * </p>
- *
- * @return the conditional format operator
- */
- byte getComparisonOperation();
-
- /**
- * The formula used to evaluate the first operand for the conditional formatting rule.
- * <p>
- * If the condition type is {@link ConditionType#CELL_VALUE_IS},
- * this field is the first operand of the comparison.
- * If type is {@link ConditionType#FORMULA}, this formula is used
- * to determine if the conditional formatting is applied.
- * </p>
- * <p>
- * If comparison type is {@link ConditionType#FORMULA} the formula MUST be a Boolean function
- * </p>
- *
- * @return the first formula
- */
- String getFormula1();
-
- /**
- * The formula used to evaluate the second operand of the comparison when
- * comparison type is {@link ConditionType#CELL_VALUE_IS} and operator
- * is either {@link ComparisonOperator#BETWEEN} or {@link ComparisonOperator#NOT_BETWEEN}
- *
- * @return the second formula
- */
- String getFormula2();
-
- /**
- * HSSF just returns 0, XSSF uses the value stored in the model if present,
- * otherwise uses 0.
- * <p>
- * If priority is 0, just use definition order, as that's how HSSF rules are evaluated.
- * <p>
- * If a rule is created but not yet added to a sheet, this value may not be valid.
-
- * @return rule priority
- */
- int getPriority();
-
- /**
- * Always true for HSSF rules, optional flag for XSSF rules.
- * See Excel help for more.
- *
- * @return true if conditional formatting rule processing stops when this one is true, false if not
- * @see <a href="https://support.office.com/en-us/article/Manage-conditional-formatting-rule-precedence-063cde21-516e-45ca-83f5-8e8126076249">Microsoft Excel help</a>
- */
- boolean getStopIfTrue();
-}
diff --git a/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java b/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java deleted file mode 100644 index c70e3d1d24..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - - -/** - * The Threshold / CFVO / Conditional Formatting Value Object. - * <p>This defines how to calculate the ranges for a conditional - * formatting rule, eg which values get a Green Traffic Light - * icon and which Yellow or Red.</p> - */ -public interface ConditionalFormattingThreshold { - public enum RangeType { - /** Number / Parameter */ - NUMBER(1, "num"), - /** The minimum value from the range */ - MIN(2, "min"), - /** The maximum value from the range */ - MAX(3, "max"), - /** Percent of the way from the mi to the max value in the range */ - PERCENT(4, "percent"), - /** The minimum value of the cell that is in X percentile of the range */ - PERCENTILE(5, "percentile"), - UNALLOCATED(6, null), - /** Formula result */ - FORMULA(7, "formula"); - - /** Numeric ID of the type */ - public final int id; - /** Name (system) of the type */ - public final String name; - - public String toString() { - return id + " - " + name; - } - - public static RangeType byId(int id) { - return values()[id-1]; // 1-based IDs - } - public static RangeType byName(String name) { - for (RangeType t : values()) { - if (t.name.equals(name)) return t; - } - return null; - } - - private RangeType(int id, String name) { - this.id = id; this.name = name; - } - } - - /** - * Get the Range Type used - */ - RangeType getRangeType(); - - /** - * Changes the Range Type used - * - * <p>If you change the range type, you need to - * ensure that the Formula and Value parameters - * are compatible with it before saving</p> - */ - void setRangeType(RangeType type); - - /** - * Formula to use to calculate the threshold, - * or <code>null</code> if no formula - */ - String getFormula(); - - /** - * Sets the formula used to calculate the threshold, - * or unsets it if <code>null</code> is given. - */ - void setFormula(String formula); - - /** - * Gets the value used for the threshold, or - * <code>null</code> if there isn't one. - */ - Double getValue(); - - /** - * Sets the value used for the threshold. - * <p>If the type is {@link RangeType#PERCENT} or - * {@link RangeType#PERCENTILE} it must be between 0 and 100. - * <p>If the type is {@link RangeType#MIN} or {@link RangeType#MAX} - * or {@link RangeType#FORMULA} it shouldn't be set. - * <p>Use <code>null</code> to unset - */ - void setValue(Double value); -} diff --git a/src/java/org/apache/poi/ss/usermodel/CreationHelper.java b/src/java/org/apache/poi/ss/usermodel/CreationHelper.java deleted file mode 100644 index 004025db10..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/CreationHelper.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; - -/** - * An object that handles instantiating concrete - * classes of the various instances one needs for - * HSSF and XSSF. - * Works around a limitation in Java where we - * cannot have static methods on interfaces or abstract - * classes. - * This allows you to get the appropriate class for - * a given interface, without you having to worry - * about if you're dealing with HSSF or XSSF. - */ -public interface CreationHelper { - /** - * Creates a new RichTextString instance - * @param text The text to initialise the RichTextString with - */ - RichTextString createRichTextString(String text); - - /** - * Creates a new DataFormat instance - */ - DataFormat createDataFormat(); - - /** - * Creates a new Hyperlink, of the given type - */ - Hyperlink createHyperlink(HyperlinkType type); - - /** - * Creates FormulaEvaluator - an object that evaluates formula cells. - * - * @return a FormulaEvaluator instance - */ - FormulaEvaluator createFormulaEvaluator(); - - /** - * Creates a XSSF-style Color object, used for extended sheet - * formattings and conditional formattings - */ - ExtendedColor createExtendedColor(); - - /** - * Creates a ClientAnchor. Use this object to position drawing object in a sheet - * - * @return a ClientAnchor instance - * @see org.apache.poi.ss.usermodel.Drawing - */ - ClientAnchor createClientAnchor(); - - /** - * Creates an AreaReference. - * - * @param reference cell reference - * @return an AreaReference instance - */ - AreaReference createAreaReference(String reference); - - /** - * Creates an area ref from a pair of Cell References.. - * - * @param topLeft cell reference - * @param bottomRight cell reference - * @return an AreaReference instance - */ - AreaReference createAreaReference(CellReference topLeft, CellReference bottomRight); - -} diff --git a/src/java/org/apache/poi/ss/usermodel/DataBarFormatting.java b/src/java/org/apache/poi/ss/usermodel/DataBarFormatting.java deleted file mode 100644 index bcdd34a6d2..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataBarFormatting.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * High level representation for the DataBar Formatting - * component of Conditional Formatting settings - */ -public interface DataBarFormatting { - /** - * Is the bar drawn from Left-to-Right, or from - * Right-to-Left - */ - boolean isLeftToRight(); - /** - * Control if the bar is drawn from Left-to-Right, - * or from Right-to-Left - */ - void setLeftToRight(boolean ltr); - - /** - * Should Icon + Value be displayed, or only the Icon? - */ - boolean isIconOnly(); - /** - * Control if only the Icon is shown, or Icon + Value - */ - void setIconOnly(boolean only); - - /** - * How much of the cell width, in %, should be given to - * the min value? - */ - int getWidthMin(); - void setWidthMin(int width); - - /** - * How much of the cell width, in %, should be given to - * the max value? - */ - int getWidthMax(); - void setWidthMax(int width); - - Color getColor(); - void setColor(Color color); - - /** - * The threshold that defines "everything from here down is minimum" - */ - ConditionalFormattingThreshold getMinThreshold(); - /** - * The threshold that defines "everything from here up is maximum" - */ - ConditionalFormattingThreshold getMaxThreshold(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/DataConsolidateFunction.java b/src/java/org/apache/poi/ss/usermodel/DataConsolidateFunction.java deleted file mode 100644 index d40a8d11c5..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataConsolidateFunction.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Beta; - -/** - * Enum mapping the values of STDataConsolidateFunction - */ -@Beta -public enum DataConsolidateFunction { - AVERAGE(1,"Average"), - COUNT(2, "Count"), - COUNT_NUMS(3, "Count"), - MAX(4, "Max"), - MIN(5, "Min"), - PRODUCT(6, "Product"), - STD_DEV(7, "StdDev"), - STD_DEVP(8, "StdDevp"), - SUM(9, "Sum"), - VAR(10, "Var"), - VARP(11, "Varp"); - - private final int value; - private final String name; - - DataConsolidateFunction(int value, String name) { - this.value = value; - this.name = name; - } - - public String getName() { - return this.name; - } - - public int getValue() { - return this.value; - } -}
\ No newline at end of file diff --git a/src/java/org/apache/poi/ss/usermodel/DataFormat.java b/src/java/org/apache/poi/ss/usermodel/DataFormat.java deleted file mode 100644 index 3728541ef6..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataFormat.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -public interface DataFormat { - /** - * get the format index that matches the given format string. - * Creates a new format if one is not found. Aliases text to the proper format. - * @param format string matching a built in format - * @return index of format. - */ - short getFormat(String format); - - /** - * get the format string that matches the given format index - * @param index of a format - * @return string represented at index of format or null if there is not a format at that index - */ - String getFormat(short index); -}
\ No newline at end of file diff --git a/src/java/org/apache/poi/ss/usermodel/DataFormatter.java b/src/java/org/apache/poi/ss/usermodel/DataFormatter.java deleted file mode 100644 index 78bbd79b55..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataFormatter.java +++ /dev/null @@ -1,1326 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.beans.PropertyChangeSupport; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.FieldPosition; -import java.text.Format; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.format.CellFormatResult; -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.ss.util.DateFormatConverter; -import org.apache.poi.ss.util.NumberToTextConverter; -import org.apache.poi.util.LocaleUtil; - - -/** - * DataFormatter contains methods for formatting the value stored in an - * Cell. This can be useful for reports and GUI presentations when you - * need to display data exactly as it appears in Excel. Supported formats - * include currency, SSN, percentages, decimals, dates, phone numbers, zip - * codes, etc. - * <p> - * Internally, formats will be implemented using subclasses of {@link Format} - * such as {@link DecimalFormat} and {@link SimpleDateFormat}. Therefore the - * formats used by this class must obey the same pattern rules as these Format - * subclasses. This means that only legal number pattern characters ("0", "#", - * ".", "," etc.) may appear in number formats. Other characters can be - * inserted <em>before</em> or <em> after</em> the number pattern to form a - * 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 - * 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 - * 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> - * <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 - * default format will only be used when a Format cannot be created from the - * cell's data format string. - * - * <p> - * Note that by default formatted numeric values are trimmed. - * Excel formats can contain spacers and padding and the default behavior is to strip them off. - * </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>. - * </p> - * You can enable spaces by passing the <code>emulateCSV=true</code> flag in the <code>DateFormatter</code> 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". - * </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. - * These locale directives are (currently) ignored. - * You can use {@link DateFormatConverter} to do some of this localisation if - * you need it. - */ -@SuppressWarnings("unused") -public class DataFormatter { - private static final String defaultFractionWholePartFormat = "#"; - private static final String defaultFractionFractionPartFormat = "#/##"; - /** Pattern to find a number format: "0" or "#" */ - private static final Pattern numPattern = Pattern.compile("[0#]+"); - - /** Pattern to find days of week as text "ddd...." */ - private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE); - - /** Pattern to find "AM/PM" marker */ - private static final Pattern amPmPattern = Pattern.compile("(([AP])[M/P]*)", Pattern.CASE_INSENSITIVE); - - /** Pattern to find formats with condition ranges e.g. [>=100] */ - private static final Pattern rangeConditionalPattern = Pattern.compile(".*\\[\\s*(>|>=|<|<=|=)\\s*[0-9]*\\.*[0-9].*"); - - /** - * A regex to find locale patterns like [$$-1009] and [$?-452]. - * Note that we don't currently process these into locales - */ - private static final Pattern localePatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+])"); - - /** - * A regex to match the colour formattings rules. - * Allowed colours are: Black, Blue, Cyan, Green, - * Magenta, Red, White, Yellow, "Color n" (1<=n<=56) - */ - private static final Pattern colorPattern = - Pattern.compile("(\\[BLACK])|(\\[BLUE])|(\\[CYAN])|(\\[GREEN])|" + - "(\\[MAGENTA])|(\\[RED])|(\\[WHITE])|(\\[YELLOW])|" + - "(\\[COLOR\\s*\\d])|(\\[COLOR\\s*[0-5]\\d])", Pattern.CASE_INSENSITIVE); - - /** - * A regex to identify a fraction pattern. - * This requires that replaceAll("\\?", "#") has already been called - */ - private static final Pattern fractionPattern = Pattern.compile("(?:([#\\d]+)\\s+)?(#+)\\s*/\\s*([#\\d]+)"); - - /** - * A regex to strip junk out of fraction formats - */ - private static final Pattern fractionStripper = Pattern.compile("(\"[^\"]*\")|([^ ?#\\d/]+)"); - - /** - * A regex to detect if an alternate grouping character is used - * in a numeric format - */ - private static final Pattern alternateGrouping = Pattern.compile("([#0]([^.#0])[#0]{3})"); - - /** - * Cells formatted with a date or time format and which contain invalid date or time values - * show 255 pound signs ("#"). - */ - private static final String invalidDateTimeString; - static { - StringBuilder buf = new StringBuilder(); - for(int i = 0; i < 255; i++) buf.append('#'); - invalidDateTimeString = buf.toString(); - } - - /** - * The decimal symbols of the locale used for formatting values. - */ - private DecimalFormatSymbols decimalSymbols; - - /** - * The date symbols of the locale used for formatting values. - */ - private DateFormatSymbols dateSymbols; - - /** - * A default date format, if no date format was given - */ - private DateFormat defaultDateformat; - - /** <em>General</em> format for numbers. */ - private Format generalNumberFormat; - - /** A default format to use when a number pattern cannot be parsed. */ - private Format defaultNumFormat; - - /** - * A map to cache formats. - * Map<String,Format> formats - */ - private final Map<String,Format> formats = new HashMap<>(); - - private final boolean emulateCSV; - - /** stores the locale valid it the last formatting call */ - private Locale locale; - - /** stores if the locale should change according to {@link LocaleUtil#getUserLocale()} */ - private boolean localeIsAdapting; - - // contain a support object instead of extending the support class - private final PropertyChangeSupport pcs; - - /** For logging any problems we find */ - private static final Logger LOG = LogManager.getLogger(DataFormatter.class); - - /** - * Creates a formatter using the {@link Locale#getDefault() default locale}. - */ - public DataFormatter() { - this(false); - } - - /** - * Creates a formatter using the {@link Locale#getDefault() default locale}. - * - * @param emulateCSV whether to emulate CSV output. - */ - public DataFormatter(boolean emulateCSV) { - this(LocaleUtil.getUserLocale(), true, emulateCSV); - } - - /** - * Creates a formatter using the given locale. - */ - public DataFormatter(Locale locale) { - this(locale, false); - } - - /** - * Creates a formatter using the given locale. - * - * @param emulateCSV whether to emulate CSV output. - */ - public DataFormatter(Locale locale, boolean emulateCSV) { - this(locale, false, emulateCSV); - } - - /** - * Creates a formatter using the given locale. - * @param localeIsAdapting (true only if locale is not user-specified) - * @param emulateCSV whether to emulate CSV output. - */ - public DataFormatter(Locale locale, boolean localeIsAdapting, boolean emulateCSV) { - this.localeIsAdapting = true; - pcs = new PropertyChangeSupport(this); - // localeIsAdapting must be true prior to this first checkForLocaleChange call. - checkForLocaleChange(locale); - // set localeIsAdapting so subsequent checks perform correctly - // (whether a specific locale was provided to this DataFormatter or DataFormatter should - // adapt to the current user locale as the locale changes) - this.localeIsAdapting = localeIsAdapting; - this.emulateCSV = emulateCSV; - } - - /** - * 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 - * following is true: - * <ul> - * <li>the cell's style is null</li> - * <li>the style's data format string is null or empty</li> - * <li>the format string cannot be recognized as either a number or date</li> - * </ul> - * - * @param cell The cell to retrieve a Format for - * @return A Format for the format String - */ - private Format getFormat(Cell cell, ConditionalFormattingEvaluator cfEvaluator) { - if (cell == null) return null; - - ExcelNumberFormat numFmt = ExcelNumberFormat.from(cell, cfEvaluator); - - if ( numFmt == null) { - return null; - } - - int formatIndex = numFmt.getIdx(); - String formatStr = numFmt.getFormat(); - if(formatStr == null || formatStr.trim().length() == 0) { - return null; - } - return getFormat(cell.getNumericCellValue(), formatIndex, formatStr, isDate1904(cell)); - } - - private boolean isDate1904(Cell cell) { - if ( cell != null && cell.getSheet().getWorkbook() instanceof Date1904Support) { - return ((Date1904Support)cell.getSheet().getWorkbook()).isDate1904(); - - } - return false; - } - - private Format getFormat(double cellValue, int formatIndex, String formatStrIn, boolean use1904Windowing) { - checkForLocaleChange(); - - // Might be better to separate out the n p and z formats, falling back to p when n and z are not set. - // That however would require other code to be re factored. - // String[] formatBits = formatStrIn.split(";"); - // int i = cellValue > 0.0 ? 0 : cellValue < 0.0 ? 1 : 2; - // String formatStr = (i < formatBits.length) ? formatBits[i] : formatBits[0]; - - String formatStr = formatStrIn; - - // Excel supports 2+ part conditional data formats, eg positive/negative/zero, - // or (>1000),(>0),(0),(negative). As Java doesn't handle these kinds - // of different formats for different ranges, just +ve/-ve, we need to - // handle these ourselves in a special way. - // For now, if we detect 2+ parts, we call out to CellFormat to handle it - // TODO Going forward, we should really merge the logic between the two classes - if (formatStr.contains(";") && - (formatStr.indexOf(';') != formatStr.lastIndexOf(';') - || rangeConditionalPattern.matcher(formatStr).matches() - ) ) { - try { - // Ask CellFormat to get a formatter for it - CellFormat cfmt = CellFormat.getInstance(locale, formatStr); - // CellFormat requires callers to identify date vs not, so do so - // don't try to handle Date value 0, let a 3 or 4-part format take care of it - Object cellValueO = (cellValue != 0.0 && DateUtil.isADateFormat(formatIndex, formatStr)) - ? DateUtil.getJavaDate(cellValue, use1904Windowing) - : cellValue; - // Wrap and return (non-cacheable - CellFormat does that) - return new CellFormatResultWrapper( cfmt.apply(cellValueO) ); - } catch (Exception e) { - LOG.atWarn().withThrowable(e).log("Formatting failed for format {}, falling back", formatStr); - } - } - - // Excel's # with value 0 will output empty where Java will output 0. This hack removes the # from the format. - if (emulateCSV && cellValue == 0.0 && formatStr.contains("#") && !formatStr.contains("0")) { - formatStr = formatStr.replace("#", ""); - } - - // See if we already have it cached - Format format = formats.get(formatStr); - if (format != null) { - return format; - } - - // Is it one of the special built in types, General or @? - if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) { - return generalNumberFormat; - } - - // Build a formatter, and cache it - format = createFormat(cellValue, formatIndex, formatStr); - formats.put(formatStr, format); - return format; - } - - /** - * Create and return a Format based on the format string from a cell's - * style. If the pattern cannot be parsed, return a default pattern. - * - * @param cell The Excel cell - * @return A Format representing the excel format. May return null. - */ - public Format createFormat(Cell cell) { - - int formatIndex = cell.getCellStyle().getDataFormat(); - String formatStr = cell.getCellStyle().getDataFormatString(); - return createFormat(cell.getNumericCellValue(), formatIndex, formatStr); - } - - private Format createFormat(double cellValue, int formatIndex, String sFormat) { - checkForLocaleChange(); - - String formatStr = sFormat; - - // Remove colour formatting if present - if (formatStr != null) { - Matcher colourM = colorPattern.matcher(formatStr); - while (colourM.find()) { - String colour = colourM.group(); - - // Paranoid replacement... - int at = formatStr.indexOf(colour); - if (at == -1) break; - String nFormatStr = formatStr.substring(0, at) + - formatStr.substring(at + colour.length()); - if (nFormatStr.equals(formatStr)) break; - - // Try again in case there's multiple - formatStr = nFormatStr; - colourM = colorPattern.matcher(formatStr); - } - } - - // Strip off the locale information, we use an instance-wide locale for everything - if (formatStr != null) { - Matcher m = localePatternGroup.matcher(formatStr); - while (m.find()) { - String match = m.group(); - String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-')); - if (symbol.indexOf('$') > -1) { - symbol = symbol.substring(0, symbol.indexOf('$')) + - '\\' + - symbol.substring(symbol.indexOf('$')); - } - formatStr = m.replaceAll(symbol); - m = localePatternGroup.matcher(formatStr); - } - } - - // Check for special cases - if(formatStr == null || formatStr.trim().isEmpty()) { - return getDefaultFormat(cellValue); - } - - if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) { - return generalNumberFormat; - } - - if(DateUtil.isADateFormat(formatIndex,formatStr) && - DateUtil.isValidExcelDate(cellValue)) { - return createDateFormat(formatStr, cellValue); - } - // Excel supports fractions in format strings, which Java doesn't - if (formatStr.contains("#/") || formatStr.contains("?/")) { - String[] chunks = formatStr.split(";"); - for (String chunk1 : chunks) { - String chunk = chunk1.replaceAll("\\?", "#"); - Matcher matcher = fractionStripper.matcher(chunk); - chunk = matcher.replaceAll(" "); - chunk = chunk.replaceAll(" +", " "); - Matcher fractionMatcher = fractionPattern.matcher(chunk); - //take the first match - if (fractionMatcher.find()) { - String wholePart = (fractionMatcher.group(1) == null) ? "" : defaultFractionWholePartFormat; - return new FractionFormat(wholePart, fractionMatcher.group(3)); - } - } - - // Strip custom text in quotes and escaped characters for now as it can cause performance problems in fractions. - //String strippedFormatStr = formatStr.replaceAll("\\\\ ", " ").replaceAll("\\\\.", "").replaceAll("\"[^\"]*\"", " ").replaceAll("\\?", "#"); - return new FractionFormat(defaultFractionWholePartFormat, defaultFractionFractionPartFormat); - } - - if (numPattern.matcher(formatStr).find()) { - return createNumberFormat(formatStr, cellValue); - } - - if (emulateCSV) { - return new ConstantStringFormat(cleanFormatForNumber(formatStr)); - } - // TODO - when does this occur? - return null; - } - - - - private Format createDateFormat(String pFormatStr, double cellValue) { - String formatStr = pFormatStr; - formatStr = formatStr.replace("\\-","-"); - formatStr = formatStr.replace("\\,",","); - formatStr = formatStr.replace("\\.","."); // . is a special regexp char - formatStr = formatStr.replace("\\ "," "); - formatStr = formatStr.replace("\\/","/"); // weird: m\\/d\\/yyyy - formatStr = formatStr.replace(";@", ""); - formatStr = formatStr.replace("\"/\"", "/"); // "/" is escaped for no reason in: mm"/"dd"/"yyyy - formatStr = formatStr.replace("\"\"", "'"); // replace Excel quoting with Java style quoting - formatStr = formatStr.replace("\\T","'T'"); // Quote the T is iso8601 style dates - - - boolean hasAmPm = false; - Matcher amPmMatcher = amPmPattern.matcher(formatStr); - while (amPmMatcher.find()) { - formatStr = amPmMatcher.replaceAll("@"); - hasAmPm = true; - amPmMatcher = amPmPattern.matcher(formatStr); - } - formatStr = formatStr.replace('@', 'a'); - - - Matcher dateMatcher = daysAsText.matcher(formatStr); - if (dateMatcher.find()) { - String match = dateMatcher.group(0).toUpperCase(Locale.ROOT).replace('D', 'E'); - formatStr = dateMatcher.replaceAll(match); - } - - // Convert excel date format to SimpleDateFormat. - // Excel uses lower and upper case 'm' for both minutes and months. - // From Excel help: - /* - The "m" or "mm" code must appear immediately after the "h" or"hh" - code or immediately before the "ss" code; otherwise, Microsoft - Excel displays the month instead of minutes." - */ - - StringBuilder sb = new StringBuilder(); - char[] chars = formatStr.toCharArray(); - boolean mIsMonth = true; - List<Integer> ms = new ArrayList<>(); - boolean isElapsed = false; - for(int j=0; j<chars.length; j++) { - char c = chars[j]; - if (c == '\'') { - sb.append(c); - j++; - - // skip until the next quote - while(j<chars.length) { - c = chars[j]; - sb.append(c); - if(c == '\'') { - break; - } - j++; - } - } - else if (c == '[' && !isElapsed) { - isElapsed = true; - mIsMonth = false; - sb.append(c); - } - else if (c == ']' && isElapsed) { - isElapsed = false; - sb.append(c); - } - else if (isElapsed) { - if (c == 'h' || c == 'H') { - sb.append('H'); - } - else if (c == 'm' || c == 'M') { - sb.append('m'); - } - else if (c == 's' || c == 'S') { - sb.append('s'); - } - else { - sb.append(c); - } - } - else if (c == 'h' || c == 'H') { - mIsMonth = false; - if (hasAmPm) { - sb.append('h'); - } else { - sb.append('H'); - } - } - else if (c == 'm' || c == 'M') { - if(mIsMonth) { - sb.append('M'); - ms.add(sb.length() - 1); - } else { - sb.append('m'); - } - } - else if (c == 's' || c == 'S') { - sb.append('s'); - // if 'M' precedes 's' it should be minutes ('m') - for (int index : ms) { - if (sb.charAt(index) == 'M') { - sb.replace(index, index + 1, "m"); - } - } - mIsMonth = true; - ms.clear(); - } - else if (Character.isLetter(c)) { - mIsMonth = true; - ms.clear(); - if (c == 'y' || c == 'Y') { - sb.append('y'); - } - else if (c == 'd' || c == 'D') { - sb.append('d'); - } - else { - sb.append(c); - } - } - else { - if (Character.isWhitespace(c)){ - ms.clear(); - } - sb.append(c); - } - } - formatStr = sb.toString(); - - try { - return new ExcelStyleDateFormatter(formatStr, dateSymbols); - } catch(IllegalArgumentException iae) { - LOG.atDebug().withThrowable(iae).log("Formatting failed for format {}, falling back", formatStr); - // the pattern could not be parsed correctly, - // so fall back to the default number format - return getDefaultFormat(cellValue); - } - - } - - private String cleanFormatForNumber(String formatStr) { - StringBuilder sb = new StringBuilder(formatStr); - - if (emulateCSV) { - // Requested spacers with "_" are replaced by a single space. - // Full-column-width padding "*" are removed. - // Not processing fractions at this time. Replace ? with space. - // This matches CSV output. - for (int i = 0; i < sb.length(); i++) { - char c = sb.charAt(i); - if (c == '_' || c == '*' || c == '?') { - if (i > 0 && sb.charAt((i - 1)) == '\\') { - // It's escaped, don't worry - continue; - } - if (c == '?') { - sb.setCharAt(i, ' '); - } else if (i < sb.length() - 1) { - // Remove the character we're supposed - // to match the space of / pad to the - // column width with - if (c == '_') { - sb.setCharAt(i + 1, ' '); - } else { - sb.deleteCharAt(i + 1); - } - // Remove the character too - sb.deleteCharAt(i); - i--; - } - } - } - } else { - // If they requested spacers, with "_", - // remove those as we don't do spacing - // If they requested full-column-width - // padding, with "*", remove those too - for (int i = 0; i < sb.length(); i++) { - char c = sb.charAt(i); - if (c == '_' || c == '*') { - if (i > 0 && sb.charAt((i - 1)) == '\\') { - // It's escaped, don't worry - continue; - } - if (i < sb.length() - 1) { - // Remove the character we're supposed - // to match the space of / pad to the - // column width with - sb.deleteCharAt(i + 1); - } - // Remove the _ too - sb.deleteCharAt(i); - i--; - } - } - } - - // Now, handle the other aspects like - // quoting and scientific notation - for(int i = 0; i < sb.length(); i++) { - char c = sb.charAt(i); - // remove quotes and back slashes - if (c == '\\' || c == '"') { - sb.deleteCharAt(i); - i--; - - // for scientific/engineering notation - } else if ((c == '+' || c == '-') && i > 0 && sb.charAt(i - 1) == 'E') { - sb.deleteCharAt(i); - i--; - } - } - - return sb.toString(); - } - - private static class InternalDecimalFormatWithScale extends Format { - - private static final Pattern endsWithCommas = Pattern.compile("(,+)$"); - private BigDecimal divider; - private static final BigDecimal ONE_THOUSAND = new BigDecimal(1000); - private final DecimalFormat df; - private static String trimTrailingCommas(String s) { - return s.replaceAll(",+$", ""); - } - - public InternalDecimalFormatWithScale(String pattern, DecimalFormatSymbols symbols) { - df = new DecimalFormat(trimTrailingCommas(pattern), symbols); - setExcelStyleRoundingMode(df); - Matcher endsWithCommasMatcher = endsWithCommas.matcher(pattern); - if (endsWithCommasMatcher.find()) { - String commas = (endsWithCommasMatcher.group(1)); - BigDecimal temp = BigDecimal.ONE; - for (int i = 0; i < commas.length(); ++i) { - temp = temp.multiply(ONE_THOUSAND); - } - divider = temp; - } else { - divider = null; - } - } - - private Object scaleInput(Object obj) { - if (divider != null) { - if (obj instanceof BigDecimal) { - obj = ((BigDecimal) obj).divide(divider, RoundingMode.HALF_UP); - } else if (obj instanceof Double) { - obj = (Double) obj / divider.doubleValue(); - } else { - throw new UnsupportedOperationException(); - } - } - return obj; - } - - @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - obj = scaleInput(obj); - return df.format(obj, toAppendTo, pos); - } - - @Override - public Object parseObject(String source, ParsePosition pos) { - throw new UnsupportedOperationException(); - } - } - - private Format createNumberFormat(String formatStr, double cellValue) { - String format = cleanFormatForNumber(formatStr); - DecimalFormatSymbols symbols = decimalSymbols; - - // Do we need to change the grouping character? - // eg for a format like #'##0 which wants 12'345 not 12,345 - Matcher agm = alternateGrouping.matcher(format); - if (agm.find()) { - char grouping = agm.group(2).charAt(0); - // Only replace the grouping character if it is not the default - // grouping character for the US locale (',') in order to enable - // correct grouping for non-US locales. - if (grouping!=',') { - symbols = DecimalFormatSymbols.getInstance(locale); - - symbols.setGroupingSeparator(grouping); - String oldPart = agm.group(1); - String newPart = oldPart.replace(grouping, ','); - format = format.replace(oldPart, newPart); - } - } - - try { - return new InternalDecimalFormatWithScale(format, symbols); - } catch(IllegalArgumentException iae) { - LOG.atDebug().withThrowable(iae).log("Formatting failed for format {}, falling back", formatStr); - // the pattern could not be parsed correctly, - // so fall back to the default number format - return getDefaultFormat(cellValue); - } - } - - /** - * Returns a default format for a cell. - * @param cell The cell - * @return a default format - */ - public Format getDefaultFormat(Cell cell) { - return getDefaultFormat(cell.getNumericCellValue()); - } - private Format getDefaultFormat(double cellValue) { - checkForLocaleChange(); - - // for numeric cells try user supplied default - if (defaultNumFormat != null) { - return defaultNumFormat; - - // otherwise use general format - } - return generalNumberFormat; - } - - /** - * Performs Excel-style date formatting, using the - * supplied Date and format - */ - @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") - private String performDateFormatting(Date d, Format dateFormat) { - Format df = dateFormat != null ? dateFormat : defaultDateformat; - synchronized (df) { - return df.format(d); - } - } - - /** - * 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" - * , "01/02/2003" , "02-Jan" , etc. - * <p> - * If any conditional format rules apply, the highest priority with a number format is used. - * If no rules contain a number format, or no rules apply, the cell's style format is used. - * If the style does not have a format, the default date format is applied. - * - * @param cell to format - * @param cfEvaluator ConditionalFormattingEvaluator (if available) - * @return Formatted value - */ - @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") - private String getFormattedDateString(Cell cell, ConditionalFormattingEvaluator cfEvaluator) { - if (cell == null) { - return null; - } - Format dateFormat = getFormat(cell, cfEvaluator); - if (dateFormat == null) { - if (defaultDateformat == null) { - DateFormatSymbols sym = DateFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", sym); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - dateFormat = sdf; - } else { - dateFormat = defaultNumFormat; - } - } - synchronized (dateFormat) { - if(dateFormat instanceof ExcelStyleDateFormatter) { - // Hint about the raw excel value - ((ExcelStyleDateFormatter)dateFormat).setDateToBeFormatted( - cell.getNumericCellValue() - ); - } - Date d = cell.getDateCellValue(); - return performDateFormatting(d, dateFormat); - } - } - - /** - * Returns the formatted value of an Excel number as a <tt>String</tt> - * based on the cell's <code>DataFormat</code>. Supported formats include - * currency, percents, decimals, phone number, SSN, etc.: - * "61.54%", "$100.00", "(800) 555-1234". - * <p> - * Format comes from either the highest priority conditional format rule with a - * specified format, or from the cell style. - * - * @param cell The cell - * @param cfEvaluator if available, or null - * @return a formatted number string - */ - private String getFormattedNumberString(Cell cell, ConditionalFormattingEvaluator cfEvaluator) { - if (cell == null) { - return null; - } - Format numberFormat = getFormat(cell, cfEvaluator); - double d = cell.getNumericCellValue(); - if (numberFormat == null) { - return String.valueOf(d); - } - String formatted = numberFormat.format(d); - return formatted.replaceFirst("E(\\d)", "E+$1"); // to match Excel's E-notation - } - - /** - * Formats the given raw cell value, based on the supplied - * format index and string, according to excel style rules. - * @see #formatCellValue(Cell) - */ - public String formatRawCellContents(double value, int formatIndex, String formatString) { - return formatRawCellContents(value, formatIndex, formatString, false); - } - /** - * Formats the given raw cell value, based on the supplied - * format index and string, according to excel style rules. - * @see #formatCellValue(Cell) - */ - public String formatRawCellContents(double value, int formatIndex, String formatString, boolean use1904Windowing) { - checkForLocaleChange(); - - // Is it a date? - if(DateUtil.isADateFormat(formatIndex,formatString)) { - if(DateUtil.isValidExcelDate(value)) { - Format dateFormat = getFormat(value, formatIndex, formatString, use1904Windowing); - if(dateFormat instanceof ExcelStyleDateFormatter) { - // Hint about the raw excel value - ((ExcelStyleDateFormatter)dateFormat).setDateToBeFormatted(value); - } - Date d = DateUtil.getJavaDate(value, use1904Windowing); - return performDateFormatting(d, dateFormat); - } - // RK: Invalid dates are 255 #s. - if (emulateCSV) { - return invalidDateTimeString; - } - } - - // else Number - Format numberFormat = getFormat(value, formatIndex, formatString, use1904Windowing); - if (numberFormat == null) { - return String.valueOf(value); - } - - // When formatting 'value', double to text to BigDecimal produces more - // accurate results than double to Double in JDK8 (as compared to - // previous versions). However, if the value contains E notation, this - // would expand the values, which we do not want, so revert to - // original method. - String result; - final String textValue = NumberToTextConverter.toText(value); - if (textValue.indexOf('E') > -1) { - result = numberFormat.format(value); - } - else { - result = numberFormat.format(new BigDecimal(textValue)); - } - - // If they requested a non-abbreviated Scientific format, - // and there's an E## (but not E-##), add the missing '+' for E+## - String fslc = formatString.toLowerCase(Locale.ROOT); - if ((fslc.contains("general") || fslc.contains("e+0")) - && result.contains("E") && !result.contains("E-")) { - result = result.replaceFirst("E", "E+"); - } - return result; - } - - /** - * <p> - * Returns the formatted value of a cell as a <tt>String</tt> 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>When passed a null or blank cell, this method will return an empty - * String (""). Formulas in formula type cells will not be evaluated. - * </p> - * - * @param cell The cell - * @return the formatted cell value as a String - */ - public String formatCellValue(Cell cell) { - return formatCellValue(cell, null); - } - - /** - * <p> - * Returns the formatted value of a cell as a <tt>String</tt> 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>When passed a null or blank cell, this method will return an empty - * String (""). Formula cells will be evaluated using the given - * {@link FormulaEvaluator} if the evaluator is non-null. If the - * evaluator is null, then the formula String will be returned. The caller - * is responsible for setting the currentRow on the evaluator - *</p> - * - * @param cell The cell (can be null) - * @param evaluator The FormulaEvaluator (can be null) - * @return a string value of the cell - */ - public String formatCellValue(Cell cell, FormulaEvaluator evaluator) { - return formatCellValue(cell, evaluator, null); - } - - /** - * <p> - * Returns the formatted value of a cell as a <tt>String</tt> 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>When passed a null or blank cell, this method will return an empty - * String (""). Formula cells will be evaluated using the given - * {@link FormulaEvaluator} if the evaluator is non-null. If the - * evaluator is null, then the formula String will be returned. The caller - * is responsible for setting the currentRow on the evaluator - *</p> - * <p> - * When a ConditionalFormattingEvaluator is present, it is checked first to see - * if there is a number format to apply. If multiple rules apply, the last one is used. - * If no ConditionalFormattingEvaluator is present, no rules apply, or the applied - * rules do not define a format, the cell's style format is used. - * </p> - * <p> - * The two evaluators should be from the same context, to avoid inconsistencies in cached values. - *</p> - * - * @param cell The cell (can be null) - * @param evaluator The FormulaEvaluator (can be null) - * @param cfEvaluator ConditionalFormattingEvaluator (can be null) - * @return a string value of the cell - */ - public String formatCellValue(Cell cell, FormulaEvaluator evaluator, ConditionalFormattingEvaluator cfEvaluator) { - checkForLocaleChange(); - - if (cell == null) { - return ""; - } - - CellType cellType = cell.getCellType(); - if (cellType == CellType.FORMULA) { - if (evaluator == null) { - return cell.getCellFormula(); - } - cellType = evaluator.evaluateFormulaCell(cell); - } - switch (cellType) { - case NUMERIC : - - if (DateUtil.isCellDateFormatted(cell, cfEvaluator)) { - return getFormattedDateString(cell, cfEvaluator); - } - return getFormattedNumberString(cell, cfEvaluator); - - case STRING : - return cell.getRichStringCellValue().getString(); - - case BOOLEAN : - return cell.getBooleanCellValue() ? "TRUE" : "FALSE"; - case BLANK : - return ""; - case ERROR: - return FormulaError.forInt(cell.getErrorCellValue()).getString(); - default: - throw new RuntimeException("Unexpected celltype (" + cellType + ")"); - } - } - - - /** - * <p> - * Sets a default number format to be used when the Excel format cannot be - * parsed successfully. <b>Note:</b> This is a fall back for when an error - * occurs while parsing an Excel number format pattern. This will not - * affect cells with the <em>General</em> format. - * </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 - * numeric cell. Therefore the code in the format method should expect a - * <code>Number</code> value. - * </p> - * - * @param format A Format instance to be used as a default - * @see Format#format - */ - public void setDefaultNumberFormat(Format format) { - for (Map.Entry<String, Format> entry : formats.entrySet()) { - if (entry.getValue() == generalNumberFormat) { - entry.setValue(format); - } - } - defaultNumFormat = format; - } - - /** - * 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 - * numeric cell. Therefore the code in the format method should expect a - * <code>Number</code> value. - * </p> - * @param excelFormatStr The data format string - * @param format A Format instance - */ - public void addFormat(String excelFormatStr, Format format) { - formats.put(excelFormatStr, format); - } - - // Some custom formats - - /** - * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code> - */ - private static DecimalFormat createIntegerOnlyFormat(String fmt) { - DecimalFormatSymbols dsf = DecimalFormatSymbols.getInstance(Locale.ROOT); - DecimalFormat result = new DecimalFormat(fmt, dsf); - result.setParseIntegerOnly(true); - return result; - } - - /** - * Enables excel style rounding mode (round half up) on the - * Decimal Format given. - */ - public static void setExcelStyleRoundingMode(DecimalFormat format) { - setExcelStyleRoundingMode(format, RoundingMode.HALF_UP); - } - - /** - * Enables custom rounding mode on the given Decimal Format. - * @param format DecimalFormat - * @param roundingMode RoundingMode - */ - public static void setExcelStyleRoundingMode(DecimalFormat format, RoundingMode roundingMode) { - format.setRoundingMode(roundingMode); - } - - /** - * If the Locale has been changed via {@link LocaleUtil#setUserLocale(Locale)} the stored - * formats need to be refreshed. All formats which aren't originated from DataFormatter - * itself, i.e. all Formats added via {@link DataFormatter#addFormat(String, Format)} and - * {@link DataFormatter#setDefaultNumberFormat(Format)}, need to be added again. - * To notify callers, the returned {@link PropertyChangeSupport} should be used. - * The Locale in {@link #updateLocale(Locale)} is the new Locale. - * - * @return the listener object, where callers can register themselves - */ - public PropertyChangeSupport getLocaleChangedObservable() { - return pcs; - } - - private void checkForLocaleChange() { - checkForLocaleChange(LocaleUtil.getUserLocale()); - } - - private void checkForLocaleChange(Locale newLocale) { - if (!localeIsAdapting) return; - if (newLocale.equals(locale)) return; - updateLocale(newLocale); - pcs.firePropertyChange("locale", locale, newLocale); - } - - /** - * Update formats when locale has been changed - * - * @param newLocale the new locale - */ - public void updateLocale(Locale newLocale) { - if (!localeIsAdapting || newLocale.equals(locale)) return; - - locale = newLocale; - - dateSymbols = DateFormatSymbols.getInstance(locale); - decimalSymbols = DecimalFormatSymbols.getInstance(locale); - generalNumberFormat = new ExcelGeneralNumberFormat(locale); - - // taken from Date.toString() - defaultDateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", dateSymbols); - defaultDateformat.setTimeZone(LocaleUtil.getUserTimeZone()); - - // init built-in formats - - formats.clear(); - Format zipFormat = ZipPlusFourFormat.instance; - addFormat("00000\\-0000", zipFormat); - addFormat("00000-0000", zipFormat); - - Format phoneFormat = PhoneFormat.instance; - // allow for format string variations - addFormat("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####", phoneFormat); - addFormat("[<=9999999]###-####;(###) ###-####", phoneFormat); - addFormat("###\\-####;\\(###\\)\\ ###\\-####", phoneFormat); - addFormat("###-####;(###) ###-####", phoneFormat); - - Format ssnFormat = SSNFormat.instance; - addFormat("000\\-00\\-0000", ssnFormat); - addFormat("000-00-0000", ssnFormat); - } - - /** - * 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 { - public static final Format instance = new SSNFormat(); - private static final DecimalFormat df = createIntegerOnlyFormat("000000000"); - private SSNFormat() { - // enforce singleton - } - - /** Format a number as an SSN */ - public static String format(Number num) { - String result = df.format(num); - return result.substring(0, 3) + '-' + - result.substring(3, 5) + '-' + - result.substring(5, 9); - } - - @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - return toAppendTo.append(format((Number)obj)); - } - - @Override - public Object parseObject(String source, ParsePosition pos) { - return df.parseObject(source, pos); - } - } - - /** - * 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 { - public static final Format instance = new ZipPlusFourFormat(); - private static final DecimalFormat df = createIntegerOnlyFormat("000000000"); - private ZipPlusFourFormat() { - // enforce singleton - } - - /** Format a number as Zip + 4 */ - public static String format(Number num) { - String result = df.format(num); - return result.substring(0, 5) + '-' + - result.substring(5, 9); - } - - @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - return toAppendTo.append(format((Number)obj)); - } - - @Override - public Object parseObject(String source, ParsePosition pos) { - return df.parseObject(source, pos); - } - } - - /** - * 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 { - public static final Format instance = new PhoneFormat(); - private static final DecimalFormat df = createIntegerOnlyFormat("##########"); - private PhoneFormat() { - // enforce singleton - } - - /** Format a number as a phone number */ - public static String format(Number num) { - String result = df.format(num); - StringBuilder sb = new StringBuilder(); - String seg1, seg2, seg3; - int len = result.length(); - if (len <= 4) { - return result; - } - - seg3 = result.substring(len - 4, len); - seg2 = result.substring(Math.max(0, len - 7), len - 4); - seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7)); - - if(seg1.trim().length() > 0) { - sb.append('(').append(seg1).append(") "); - } - if(seg2.trim().length() > 0) { - sb.append(seg2).append('-'); - } - sb.append(seg3); - return sb.toString(); - } - - @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - return toAppendTo.append(format((Number)obj)); - } - - @Override - public Object parseObject(String source, ParsePosition pos) { - return df.parseObject(source, pos); - } - } - - - - - /** - * Format class that does nothing and always returns a constant string. - * - * This format is used to simulate Excel's handling of a format string - * of all # when the value is 0. Excel will output "", Java will output "0". - * - * @see DataFormatter#createFormat(double, int, String) - */ - @SuppressWarnings("serial") - private static final class ConstantStringFormat extends Format { - private static final DecimalFormat df = createIntegerOnlyFormat("##########"); - private final String str; - public ConstantStringFormat(String s) { - str = s; - } - - @Override - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - return toAppendTo.append(str); - } - - @Override - public Object parseObject(String source, ParsePosition pos) { - return df.parseObject(source, pos); - } - } - /** - * Workaround until we merge {@link DataFormatter} with {@link CellFormat}. - * Constant, non-cachable wrapper around a {@link CellFormatResult} - */ - @SuppressWarnings("serial") - private final class CellFormatResultWrapper extends Format { - private final CellFormatResult result; - private CellFormatResultWrapper(CellFormatResult result) { - this.result = result; - } - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - if (emulateCSV) { - return toAppendTo.append(result.text); - } else { - return toAppendTo.append(result.text.trim()); - } - } - public Object parseObject(String source, ParsePosition pos) { - return null; // Not supported - } - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/DataValidation.java b/src/java/org/apache/poi/ss/usermodel/DataValidation.java deleted file mode 100644 index c80ed6a744..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataValidation.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.util.CellRangeAddressList; - - -public interface DataValidation { - /** - * Error style constants for error box - */ - public static final class ErrorStyle { - /** STOP style */ - public static final int STOP = 0x00; - /** WARNING style */ - public static final int WARNING = 0x01; - /** INFO style */ - public static final int INFO = 0x02; - } - - public abstract DataValidationConstraint getValidationConstraint(); - - /** - * Sets the error style for error box - * @see ErrorStyle - */ - public abstract void setErrorStyle(int error_style); - - /**o - * @return the error style of error box - * @see ErrorStyle - */ - public abstract int getErrorStyle(); - - /** - * Sets if this object allows empty as a valid value - * - * @param allowed <code>true</code> if this object should treats empty as valid value , <code>false</code> - * otherwise - */ - public abstract void setEmptyCellAllowed(boolean allowed); - - /** - * Retrieve the settings for empty cells allowed - * - * @return True if this object should treats empty as valid value , false - * otherwise - */ - public abstract boolean getEmptyCellAllowed(); - - /** - * Useful for list validation objects . - * - * @param suppress - * True if a list should display the values into a drop down list , - * false otherwise . In other words , if a list should display - * the arrow sign on its right side - */ - public abstract void setSuppressDropDownArrow(boolean suppress); - - /** - * Useful only list validation objects . This method always returns false if - * the object isn't a list validation object - * - * @return <code>true</code> if a list should display the values into a drop down list , - * <code>false</code> otherwise . - */ - public abstract boolean getSuppressDropDownArrow(); - - /** - * Sets the behaviour when a cell which belongs to this object is selected - * - * @param show <code>true</code> if an prompt box should be displayed , <code>false</code> otherwise - */ - public abstract void setShowPromptBox(boolean show); - - /** - * @return <code>true</code> if an prompt box should be displayed , <code>false</code> otherwise - */ - public abstract boolean getShowPromptBox(); - - /** - * Sets the behaviour when an invalid value is entered - * - * @param show <code>true</code> if an error box should be displayed , <code>false</code> otherwise - */ - public abstract void setShowErrorBox(boolean show); - - /** - * @return <code>true</code> if an error box should be displayed , <code>false</code> otherwise - */ - public abstract boolean getShowErrorBox(); - - /** - * Sets the title and text for the prompt box . Prompt box is displayed when - * the user selects a cell which belongs to this validation object . In - * order for a prompt box to be displayed you should also use method - * setShowPromptBox( boolean show ) - * - * @param title The prompt box's title - * @param text The prompt box's text - */ - public abstract void createPromptBox(String title, String text); - - /** - * @return Prompt box's title or <code>null</code> - */ - public abstract String getPromptBoxTitle(); - - /** - * @return Prompt box's text or <code>null</code> - */ - public abstract String getPromptBoxText(); - - /** - * Sets the title and text for the error box . Error box is displayed when - * the user enters an invalid value int o a cell which belongs to this - * validation object . In order for an error box to be displayed you should - * also use method setShowErrorBox( boolean show ) - * - * @param title The error box's title - * @param text The error box's text - */ - public abstract void createErrorBox(String title, String text); - - /** - * @return Error box's title or <code>null</code> - */ - public abstract String getErrorBoxTitle(); - - /** - * @return Error box's text or <code>null</code> - */ - public abstract String getErrorBoxText(); - - public abstract CellRangeAddressList getRegions(); - -} diff --git a/src/java/org/apache/poi/ss/usermodel/DataValidationConstraint.java b/src/java/org/apache/poi/ss/usermodel/DataValidationConstraint.java deleted file mode 100644 index 38f78e8681..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataValidationConstraint.java +++ /dev/null @@ -1,124 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - - -public interface DataValidationConstraint { - - /** - * @return data validation type of this constraint - * @see ValidationType - */ - public abstract int getValidationType(); - - /** - * @return the operator used for this constraint - * @see OperatorType - */ - public abstract int getOperator(); - - /** - * Sets the comparison operator for this constraint - * @see OperatorType - */ - public abstract void setOperator(int operator); - - /** - * If validation type is {@link ValidationType#LIST} - * and <code>formula1</code> was comma-separated literal values rather than a range or named range, - * returns list of literal values. - * Otherwise returns <code>null</code>. - */ - public abstract String[] getExplicitListValues(); - - public abstract void setExplicitListValues(String[] explicitListValues); - - /** - * @return the formula for expression 1. May be <code>null</code> - */ - public abstract String getFormula1(); - - /** - * Sets a formula for expression 1. - */ - public abstract void setFormula1(String formula1); - - /** - * @return the formula for expression 2. May be <code>null</code> - */ - public abstract String getFormula2(); - - /** - * Sets a formula for expression 2. - */ - public abstract void setFormula2(String formula2); - - /** - * ValidationType enum - */ - public static final class ValidationType { - private ValidationType() { - // no instances of this class - } - /** 'Any value' type - value not restricted */ - public static final int ANY = 0x00; - /** Integer ('Whole number') type */ - public static final int INTEGER = 0x01; - /** Decimal type */ - public static final int DECIMAL = 0x02; - /** List type ( combo box type ) */ - public static final int LIST = 0x03; - /** Date type */ - public static final int DATE = 0x04; - /** Time type */ - public static final int TIME = 0x05; - /** String length type */ - public static final int TEXT_LENGTH = 0x06; - /** Formula ( 'Custom' ) type */ - public static final int FORMULA = 0x07; - } - /** - * Condition operator enum - */ - public static final class OperatorType { - private OperatorType() { - // no instances of this class - } - - public static final int BETWEEN = 0x00; - public static final int NOT_BETWEEN = 0x01; - public static final int EQUAL = 0x02; - public static final int NOT_EQUAL = 0x03; - public static final int GREATER_THAN = 0x04; - public static final int LESS_THAN = 0x05; - public static final int GREATER_OR_EQUAL = 0x06; - public static final int LESS_OR_EQUAL = 0x07; - /** default value to supply when the operator type is not used */ - public static final int IGNORED = BETWEEN; - - /* package */ public static void validateSecondArg(int comparisonOperator, String paramValue) { - switch (comparisonOperator) { - case BETWEEN: - case NOT_BETWEEN: - if (paramValue == null) { - throw new IllegalArgumentException("expr2 must be supplied for 'between' comparisons"); - } - // all other operators don't need second arg - } - } - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/DataValidationHelper.java b/src/java/org/apache/poi/ss/usermodel/DataValidationHelper.java deleted file mode 100644 index 2e749467e4..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DataValidationHelper.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -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); -} diff --git a/src/java/org/apache/poi/ss/usermodel/Date1904Support.java b/src/java/org/apache/poi/ss/usermodel/Date1904Support.java deleted file mode 100644 index db9cdd3b69..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Date1904Support.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Internal; - -@Internal -public interface Date1904Support { - /** - * Gets a boolean value that indicates whether the date systems used in the workbook starts in 1904. - * <p> - * The default value is false, meaning that the workbook uses the 1900 date system, - * where 1/1/1900 is the first day in the system. - * - * 1904 based dates are only supported in XSSF workbooks. - * </p> - * @return true if the date systems used in the workbook starts in 1904 - */ - boolean isDate1904(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/DateUtil.java b/src/java/org/apache/poi/ss/usermodel/DateUtil.java deleted file mode 100644 index ea95436c06..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DateUtil.java +++ /dev/null @@ -1,993 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.usermodel; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.temporal.ChronoField; -import java.time.temporal.ChronoUnit; -import java.time.temporal.TemporalAccessor; -import java.time.temporal.TemporalQueries; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; -import java.util.regex.Pattern; - -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.util.LocaleUtil; - -/** - * Contains methods for dealing with Excel dates. - */ -public class DateUtil { - // FIXME this should be changed to private and the class marked final once HSSFDateUtil can be removed - protected DateUtil() { - // no instances of this class - } - - public static final int SECONDS_PER_MINUTE = 60; - public static final int MINUTES_PER_HOUR = 60; - public static final int HOURS_PER_DAY = 24; - public static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); - - // used to specify that date is invalid - private static final int BAD_DATE = -1; - public static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L; - - - - private static final BigDecimal BD_NANOSEC_DAY = BigDecimal.valueOf(SECONDS_PER_DAY * 1e9); - private static final BigDecimal BD_MILISEC_RND = BigDecimal.valueOf(0.5 * 1e6); - private static final BigDecimal BD_SECOND_RND = BigDecimal.valueOf(0.5 * 1e9); - - private static final Pattern TIME_SEPARATOR_PATTERN = Pattern.compile(":"); - - /** - * The following patterns are used in {@link #isADateFormat(int, String)} - */ - private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$\\-.*?\\]"); - private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+\\]"); - private static final Pattern date_ptrn3a = Pattern.compile("[yYmMdDhHsS]"); - // add "\u5e74 \u6708 \u65e5" for Chinese/Japanese date format:2017 \u5e74 2 \u6708 7 \u65e5 - private static final Pattern date_ptrn3b = Pattern.compile("^[\\[\\]yYmMdDhHsS\\-T/\u5e74\u6708\u65e5,. :\"\\\\]+0*[ampAMP/]*$"); - // elapsed time patterns: [h],[m] and [s] - private static final Pattern date_ptrn4 = Pattern.compile("^\\[([hH]+|[mM]+|[sS]+)\\]"); - - // for format which start with "[DBNum1]" or "[DBNum2]" or "[DBNum3]" could be a Chinese date - private static final Pattern date_ptrn5 = Pattern.compile("^\\[DBNum(1|2|3)\\]"); - - private static final DateTimeFormatter dateTimeFormats = new DateTimeFormatterBuilder() - .appendPattern("[dd MMM[ yyyy]][[ ]h:m[:s] a][[ ]H:m[:s]]") - .appendPattern("[[yyyy ]dd-MMM[-yyyy]][[ ]h:m[:s] a][[ ]H:m[:s]]") - .appendPattern("[M/dd[/yyyy]][[ ]h:m[:s] a][[ ]H:m[:s]]") - .appendPattern("[[yyyy/]M/dd][[ ]h:m[:s] a][[ ]H:m[:s]]") - .parseDefaulting(ChronoField.YEAR_OF_ERA, LocaleUtil.getLocaleCalendar().get(Calendar.YEAR)) - .toFormatter(); - - /** - * Convert a Java Date (at UTC) to LocalDateTime. - * @param date the date - * @return LocalDateTime instance - */ - public static LocalDateTime toLocalDateTime(Date date) { - return date.toInstant() - .atZone(TimeZone.getTimeZone("UTC").toZoneId()) // java.util.Date uses UTC - .toLocalDateTime(); - } - - /** - * Convert a Java Calendar (at UTC) to LocalDateTime. - * @param date the date - * @return LocalDateTime instance - */ - public static LocalDateTime toLocalDateTime(Calendar date) { - return date.toInstant() - .atZone(TimeZone.getTimeZone("UTC").toZoneId()) // java.util.Date uses UTC - .toLocalDateTime(); - } - - /** - * Given a LocalDate, converts it into a double representing its internal Excel representation, - * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Date - */ - public static double getExcelDate(LocalDate date) { - return getExcelDate(date, false); - } - - /** - * Given a LocalDate, converts it into a double representing its internal Excel representation, - * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Date - * @param use1904windowing Should 1900 or 1904 date windowing be used? - */ - public static double getExcelDate(LocalDate date, boolean use1904windowing) { - int year = date.getYear(); - int dayOfYear = date.getDayOfYear(); - int hour = 0; - int minute = 0; - int second = 0; - int milliSecond = 0; - - return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing); - } - - /** - * Given a LocalDateTime, converts it into a double representing its internal Excel representation, - * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Date - */ - public static double getExcelDate(LocalDateTime date) { - return getExcelDate(date, false); - } - - /** - * Given a LocalDateTime, converts it into a double representing its internal Excel representation, - * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Date - * @param use1904windowing Should 1900 or 1904 date windowing be used? - */ - public static double getExcelDate(LocalDateTime date, boolean use1904windowing) { - int year = date.getYear(); - int dayOfYear = date.getDayOfYear(); - int hour = date.getHour(); - int minute = date.getMinute(); - int second = date.getSecond(); - int milliSecond = date.getNano()/1_000_000; - - return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing); - } - - /** - * Given a Date, converts it into a double representing its internal Excel representation, - * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Date - */ - public static double getExcelDate(Date date) { - return getExcelDate(date, false); - } - - /** - * Given a Date, converts it into a double representing its internal Excel representation, - * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Date - * @param use1904windowing Should 1900 or 1904 date windowing be used? - */ - public static double getExcelDate(Date date, boolean use1904windowing) { - Calendar calStart = LocaleUtil.getLocaleCalendar(); - calStart.setTime(date); - int year = calStart.get(Calendar.YEAR); - int dayOfYear = calStart.get(Calendar.DAY_OF_YEAR); - int hour = calStart.get(Calendar.HOUR_OF_DAY); - int minute = calStart.get(Calendar.MINUTE); - int second = calStart.get(Calendar.SECOND); - int milliSecond = calStart.get(Calendar.MILLISECOND); - - return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing); - } - - /** - * Given a Date in the form of a Calendar, converts it into a double - * representing its internal Excel representation, which is the - * number of days since 1/1/1900. Fractional days represent hours, - * minutes, and seconds. - * - * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1) - * @param date the Calendar holding the date to convert - * @param use1904windowing Should 1900 or 1904 date windowing be used? - */ - public static double getExcelDate(Calendar date, boolean use1904windowing) { - int year = date.get(Calendar.YEAR); - int dayOfYear = date.get(Calendar.DAY_OF_YEAR); - int hour = date.get(Calendar.HOUR_OF_DAY); - int minute = date.get(Calendar.MINUTE); - int second = date.get(Calendar.SECOND); - int milliSecond = date.get(Calendar.MILLISECOND); - - return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing); - } - - private static double internalGetExcelDate(int year, int dayOfYear, int hour, int minute, int second, int milliSecond, boolean use1904windowing) { - if ((!use1904windowing && year < 1900) || - (use1904windowing && year < 1904)) - { - return BAD_DATE; - } - - // Because of daylight time saving we cannot use - // date.getTime() - calStart.getTimeInMillis() - // as the difference in milliseconds between 00:00 and 04:00 - // can be 3, 4 or 5 hours but Excel expects it to always - // be 4 hours. - // E.g. 2004-03-28 04:00 CEST - 2004-03-28 00:00 CET is 3 hours - // and 2004-10-31 04:00 CET - 2004-10-31 00:00 CEST is 5 hours - double fraction = (((hour * 60.0 - + minute - ) * 60.0 + second - ) * 1000.0 + milliSecond - ) / DAY_MILLISECONDS; - - double value = fraction + absoluteDay(year, dayOfYear, use1904windowing); - - if (!use1904windowing && value >= 60) { - value++; - } else if (use1904windowing) { - value--; - } - - return value; - } - - /** - * Given an Excel date with using 1900 date windowing, and - * converts it to a java.util.Date. - * - * Excel Dates and Times are stored without any timezone - * information. If you know (through other means) that your file - * uses a different TimeZone to the system default, you can use - * this version of the getJavaDate() method to handle it. - * - * @param date The Excel date. - * @param tz The TimeZone to evaluate the date in - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Date getJavaDate(double date, TimeZone tz) { - return getJavaDate(date, false, tz, false); - } - /** - * Given an Excel date with using 1900 date windowing, and - * converts it to a java.util.Date. - * - * NOTE: If the default <code>TimeZone</code> in Java uses Daylight - * Saving Time then the conversion back to an Excel date may not give - * the same value, that is the comparison - * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE> - * is not always true. For example if default timezone is - * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after - * 01:59 CET is 03:00 CEST, if the excel date represents a time between - * 02:00 and 03:00 then it is converted to past 03:00 summer time - * - * @param date The Excel date. - * @return Java representation of the date, or null if date is not a valid Excel date - * @see java.util.TimeZone - */ - public static Date getJavaDate(double date) { - return getJavaDate(date, false, null, false); - } - - /** - * Given an Excel date with either 1900 or 1904 date windowing, - * converts it to a java.util.Date. - * - * Excel Dates and Times are stored without any timezone - * information. If you know (through other means) that your file - * uses a different TimeZone to the system default, you can use - * this version of the getJavaDate() method to handle it. - * - * @param date The Excel date. - * @param tz The TimeZone to evaluate the date in - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Date getJavaDate(double date, boolean use1904windowing, TimeZone tz) { - return getJavaDate(date, use1904windowing, tz, false); - } - - /** - * Given an Excel date with either 1900 or 1904 date windowing, - * converts it to a java.util.Date. - * - * Excel Dates and Times are stored without any timezone - * information. If you know (through other means) that your file - * uses a different TimeZone to the system default, you can use - * this version of the getJavaDate() method to handle it. - * - * @param date The Excel date. - * @param tz The TimeZone to evaluate the date in - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @param roundSeconds round to closest second - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Date getJavaDate(double date, boolean use1904windowing, TimeZone tz, boolean roundSeconds) { - Calendar calendar = getJavaCalendar(date, use1904windowing, tz, roundSeconds); - return calendar == null ? null : calendar.getTime(); - } - - /** - * Given an Excel date with either 1900 or 1904 date windowing, - * converts it to a java.util.Date. - * - * NOTE: If the default <code>TimeZone</code> in Java uses Daylight - * Saving Time then the conversion back to an Excel date may not give - * the same value, that is the comparison - * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE> - * is not always true. For example if default timezone is - * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after - * 01:59 CET is 03:00 CEST, if the excel date represents a time between - * 02:00 and 03:00 then it is converted to past 03:00 summer time - * - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @return Java representation of the date, or null if date is not a valid Excel date - * @see java.util.TimeZone - */ - public static Date getJavaDate(double date, boolean use1904windowing) { - return getJavaDate(date, use1904windowing, null, false); - } - - /** - * Given an Excel date with using 1900 date windowing, and - * converts it to a java.time.LocalDateTime. - * - * NOTE: If the default <code>TimeZone</code> in Java uses Daylight - * Saving Time then the conversion back to an Excel date may not give - * the same value, that is the comparison - * <CODE>excelDate == getExcelDate(getLocalDateTime(excelDate,false))</CODE> - * is not always true. For example if default timezone is - * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after - * 01:59 CET is 03:00 CEST, if the excel date represents a time between - * 02:00 and 03:00 then it is converted to past 03:00 summer time - * - * @param date The Excel date. - * @return Java representation of the date, or null if date is not a valid Excel date - * @see java.util.TimeZone - */ - public static LocalDateTime getLocalDateTime(double date) { - return getLocalDateTime(date, false, false); - } - - /** - * Given an Excel date with either 1900 or 1904 date windowing, - * converts it to a java.time.LocalDateTime. - * - * Excel Dates and Times are stored without any timezone - * information. If you know (through other means) that your file - * uses a different TimeZone to the system default, you can use - * this version of the getJavaDate() method to handle it. - * - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static LocalDateTime getLocalDateTime(double date, boolean use1904windowing) { - return getLocalDateTime(date, use1904windowing, false); - } - - /** - * Given an Excel date with either 1900 or 1904 date windowing, - * converts it to a java.time.LocalDateTime. - * - * Excel Dates and Times are stored without any timezone - * information. If you know (through other means) that your file - * uses a different TimeZone to the system default, you can use - * this version of the getJavaDate() method to handle it. - * - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @param roundSeconds round to closest second - * @return Java representation of the date, or null if date is not a valid Excel date - */ - @SuppressWarnings("squid:S2111") - public static LocalDateTime getLocalDateTime(double date, boolean use1904windowing, boolean roundSeconds) { - if (!isValidExcelDate(date)) { - return null; - } - - BigDecimal bd = new BigDecimal(date); - - int wholeDays = bd.intValue(); - - int startYear = 1900; - int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't - if (use1904windowing) { - startYear = 1904; - dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day - } - else if (wholeDays < 61) { - // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists - // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation - dayAdjust = 0; - } - - LocalDateTime ldt = LocalDateTime.of(startYear, 1, 1, 0, 0); - ldt = ldt.plusDays(wholeDays+dayAdjust-1L); - - long nanosTime = - bd.subtract(BigDecimal.valueOf(wholeDays)) - .multiply(BD_NANOSEC_DAY) - .add(roundSeconds ? BD_SECOND_RND : BD_MILISEC_RND) - .longValue(); - - ldt = ldt.plusNanos(nanosTime); - ldt = ldt.truncatedTo(roundSeconds ? ChronoUnit.SECONDS : ChronoUnit.MILLIS); - - return ldt; - } - - public static void setCalendar(Calendar calendar, int wholeDays, - int millisecondsInDay, boolean use1904windowing, boolean roundSeconds) { - int startYear = 1900; - int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't - if (use1904windowing) { - startYear = 1904; - dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day - } - else if (wholeDays < 61) { - // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists - // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation - dayAdjust = 0; - } - calendar.set(startYear,0, wholeDays + dayAdjust, 0, 0, 0); - calendar.set(Calendar.MILLISECOND, millisecondsInDay); - if (calendar.get(Calendar.MILLISECOND) == 0) { - calendar.clear(Calendar.MILLISECOND); - } - if (roundSeconds) { - calendar.add(Calendar.MILLISECOND, 500); - calendar.clear(Calendar.MILLISECOND); - } - } - - - /** - * Get EXCEL date as Java Calendar (with default time zone). - * This is like {@link #getJavaDate(double)} but returns a Calendar object. - * @param date The Excel date. - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Calendar getJavaCalendar(double date) { - return getJavaCalendar(date, false, null, false); - } - - /** - * Get EXCEL date as Java Calendar (with default time zone). - * This is like {@link #getJavaDate(double, boolean)} but returns a Calendar object. - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Calendar getJavaCalendar(double date, boolean use1904windowing) { - return getJavaCalendar(date, use1904windowing, null, false); - } - - /** - * Get EXCEL date as Java Calendar with UTC time zone. - * This is similar to {@link #getJavaDate(double, boolean)} but returns a - * Calendar object that has UTC as time zone, so no daylight saving hassle. - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @return Java representation of the date in UTC, or null if date is not a valid Excel date - */ - public static Calendar getJavaCalendarUTC(double date, boolean use1904windowing) { - return getJavaCalendar(date, use1904windowing, LocaleUtil.TIMEZONE_UTC, false); - } - - - /** - * Get EXCEL date as Java Calendar with given time zone. - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @param timeZone The TimeZone to evaluate the date in - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone) { - return getJavaCalendar(date, use1904windowing, timeZone, false); - } - - /** - * Get EXCEL date as Java Calendar with given time zone. - * @param date The Excel date. - * @param use1904windowing true if date uses 1904 windowing, - * or false if using 1900 date windowing. - * @param timeZone The TimeZone to evaluate the date in - * @param roundSeconds round to closest second - * @return Java representation of the date, or null if date is not a valid Excel date - */ - public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone, boolean roundSeconds) { - if (!isValidExcelDate(date)) { - return null; - } - int wholeDays = (int)Math.floor(date); - int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); - Calendar calendar; - if (timeZone != null) { - calendar = LocaleUtil.getLocaleCalendar(timeZone); - } else { - calendar = LocaleUtil.getLocaleCalendar(); // using default time-zone - } - setCalendar(calendar, wholeDays, millisecondsInDay, use1904windowing, roundSeconds); - return calendar; - } - - // variables for performance optimization: - // avoid re-checking DataUtil.isADateFormat(int, String) if a given format - // string represents a date format if the same string is passed multiple times. - // see https://issues.apache.org/bugzilla/show_bug.cgi?id=55611 - private static ThreadLocal<Integer> lastFormatIndex = ThreadLocal.withInitial(() -> -1); - private static ThreadLocal<String> lastFormatString = new ThreadLocal<>(); - private static ThreadLocal<Boolean> lastCachedResult = new ThreadLocal<>(); - - private static boolean isCached(String formatString, int formatIndex) { - return formatIndex == lastFormatIndex.get() - && formatString.equals(lastFormatString.get()); - } - - private static void cache(String formatString, int formatIndex, boolean cached) { - if (formatString == null || "".equals(formatString)) { - lastFormatString.remove(); - } else { - lastFormatString.set(formatString); - } - if (formatIndex == -1) { - lastFormatIndex.remove(); - } else { - lastFormatIndex.set(formatIndex); - } - lastCachedResult.set(cached); - } - - /** - * Given a format ID and its format String, will check to see if the - * format represents a date format or not. - * Firstly, it will check to see if the format ID corresponds to an - * internal excel date format (eg most US date formats) - * If not, it will check to see if the format string only contains - * date formatting characters (ymd-/), which covers most - * non US date formats. - * - * @param numFmt The number format index and string expression, or null if not specified - * @return true if it is a valid date format, false if not or null - * @see #isInternalDateFormat(int) - */ - public static boolean isADateFormat(ExcelNumberFormat numFmt) { - - if (numFmt == null) { - return false; - } - - return isADateFormat(numFmt.getIdx(), numFmt.getFormat()); - } - - /** - * Given a format ID and its format String, will check to see if the - * format represents a date format or not. - * Firstly, it will check to see if the format ID corresponds to an - * internal excel date format (eg most US date formats) - * If not, it will check to see if the format string only contains - * date formatting characters (ymd-/), which covers most - * non US date formats. - * - * @param formatIndex The index of the format, eg from ExtendedFormatRecord.getFormatIndex - * @param formatString The format string, eg from FormatRecord.getFormatString - * @return true if it is a valid date format, false if not or null - * @see #isInternalDateFormat(int) - */ - public static boolean isADateFormat(int formatIndex, String formatString) { - - // First up, is this an internal date format? - if(isInternalDateFormat(formatIndex)) { - cache(formatString, formatIndex, true); - return true; - } - - // If we didn't get a real string, don't even cache it as we can always find this out quickly - if(formatString == null || formatString.length() == 0) { - return false; - } - - // check the cache first - if (isCached(formatString, formatIndex)) { - return lastCachedResult.get(); - } - - String fs = formatString; - /*if (false) { - // Normalize the format string. The code below is equivalent - // to the following consecutive regexp replacements: - - // Translate \- into just -, before matching - fs = fs.replaceAll("\\\\-","-"); - // And \, into , - fs = fs.replaceAll("\\\\,",","); - // And \. into . - fs = fs.replaceAll("\\\\\\.","."); - // And '\ ' into ' ' - fs = fs.replaceAll("\\\\ "," "); - - // If it end in ;@, that's some crazy dd/mm vs mm/dd - // switching stuff, which we can ignore - fs = fs.replaceAll(";@", ""); - - // The code above was reworked as suggested in bug 48425: - // simple loop is more efficient than consecutive regexp replacements. - }*/ - final int length = fs.length(); - StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; i++) { - char c = fs.charAt(i); - if (i < length - 1) { - char nc = fs.charAt(i + 1); - if (c == '\\') { - switch (nc) { - case '-': - case ',': - case '.': - case ' ': - case '\\': - // skip current '\' and continue to the next char - continue; - } - } else if (c == ';' && nc == '@') { - i++; - // skip ";@" duplets - continue; - } - } - sb.append(c); - } - fs = sb.toString(); - - // short-circuit if it indicates elapsed time: [h], [m] or [s] - if(date_ptrn4.matcher(fs).matches()){ - cache(formatString, formatIndex, true); - return true; - } - // If it starts with [DBNum1] or [DBNum2] or [DBNum3] - // then it could be a Chinese date - fs = date_ptrn5.matcher(fs).replaceAll(""); - // If it starts with [$-...], then could be a date, but - // who knows what that starting bit is all about - fs = date_ptrn1.matcher(fs).replaceAll(""); - // If it starts with something like [Black] or [Yellow], - // then it could be a date - fs = date_ptrn2.matcher(fs).replaceAll(""); - // You're allowed something like dd/mm/yy;[red]dd/mm/yy - // which would place dates before 1900/1904 in red - // For now, only consider the first one - final int separatorIndex = fs.indexOf(';'); - if(0 < separatorIndex && separatorIndex < fs.length()-1) { - fs = fs.substring(0, separatorIndex); - } - - // Ensure it has some date letters in it - // (Avoids false positives on the rest of pattern 3) - if (! date_ptrn3a.matcher(fs).find()) { - return false; - } - - // If we get here, check it's only made up, in any case, of: - // y m d h s - \ / , . : [ ] T - // optionally followed by AM/PM - - boolean result = date_ptrn3b.matcher(fs).matches(); - cache(formatString, formatIndex, result); - return result; - } - - /** - * Given a format ID this will check whether the format represents - * an internal excel date format or not. - * @see #isADateFormat(int, java.lang.String) - */ - public static boolean isInternalDateFormat(int format) { - switch(format) { - // Internal Date Formats as described on page 427 in - // Microsoft Excel Dev's Kit... - case 0x0e: - case 0x0f: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x2d: - case 0x2e: - case 0x2f: - return true; - } - return false; - } - - /** - * Check if a cell contains a date - * Since dates are stored internally in Excel as double values - * we infer it is a date if it is formatted as such. - * @param cell - * @return true if it looks like a date - * @see #isADateFormat(int, String) - * @see #isInternalDateFormat(int) - */ - public static boolean isCellDateFormatted(Cell cell) { - return isCellDateFormatted(cell, null); - } - - /** - * Check if a cell contains a date - * Since dates are stored internally in Excel as double values - * we infer it is a date if it is formatted as such. - * Format is determined from applicable conditional formatting, if - * any, or cell style. - * @param cell - * @param cfEvaluator if available, or null - * @return true if it looks like a date - * @see #isADateFormat(int, String) - * @see #isInternalDateFormat(int) - */ - public static boolean isCellDateFormatted(Cell cell, ConditionalFormattingEvaluator cfEvaluator) { - if (cell == null) { - return false; - } - boolean bDate = false; - - double d = cell.getNumericCellValue(); - if ( DateUtil.isValidExcelDate(d) ) { - ExcelNumberFormat nf = ExcelNumberFormat.from(cell, cfEvaluator); - if(nf==null) { - return false; - } - bDate = isADateFormat(nf); - } - return bDate; - } - - /** - * Check if a cell contains a date, checking only for internal - * excel date formats. - * As Excel stores a great many of its dates in "non-internal" - * date formats, you will not normally want to use this method. - * @see #isADateFormat(int,String) - * @see #isInternalDateFormat(int) - */ - public static boolean isCellInternalDateFormatted(Cell cell) { - if (cell == null) { - return false; - } - boolean bDate = false; - - double d = cell.getNumericCellValue(); - if ( DateUtil.isValidExcelDate(d) ) { - CellStyle style = cell.getCellStyle(); - int i = style.getDataFormat(); - bDate = isInternalDateFormat(i); - } - return bDate; - } - - - /** - * Given a double, checks if it is a valid Excel date. - * - * @return true if valid - * @param value the double value - */ - - public static boolean isValidExcelDate(double value) - { - return (value > -Double.MIN_VALUE); - } - - /** - * Given a Calendar, return the number of days since 1900/12/31. - * - * @return days number of days since 1900/12/31 - * @param cal the Calendar - * @exception IllegalArgumentException if date is invalid - */ - protected static int absoluteDay(Calendar cal, boolean use1904windowing) - { - return absoluteDay(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), use1904windowing); - } - - /** - * Given a LocalDateTime, return the number of days since 1900/12/31. - * - * @return days number of days since 1900/12/31 - * @param date the Date - * @exception IllegalArgumentException if date is invalid - */ - protected static int absoluteDay(LocalDateTime date, boolean use1904windowing) - { - return absoluteDay(date.getYear(), date.getDayOfYear(), use1904windowing); - } - - /** - * Given a year and day of year, return the number of days since 1900/12/31. - * - * @return days number of days since 1900/12/31 - * @param dayOfYear the day of the year - * @param year the year - * @exception IllegalArgumentException if date is invalid - */ - private static int absoluteDay(int year, int dayOfYear, boolean use1904windowing) { - return dayOfYear + daysInPriorYears(year, use1904windowing); - } - - /** - * Return the number of days in prior years since 1900 - * - * @return days number of days in years prior to yr. - * @param yr a year (1900 < yr < 4000) - * @param use1904windowing - * @exception IllegalArgumentException if year is outside of range. - */ - - static int daysInPriorYears(int yr, boolean use1904windowing) - { - if ((!use1904windowing && yr < 1900) || (use1904windowing && yr < 1904)) { - throw new IllegalArgumentException("'year' must be 1900 or greater"); - } - - int yr1 = yr - 1; - int leapDays = yr1 / 4 // plus julian leap days in prior years - - yr1 / 100 // minus prior century years - + yr1 / 400 // plus years divisible by 400 - - 460; // leap days in previous 1900 years - - return 365 * (yr - (use1904windowing ? 1904 : 1900)) + leapDays; - } - - // set HH:MM:SS fields of cal to 00:00:00:000 - private static Calendar dayStart(final Calendar cal) - { - cal.get(Calendar - .HOUR_OF_DAY); // force recalculation of internal fields - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - cal.get(Calendar - .HOUR_OF_DAY); // force recalculation of internal fields - return cal; - } - - - @SuppressWarnings("serial") - private static final class FormatException extends Exception { - public FormatException(String msg) { - super(msg); - } - } - - /** - * Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent - * - * @return a double between 0 and 1 representing the fraction of the day - */ - public static double convertTime(String timeStr) { - try { - return convertTimeInternal(timeStr); - } catch (FormatException e) { - String msg = "Bad time format '" + timeStr - + "' expected 'HH:MM' or 'HH:MM:SS' - " + e.getMessage(); - throw new IllegalArgumentException(msg); - } - } - private static double convertTimeInternal(String timeStr) throws FormatException { - int len = timeStr.length(); - if (len < 4 || len > 8) { - throw new FormatException("Bad length"); - } - String[] parts = TIME_SEPARATOR_PATTERN.split(timeStr); - - String secStr; - switch (parts.length) { - case 2: secStr = "00"; break; - case 3: secStr = parts[2]; break; - default: - throw new FormatException("Expected 2 or 3 fields but got (" + parts.length + ")"); - } - String hourStr = parts[0]; - String minStr = parts[1]; - int hours = parseInt(hourStr, "hour", HOURS_PER_DAY); - int minutes = parseInt(minStr, "minute", MINUTES_PER_HOUR); - int seconds = parseInt(secStr, "second", SECONDS_PER_MINUTE); - - double totalSeconds = seconds + (minutes + (hours * 60.0)) * 60.0; - return totalSeconds / (SECONDS_PER_DAY); - } - /** - * Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent - * - * @return a double representing the (integer) number of days since the start of the Excel epoch - */ - public static Date parseYYYYMMDDDate(String dateStr) { - try { - return parseYYYYMMDDDateInternal(dateStr); - } catch (FormatException e) { - String msg = "Bad time format " + dateStr - + " expected 'YYYY/MM/DD' - " + e.getMessage(); - throw new IllegalArgumentException(msg); - } - } - private static Date parseYYYYMMDDDateInternal(String timeStr) throws FormatException { - if(timeStr.length() != 10) { - throw new FormatException("Bad length"); - } - - String yearStr = timeStr.substring(0, 4); - String monthStr = timeStr.substring(5, 7); - String dayStr = timeStr.substring(8, 10); - int year = parseInt(yearStr, "year", Short.MIN_VALUE, Short.MAX_VALUE); - int month = parseInt(monthStr, "month", 1, 12); - int day = parseInt(dayStr, "day", 1, 31); - - Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day); - return cal.getTime(); - } - private static int parseInt(String strVal, String fieldName, int rangeMax) throws FormatException { - return parseInt(strVal, fieldName, 0, rangeMax-1); - } - - private static int parseInt(String strVal, String fieldName, int lowerLimit, int upperLimit) throws FormatException { - int result; - try { - result = Integer.parseInt(strVal); - } catch (NumberFormatException e) { - throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field"); - } - if (result < lowerLimit || result > upperLimit) { - throw new FormatException(fieldName + " value (" + result - + ") is outside the allowable range(0.." + upperLimit + ")"); - } - return result; - } - - public static Double parseDateTime(String str){ - TemporalAccessor tmp = dateTimeFormats.parse(str.replaceAll("\\s+", " ")); - LocalTime time = tmp.query(TemporalQueries.localTime()); - LocalDate date = tmp.query(TemporalQueries.localDate()); - if(time == null && date == null) return null; - - double tm = 0; - if(date != null) { - Date d = Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - tm = DateUtil.getExcelDate(d); - } - if(time != null) tm += 1.0*time.toSecondOfDay()/SECONDS_PER_DAY; - - return tm; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/DifferentialStyleProvider.java b/src/java/org/apache/poi/ss/usermodel/DifferentialStyleProvider.java deleted file mode 100644 index ce6ad535e6..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/DifferentialStyleProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Interface for classes providing differential style definitions, such as conditional format rules - * and table/pivot table styles. - * - * @since 3.17 beta 1 - */ -public interface DifferentialStyleProvider { - - /** - * @return - border formatting object if defined, <code>null</code> otherwise - */ - BorderFormatting getBorderFormatting(); - - /** - * @return - font formatting object if defined, <code>null</code> otherwise - */ - FontFormatting getFontFormatting(); - - /** - * - * @return number format defined for this rule, or null if the cell default should be used - */ - ExcelNumberFormat getNumberFormat(); - - /** - * @return - pattern formatting object if defined, <code>null</code> otherwise - */ - PatternFormatting getPatternFormatting(); - - /** - * This is the number of rows or columns in a band or stripe. - * For styles that represent stripes, it must be > 1, for all others it is 0. - * Not the greatest overloading by the OOXML spec. - * @return number of rows/columns in a stripe for stripe styles, 0 for all others - */ - int getStripeSize(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/Drawing.java b/src/java/org/apache/poi/ss/usermodel/Drawing.java deleted file mode 100644 index 8147ff6635..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Drawing.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -/** - * High level representation of spreadsheet drawing. - */ -public interface Drawing<T extends Shape> extends ShapeContainer<T> { - /** - * Creates a picture. - * @param anchor the client anchor describes how this picture is - * attached to the sheet. - * @param pictureIndex the index of the picture in the workbook collection - * of pictures. - * - * @return the newly created picture. - */ - Picture createPicture(ClientAnchor anchor, int pictureIndex); - - /** - * Creates a comment. - * @param anchor the client anchor describes how this comment is attached - * to the sheet. - * @return the newly created comment. - */ - Comment createCellComment(ClientAnchor anchor); - - /** - * Creates a new client anchor and sets the top-left and bottom-right - * coordinates of the anchor. - * - * @param dx1 the x coordinate in EMU within the first cell. - * @param dy1 the y coordinate in EMU within the first cell. - * @param dx2 the x coordinate in EMU within the second cell. - * @param dy2 the y coordinate in EMU within the second cell. - * @param col1 the column (0 based) of the first cell. - * @param row1 the row (0 based) of the first cell. - * @param col2 the column (0 based) of the second cell. - * @param row2 the row (0 based) of the second cell. - * @return the newly created client anchor - */ - ClientAnchor createAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2); - - /** - * Adds a new OLE Package Shape - * - * @param anchor the client anchor describes how this picture is - * attached to the sheet. - * @param storageId the storageId returned by {@link Workbook#addOlePackage(byte[], String, String, String)} - * @param pictureIndex the index of the picture (used as preview image) in the - * workbook collection of pictures. - * - * @return newly created shape - */ - ObjectData createObjectData(ClientAnchor anchor, int storageId, int pictureIndex); -} diff --git a/src/java/org/apache/poi/ss/usermodel/ExcelGeneralNumberFormat.java b/src/java/org/apache/poi/ss/usermodel/ExcelGeneralNumberFormat.java deleted file mode 100644 index 891c63e8d1..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ExcelGeneralNumberFormat.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.FieldPosition; -import java.text.Format; -import java.text.ParsePosition; -import java.util.Locale; - -/** - * A format that formats a double as Excel would, ignoring FieldPosition. - * All other operations are unsupported. - **/ -public class ExcelGeneralNumberFormat extends Format { - - private static final long serialVersionUID = 1L; - - private static final MathContext TO_10_SF = new MathContext(10, RoundingMode.HALF_UP); - - private final DecimalFormatSymbols decimalSymbols; - private final DecimalFormat integerFormat; - private final DecimalFormat decimalFormat; - private final DecimalFormat scientificFormat; - - public ExcelGeneralNumberFormat(final Locale locale) { - decimalSymbols = DecimalFormatSymbols.getInstance(locale); - scientificFormat = new DecimalFormat("0.#####E0", decimalSymbols); - DataFormatter.setExcelStyleRoundingMode(scientificFormat); - integerFormat = new DecimalFormat("#", decimalSymbols); - DataFormatter.setExcelStyleRoundingMode(integerFormat); - decimalFormat = new DecimalFormat("#.##########", decimalSymbols); - DataFormatter.setExcelStyleRoundingMode(decimalFormat); - } - - @SuppressWarnings("squid:S2111") - public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { - final double value; - if (number instanceof Number) { - value = ((Number)number).doubleValue(); - if (Double.isInfinite(value) || Double.isNaN(value)) { - return integerFormat.format(number, toAppendTo, pos); - } - } else { - // testBug54786 gets here with a date, so retain previous behaviour - return integerFormat.format(number, toAppendTo, pos); - } - - final double abs = Math.abs(value); - if (abs >= 1E11 || (abs <= 1E-10 && abs > 0)) { - return scientificFormat.format(number, toAppendTo, pos); - } else if (Math.floor(value) == value || abs >= 1E10) { - // integer, or integer portion uses all 11 allowed digits - return integerFormat.format(number, toAppendTo, pos); - } - // Non-integers of non-scientific magnitude are formatted as "up to 11 - // numeric characters, with the decimal point counting as a numeric - // character". We know there is a decimal point, so limit to 10 digits. - // https://support.microsoft.com/en-us/kb/65903 - final double rounded = new BigDecimal(value).round(TO_10_SF).doubleValue(); - return decimalFormat.format(rounded, toAppendTo, pos); - } - - public Object parseObject(String source, ParsePosition pos) { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/java/org/apache/poi/ss/usermodel/ExcelNumberFormat.java b/src/java/org/apache/poi/ss/usermodel/ExcelNumberFormat.java deleted file mode 100644 index ee544f7c9a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ExcelNumberFormat.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.util.List; - -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.ss.formula.EvaluationConditionalFormatRule; - -/** - * Object to hold a number format index and string, for various formatting evaluations - */ -public class ExcelNumberFormat { - - private final int idx; - private final String format; - - /** - * @param style - * @return null if the style is null, instance from style data format values otherwise - */ - public static ExcelNumberFormat from(CellStyle style) { - if (style == null) return null; - return new ExcelNumberFormat(style.getDataFormat(), style.getDataFormatString()); - } - - /** - * @param cell cell to extract format from - * @param cfEvaluator ConditionalFormattingEvaluator to use, or null if none in this context - * @return number format from highest-priority rule with a number format, or the cell style, or null if none of the above apply/are defined - */ - public static ExcelNumberFormat from(Cell cell, ConditionalFormattingEvaluator cfEvaluator) { - if (cell == null) return null; - - ExcelNumberFormat nf = null; - - if (cfEvaluator != null) { - // first one wins (priority order, per Excel help) - List<EvaluationConditionalFormatRule> rules = cfEvaluator.getConditionalFormattingForCell(cell); - for (EvaluationConditionalFormatRule rule : rules) { - nf = rule.getNumberFormat(); - if (nf != null) break; - } - } - if (nf == null) { - CellStyle style = cell.getCellStyle(); - nf = ExcelNumberFormat.from(style); - } - return nf; - } - - /** - * Use this carefully, prefer factory methods to ensure id/format relationships are not broken or confused. - * Left public so {@link ConditionalFormattingRule#getNumberFormat()} implementations can use it. - * @param idx Excel number format index, either a built-in or a higher custom # mapped in the workbook style table - * @param format Excel number format string for the index - */ - public ExcelNumberFormat(int idx, String format) { - this.idx = idx; - this.format = format; - } - - - - /** - * - * @return Excel number format index, either a built-in or a higher custom # mapped in the workbook style table - */ - public int getIdx() { - return idx; - } - - /** - * - * @return Excel number format string for the index - */ - public String getFormat() { - return format; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/ExcelStyleDateFormatter.java b/src/java/org/apache/poi/ss/usermodel/ExcelStyleDateFormatter.java deleted file mode 100644 index fcaed994d5..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ExcelStyleDateFormatter.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.math.RoundingMode; -import java.text.DateFormatSymbols; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.FieldPosition; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.util.LocaleUtil; - -/** - * A wrapper around a {@link SimpleDateFormat} instance, - * which handles a few Excel-style extensions that - * are not supported by {@link SimpleDateFormat}. - * Currently, the extensions are around the handling - * of elapsed time, eg rendering 1 day 2 hours - * as 26 hours. - */ -public class ExcelStyleDateFormatter extends SimpleDateFormat { - public static final char MMMMM_START_SYMBOL = '\ue001'; - public static final char MMMMM_TRUNCATE_SYMBOL = '\ue002'; - public static final char H_BRACKET_SYMBOL = '\ue010'; - public static final char HH_BRACKET_SYMBOL = '\ue011'; - public static final char M_BRACKET_SYMBOL = '\ue012'; - public static final char MM_BRACKET_SYMBOL = '\ue013'; - public static final char S_BRACKET_SYMBOL = '\ue014'; - public static final char SS_BRACKET_SYMBOL = '\ue015'; - public static final char L_BRACKET_SYMBOL = '\ue016'; - public static final char LL_BRACKET_SYMBOL = '\ue017'; - - private static final DecimalFormat format1digit; - private static final DecimalFormat format2digits; - - private static final DecimalFormat format3digit; - private static final DecimalFormat format4digits; - - static { - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(Locale.ROOT); - format1digit = new DecimalFormat("0", dfs); - format2digits = new DecimalFormat("00", dfs); - format3digit = new DecimalFormat("0", dfs); - format4digits = new DecimalFormat("00", dfs); - DataFormatter.setExcelStyleRoundingMode(format1digit, RoundingMode.DOWN); - DataFormatter.setExcelStyleRoundingMode(format2digits, RoundingMode.DOWN); - DataFormatter.setExcelStyleRoundingMode(format3digit); - DataFormatter.setExcelStyleRoundingMode(format4digits); - } - - { - setTimeZone(LocaleUtil.getUserTimeZone()); - } - - private double dateToBeFormatted; - - // no-arg constructor is private because of undefined super call with locale - - public ExcelStyleDateFormatter(String pattern) { - super(processFormatPattern(pattern), LocaleUtil.getUserLocale()); - } - - public ExcelStyleDateFormatter(String pattern, - DateFormatSymbols formatSymbols) { - super(processFormatPattern(pattern), formatSymbols); - } - - public ExcelStyleDateFormatter(String pattern, Locale locale) { - super(processFormatPattern(pattern), locale); - } - - /** - * Takes a format String, and replaces Excel specific bits - * with our detection sequences - */ - private static String processFormatPattern(String f) { - String t = f.replace("MMMMM", MMMMM_START_SYMBOL + "MMM" + MMMMM_TRUNCATE_SYMBOL); - t = t.replace("[H]", String.valueOf(H_BRACKET_SYMBOL)); - t = t.replace("[HH]", String.valueOf(HH_BRACKET_SYMBOL)); - t = t.replace("[m]", String.valueOf(M_BRACKET_SYMBOL)); - t = t.replace("[mm]", String.valueOf(MM_BRACKET_SYMBOL)); - t = t.replace("[s]", String.valueOf(S_BRACKET_SYMBOL)); - t = t.replace("[ss]", String.valueOf(SS_BRACKET_SYMBOL)); - t = t.replaceAll("s.000", "s.SSS"); - t = t.replaceAll("s.00", "s." + LL_BRACKET_SYMBOL); - t = t.replaceAll("s.0", "s." + L_BRACKET_SYMBOL); - return t; - } - - /** - * Used to let us know what the date being - * formatted is, in Excel terms, which we - * may wish to use when handling elapsed - * times. - */ - public void setDateToBeFormatted(double date) { - this.dateToBeFormatted = date; - } - - @Override - public StringBuffer format(Date date, StringBuffer paramStringBuffer, - FieldPosition paramFieldPosition) { - // Do the normal format - String s = super.format(date, paramStringBuffer, paramFieldPosition).toString(); - - // Now handle our special cases - if (s.indexOf(MMMMM_START_SYMBOL) != -1) { - s = s.replaceAll( - MMMMM_START_SYMBOL + "(\\p{L}|\\p{P})[\\p{L}\\p{P}]+" + MMMMM_TRUNCATE_SYMBOL, - "$1" - ); - } - - if (s.indexOf(H_BRACKET_SYMBOL) != -1 || - s.indexOf(HH_BRACKET_SYMBOL) != -1) { - float hours = (float) dateToBeFormatted * 24; - - s = s.replaceAll( - String.valueOf(H_BRACKET_SYMBOL), - format1digit.format(hours) - ); - s = s.replaceAll( - String.valueOf(HH_BRACKET_SYMBOL), - format2digits.format(hours) - ); - } - - if (s.indexOf(M_BRACKET_SYMBOL) != -1 || - s.indexOf(MM_BRACKET_SYMBOL) != -1) { - float minutes = (float) dateToBeFormatted * 24 * 60; - s = s.replaceAll( - String.valueOf(M_BRACKET_SYMBOL), - format1digit.format(minutes) - ); - s = s.replaceAll( - String.valueOf(MM_BRACKET_SYMBOL), - format2digits.format(minutes) - ); - } - if (s.indexOf(S_BRACKET_SYMBOL) != -1 || - s.indexOf(SS_BRACKET_SYMBOL) != -1) { - float seconds = (float) (dateToBeFormatted * 24 * 60 * 60); - s = s.replaceAll( - String.valueOf(S_BRACKET_SYMBOL), - format1digit.format(seconds) - ); - s = s.replaceAll( - String.valueOf(SS_BRACKET_SYMBOL), - format2digits.format(seconds) - ); - } - - if (s.indexOf(L_BRACKET_SYMBOL) != -1 || - s.indexOf(LL_BRACKET_SYMBOL) != -1) { - float millisTemp = (float) ((dateToBeFormatted - Math.floor(dateToBeFormatted)) * 24 * 60 * 60); - float millis = (millisTemp - (int) millisTemp); - s = s.replaceAll( - String.valueOf(L_BRACKET_SYMBOL), - format3digit.format(millis * 10.0) - ); - s = s.replaceAll( - String.valueOf(LL_BRACKET_SYMBOL), - format4digits.format(millis * 100.0) - ); - } - - return new StringBuffer(s); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof ExcelStyleDateFormatter)) { - return false; - } - - ExcelStyleDateFormatter other = (ExcelStyleDateFormatter) o; - return dateToBeFormatted == other.dateToBeFormatted; - } - - @Override - public int hashCode() { - return Double.valueOf(dateToBeFormatted).hashCode(); - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/ExtendedColor.java b/src/java/org/apache/poi/ss/usermodel/ExtendedColor.java deleted file mode 100644 index 616a61709d..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ExtendedColor.java +++ /dev/null @@ -1,263 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.util.Locale; - -/** - * Represents a XSSF-style color (based on either a - * {@link org.apache.poi.xssf.usermodel.XSSFColor} or a - * {@link org.apache.poi.hssf.record.common.ExtendedColor} - */ -public abstract class ExtendedColor implements Color { - - /** - * - * @param clr awt Color to set - */ - protected void setColor(java.awt.Color clr) { - setRGB(new byte[]{(byte)clr.getRed(), (byte)clr.getGreen(), (byte)clr.getBlue()}); - } - - /** - * @return true if the color is automatic - */ - public abstract boolean isAuto(); - - /** - * @return true if the color is indexed - */ - public abstract boolean isIndexed(); - - /** - * @return true if the color is RGB / ARGB - */ - public abstract boolean isRGB(); - - /** - * @return true if the color is from a Theme - */ - public abstract boolean isThemed(); - - /** - * @return Indexed Color index value, if {@link #isIndexed()} is true - */ - public abstract short getIndex(); - - /** - * @return Index of Theme color, if {@link #isThemed()} is true - */ - public abstract int getTheme(); - - /** - * @return Standard Red Green Blue ctColor value (RGB) bytes. - * If there was an A (Alpha) value, it will be stripped. - */ - public abstract byte[] getRGB(); - - /** - * @return Standard Alpha Red Green Blue ctColor value (ARGB) bytes. - */ - public abstract byte[] getARGB(); - - /** - * @return RGB or ARGB bytes or null - */ - protected abstract byte[] getStoredRBG(); - - /** - * Sets the Red Green Blue or Alpha Red Green Blue - * @param rgb bytes - */ - public abstract void setRGB(byte[] rgb); - - /** - * @return RGB or ARGB bytes, either stored or by index - */ - protected byte[] getRGBOrARGB() { - if (isIndexed() && getIndex() > 0) { - byte[] rgb = getIndexedRGB(); - if (rgb != null) { - return rgb; - } - } - - // Grab the colour - return getStoredRBG(); - } - - /** - * @return index color RGB bytes, if {@link #isIndexed()} == true, null if not indexed or index is invalid - */ - protected abstract byte[] getIndexedRGB(); - - /** - * @return Standard Red Green Blue ctColor value (RGB) bytes with applied tint. - * Alpha values are ignored. - */ - public byte[] getRGBWithTint() { - byte[] rgb = getStoredRBG(); - if (rgb != null) { - if(rgb.length == 4) { - byte[] tmp = new byte[3]; - System.arraycopy(rgb, 1, tmp, 0, 3); - rgb = tmp; - } - double tint = getTint(); - for (int i = 0; i < rgb.length; i++){ - rgb[i] = applyTint(rgb[i] & 0xFF, tint); - } - } - return rgb; - } - - /** - * @return the ARGB value in hex string format, eg FF00FF00. - * Works for both regular and indexed colours. - */ - public String getARGBHex() { - byte[] rgb = getARGB(); - if(rgb == null) { - return null; - } - - StringBuilder sb = new StringBuilder(); - for(byte c : rgb) { - int i = c & 0xff; - String cs = Integer.toHexString(i); - if(cs.length() == 1) { - sb.append('0'); - } - sb.append(cs); - } - return sb.toString().toUpperCase(Locale.ROOT); - } - - /** - * Sets the ARGB value from hex format, eg FF0077FF. - * Only works for regular (non-indexed) colours - * @param argb color ARGB hex string - */ - public void setARGBHex(String argb) { - if (argb.length() == 6 || argb.length() == 8) { - byte[] rgb = new byte[argb.length()/2]; - for (int i=0; i<rgb.length; i++) { - String part = argb.substring(i*2,(i+1)*2); - rgb[i] = (byte)Integer.parseInt(part, 16); - } - setRGB(rgb); - } else { - throw new IllegalArgumentException("Must be of the form 112233 or FFEEDDCC"); - } - } - - private static byte applyTint(int lum, double tint){ - if(tint > 0){ - return (byte)(lum * (1.0-tint) + (255 - 255 * (1.0-tint))); - } else if (tint < 0){ - return (byte)(lum*(1+tint)); - } else { - return (byte)lum; - } - } - - /** - * Specifies the tint value applied to the ctColor. - * - * <p> - * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final - * ctColor applied. - * </p> - * <p> - * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and - * 1.0 means 100% lighten. Also, 0.0 means no change. - * </p> - * <p> - * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where - * HLSMAX is currently 255. - * </p> - * Here are some examples of how to apply tint to ctColor: - * <blockquote> - * <pre> - * If (tint < 0) - * Lum' = Lum * (1.0 + tint) - * - * For example: Lum = 200; tint = -0.5; Darken 50% - * Lum' = 200 * (0.5) => 100 - * For example: Lum = 200; tint = -1.0; Darken 100% (make black) - * Lum' = 200 * (1.0-1.0) => 0 - * If (tint > 0) - * Lum' = Lum * (1.0-tint) + (HLSMAX - HLSMAX * (1.0-tint)) - * For example: Lum = 100; tint = 0.75; Lighten 75% - * - * Lum' = 100 * (1-.75) + (HLSMAX - HLSMAX*(1-.75)) - * = 100 * .25 + (255 - 255 * .25) - * = 25 + (255 - 63) = 25 + 192 = 217 - * For example: Lum = 100; tint = 1.0; Lighten 100% (make white) - * Lum' = 100 * (1-1) + (HLSMAX - HLSMAX*(1-1)) - * = 100 * 0 + (255 - 255 * 0) - * = 0 + (255 - 0) = 255 - * </pre> - * </blockquote> - * - * @return the tint value - */ - public abstract double getTint(); - - /** - * Specifies the tint value applied to the ctColor. - * - * <p> - * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final - * ctColor applied. - * </p> - * <p> - * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and - * 1.0 means 100% lighten. Also, 0.0 means no change. - * </p> - * <p> - * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where - * HLSMAX is currently 255. - * </p> - * Here are some examples of how to apply tint to ctColor: - * <blockquote> - * <pre> - * If (tint < 0) - * Lum' = Lum * (1.0 + tint) - * - * For example: Lum = 200; tint = -0.5; Darken 50% - * Lum' = 200 * (0.5) => 100 - * For example: Lum = 200; tint = -1.0; Darken 100% (make black) - * Lum' = 200 * (1.0-1.0) => 0 - * If (tint > 0) - * Lum' = Lum * (1.0-tint) + (HLSMAX - HLSMAX * (1.0-tint)) - * For example: Lum = 100; tint = 0.75; Lighten 75% - * - * Lum' = 100 * (1-.75) + (HLSMAX - HLSMAX*(1-.75)) - * = 100 * .25 + (255 - 255 * .25) - * = 25 + (255 - 63) = 25 + 192 = 217 - * For example: Lum = 100; tint = 1.0; Lighten 100% (make white) - * Lum' = 100 * (1-1) + (HLSMAX - HLSMAX*(1-1)) - * = 100 * 0 + (255 - 255 * 0) - * = 0 + (255 - 0) = 255 - * </pre> - * </blockquote> - * - * @param tint the tint value - */ - public abstract void setTint(double tint); -} diff --git a/src/java/org/apache/poi/ss/usermodel/FillPatternType.java b/src/java/org/apache/poi/ss/usermodel/FillPatternType.java deleted file mode 100644 index 0612c928cf..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FillPatternType.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating the style of fill pattern being used for a cell format. - * - */ -public enum FillPatternType { - - /** No background */ - NO_FILL(0), - - /** Solidly filled */ - SOLID_FOREGROUND(1), - - /** Small fine dots */ - FINE_DOTS(2), - - /** Wide dots */ - ALT_BARS(3), - - /** Sparse dots */ - SPARSE_DOTS(4), - - /** Thick horizontal bands */ - THICK_HORZ_BANDS(5), - - /** Thick vertical bands */ - THICK_VERT_BANDS(6), - - /** Thick backward facing diagonals */ - THICK_BACKWARD_DIAG(7), - - /** Thick forward facing diagonals */ - THICK_FORWARD_DIAG(8), - - /** Large spots */ - BIG_SPOTS(9), - - /** Brick-like layout */ - BRICKS(10), - - /** Thin horizontal bands */ - THIN_HORZ_BANDS(11), - - /** Thin vertical bands */ - THIN_VERT_BANDS(12), - - /** Thin backward diagonal */ - THIN_BACKWARD_DIAG(13), - - /** Thin forward diagonal */ - THIN_FORWARD_DIAG(14), - - /** Squares */ - SQUARES(15), - - /** Diamonds */ - DIAMONDS(16), - - /** Less Dots */ - LESS_DOTS(17), - - /** Least Dots */ - LEAST_DOTS(18); - - /** Codes are used by ExtendedFormatRecord in HSSF */ - private final short code; - private FillPatternType(int code) { - this.code = (short) code; - } - - public short getCode() { - return code; - } - - private static final int length = values().length; - public static FillPatternType forInt(int code) { - if (code < 0 || code > length) { - throw new IllegalArgumentException("Invalid FillPatternType code: " + code); - } - return values()[code]; - } - // it may also make sense to have an @Internal method to convert STPatternType.Enum - // but may cause errors if poi-ooxml.jar is not on the classpath - -} diff --git a/src/java/org/apache/poi/ss/usermodel/Font.java b/src/java/org/apache/poi/ss/usermodel/Font.java deleted file mode 100644 index 60b8a91dc2..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Font.java +++ /dev/null @@ -1,289 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - - -import org.apache.poi.util.Removal; - -public interface Font { - // TODO: refactor and unify Font & FontFormatting in POI 5.0.0 - // TODO: refactor the constants to enums in POI 5.0.0 - - /** - * normal type of black color. - */ - short COLOR_NORMAL = 0x7fff; - - /** - * Dark Red color - */ - short COLOR_RED = 0xa; - - /** - * no type offsetting (not super or subscript) - */ - short SS_NONE = 0; - - /** - * superscript - */ - short SS_SUPER = 1; - - /** - * subscript - */ - short SS_SUB = 2; - - /** - * not underlined - */ - byte U_NONE = 0; - - /** - * single (normal) underline - */ - byte U_SINGLE = 1; - - /** - * double underlined - */ - byte U_DOUBLE = 2; - - /** - * accounting style single underline - */ - byte U_SINGLE_ACCOUNTING = 0x21; - - /** - * accounting style double underline - */ - byte U_DOUBLE_ACCOUNTING = 0x22; - - /** - * ANSI character set - */ - byte ANSI_CHARSET = 0; - - /** - * Default character set. - */ - byte DEFAULT_CHARSET = 1; - - /** - * Symbol character set - */ - byte SYMBOL_CHARSET = 2; - - /** - * Font height is handled in points and 1/20th of points so - * this is the constant used to convert between those two units. - */ - int TWIPS_PER_POINT = 20; - - /** - * set the name for the font (i.e. Arial) - * @param name String representing the name of the font to use - */ - - void setFontName(String name); - - /** - * get the name for the font (i.e. Arial) - * @return String representing the name of the font to use - */ - - String getFontName(); - - /** - * set the font height in unit's of 1/20th of a point. Maybe you might want to - * use the setFontHeightInPoints which matches to the familiar 10, 12, 14 etc.. - * @param height height in 1/20ths of a point - * @see #setFontHeightInPoints(short) - */ - - void setFontHeight(short height); - - /** - * set the font height - * @param height height in the familiar unit of measure - points - * @see #setFontHeight(short) - */ - - void setFontHeightInPoints(short height); - - /** - * Get the font height in unit's of 1/20th of a point. - * <p> - * For many users, the related {@link #getFontHeightInPoints()} - * will be more helpful, as that returns font heights in the - * more familiar points units, eg 10, 12, 14. - - * @return short - height in 1/20ths of a point - * @see #getFontHeightInPoints() - */ - short getFontHeight(); - - /** - * Get the font height in points. - * <p> - * This will return the same font height that is shown in Excel, - * such as 10 or 14 or 28. - * @return short - height in the familiar unit of measure - points - * @see #getFontHeight() - */ - short getFontHeightInPoints(); - - /** - * set whether to use italics or not - * @param italic italics or not - */ - - void setItalic(boolean italic); - - /** - * get whether to use italics or not - * @return italics or not - */ - - boolean getItalic(); - - /** - * set whether to use a strikeout horizontal line through the text or not - * @param strikeout or not - */ - - void setStrikeout(boolean strikeout); - - /** - * get whether to use a strikeout horizontal line through the text or not - * @return strikeout or not - */ - - boolean getStrikeout(); - - /** - * set the color for the font - * @param color to use - * @see #COLOR_NORMAL Note: Use this rather than HSSFColor.AUTOMATIC for default font color - * @see #COLOR_RED - */ - - void setColor(short color); - - /** - * get the color for the font - * @return color to use - * @see #COLOR_NORMAL - * @see #COLOR_RED - * @see org.apache.poi.hssf.usermodel.HSSFPalette#getColor(short) - */ - short getColor(); - - /** - * set normal,super or subscript. - * @param offset type to use (none,super,sub) - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - - void setTypeOffset(short offset); - - /** - * get normal,super or subscript. - * @return offset type to use (none,super,sub) - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - - short getTypeOffset(); - - /** - * set type of text underlining to use - * @param underline type - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ - - void setUnderline(byte underline); - - /** - * get type of text underlining to use - * @return underlining type - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ - - byte getUnderline(); - - /** - * get character-set to use. - * @return character-set - * @see #ANSI_CHARSET - * @see #DEFAULT_CHARSET - * @see #SYMBOL_CHARSET - */ - int getCharSet(); - - /** - * set character-set to use. - * @see #ANSI_CHARSET - * @see #DEFAULT_CHARSET - * @see #SYMBOL_CHARSET - */ - void setCharSet(byte charset); - /** - * set character-set to use. - * @see #ANSI_CHARSET - * @see #DEFAULT_CHARSET - * @see #SYMBOL_CHARSET - */ - void setCharSet(int charset); - - /** - * get the index within the XSSFWorkbook (sequence within the collection of Font objects) - * - * @return unique index number of the underlying record this Font represents (probably you don't care - * unless you're comparing which one is which) - * @since 5.0.0 (used to return a short) - */ - int getIndex(); - - /** - * get the index within the XSSFWorkbook (sequence within the collection of Font objects) - * - * @deprecated use {@link #getIndex()} instead - * @return unique index number of the underlying record this Font represents (probably you don't care - * unless you're comparing which one is which) - * @since 4.0.0 - */ - @Deprecated - @Removal(version = "6.0.0") - int getIndexAsInt(); - - void setBold(boolean bold); - - boolean getBold(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/FontCharset.java b/src/java/org/apache/poi/ss/usermodel/FontCharset.java deleted file mode 100644 index 24cb65f4e5..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FontCharset.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Removal; - -/** - * Charset represents the basic set of characters associated with a font (that it can display), and - * corresponds to the ANSI codepage (8-bit or DBCS) of that character set used by a given language. - * - * @deprecated enum will be replaced by common version org.apache.poi.common.usermodel.FontCharset - */ -@Removal(version="6.0.0") -@Deprecated -public enum FontCharset { - - ANSI(0), - DEFAULT(1), - SYMBOL(2), - MAC(77), - SHIFTJIS(128), - HANGEUL(129), - JOHAB(130), - GB2312(134), - CHINESEBIG5(136), - GREEK(161), - TURKISH(162), - VIETNAMESE(163), - HEBREW(177), - ARABIC(178), - BALTIC(186), - RUSSIAN(204), - THAI(222), - EASTEUROPE(238), - OEM(255); - - - private int charset; - - private FontCharset(int value){ - charset = value; - } - - /** - * Returns value of this charset - * - * @return value of this charset - */ - public int getValue(){ - return charset; - } - - private static FontCharset[] _table = new FontCharset[256]; - static { - for (FontCharset c : values()) { - _table[c.getValue()] = c; - } - } - - public static FontCharset valueOf(int value){ - if(value >= _table.length) - return null; - return _table[value]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/FontFamily.java b/src/java/org/apache/poi/ss/usermodel/FontFamily.java deleted file mode 100644 index 829246678e..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FontFamily.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - - -/** - * 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 { - - NOT_APPLICABLE(0), - ROMAN(1), - SWISS(2), - MODERN(3), - SCRIPT(4), - DECORATIVE(5); - - private int family; - - private FontFamily(int value) { - family = value; - } - - /** - * Returns index of this font family - * - * @return index of this font family - */ - public int getValue() { - return family; - } - - private static FontFamily[] _table = new FontFamily[6]; - - static { - for (FontFamily c : values()) { - _table[c.getValue()] = c; - } - } - - public static FontFamily valueOf(int family) { - return _table[family]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/FontFormatting.java b/src/java/org/apache/poi/ss/usermodel/FontFormatting.java deleted file mode 100644 index cce523fe29..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FontFormatting.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * High level representation for Font Formatting component - * of Conditional Formatting settings - */ -public interface FontFormatting { - // TODO: refactor and unify Font & FontFormatting in POI 5.0.0 - - /** - * get the type of super or subscript for the font - * - * @return super or subscript option - * @see Font#SS_NONE - * @see Font#SS_SUPER - * @see Font#SS_SUB - */ - short getEscapementType(); - - /** - * set the escapement type for the font - * - * @param escapementType super or subscript option - * @see Font#SS_NONE - * @see Font#SS_SUPER - * @see Font#SS_SUB - */ - void setEscapementType(short escapementType); - - /** - * @return font colour index, or 0 if not indexed (XSSF only) - */ - short getFontColorIndex(); - - /** - * Sets the indexed colour to use - * @param color font colour index - */ - void setFontColorIndex(short color); - - /** - * @return The colour of the font, or null if no colour applied - */ - Color getFontColor(); - - /** - * Sets the colour to use - * @param color font colour to use - */ - void setFontColor(Color color); - - /** - * gets the height of the font in 1/20th point units - * - * @return fontheight (in points/20); or -1 if not modified - */ - int getFontHeight(); - - /** - * Sets the height of the font in 1/20th point units - * - * @param height the height in twips (in points/20) - */ - void setFontHeight(int height); - - /** - * get the type of underlining for the font - * - * @return font underlining type - * - * @see Font#U_NONE - * @see Font#U_SINGLE - * @see Font#U_DOUBLE - * @see Font#U_SINGLE_ACCOUNTING - * @see Font#U_DOUBLE_ACCOUNTING - */ - short getUnderlineType(); - - /** - * set the type of underlining type for the font - * - * @param underlineType super or subscript option - * - * @see Font#U_NONE - * @see Font#U_SINGLE - * @see Font#U_DOUBLE - * @see Font#U_SINGLE_ACCOUNTING - * @see Font#U_DOUBLE_ACCOUNTING - */ - void setUnderlineType(short underlineType); - - /** - * get whether the font weight is set to bold or not - * - * @return bold - whether the font is bold or not - */ - boolean isBold(); - - /** - * @return true if font style was set to <i>italic</i> - */ - boolean isItalic(); - - - /** - * @return true if font strikeout is on - */ - boolean isStruckout(); - - /** - * set font style options. - * - * @param italic - if true, set posture style to italic, otherwise to normal - * @param bold if true, set font weight to bold, otherwise to normal - */ - void setFontStyle(boolean italic, boolean bold); - - /** - * set font style options to default values (non-italic, non-bold) - */ - void resetFontStyle(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/FontScheme.java b/src/java/org/apache/poi/ss/usermodel/FontScheme.java deleted file mode 100644 index e1b7712309..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FontScheme.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - - -/** - * Defines the font scheme to which this font belongs. - * When a font definition is part of a theme definition, then the font is categorized as either a major or minor font scheme component. - * 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 { - - - NONE(1), - MAJOR(2), - MINOR(3); - - private int value; - - private FontScheme(int val) { - value = val; - } - - public int getValue() { - return value; - } - - private static FontScheme[] _table = new FontScheme[4]; - static { - for (FontScheme c : values()) { - _table[c.getValue()] = c; - } - } - - public static FontScheme valueOf(int value){ - return _table[value]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/FontUnderline.java b/src/java/org/apache/poi/ss/usermodel/FontUnderline.java deleted file mode 100644 index a78062b92b..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FontUnderline.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * the different types of possible underline formatting - * - * @author Gisella Bronzetti - */ -public enum FontUnderline { - - /** - * Single-line underlining under each character in the cell. - * The underline is drawn through the descenders of - * characters such as g and p.. - */ - SINGLE(1), - - /** - * Double-line underlining under each character in the - * cell. underlines are drawn through the descenders of - * characters such as g and p. - */ - DOUBLE(2), - - /** - * Single-line accounting underlining under each - * character in the cell. The underline is drawn under the - * descenders of characters such as g and p. - */ - SINGLE_ACCOUNTING(3), - - /** - * Double-line accounting underlining under each - * character in the cell. The underlines are drawn under - * the descenders of characters such as g and p. - */ - DOUBLE_ACCOUNTING(4), - - /** - * No underline. - */ - NONE(5); - - private int value; - - - private FontUnderline(int val) { - value = val; - } - - public int getValue() { - return value; - } - - public byte getByteValue() { - switch (this) { - case DOUBLE: - return Font.U_DOUBLE; - case DOUBLE_ACCOUNTING: - return Font.U_DOUBLE_ACCOUNTING; - case SINGLE_ACCOUNTING: - return Font.U_SINGLE_ACCOUNTING; - case NONE: - return Font.U_NONE; - case SINGLE: - return Font.U_SINGLE; - default: - return Font.U_SINGLE; - } - } - - private static FontUnderline[] _table = new FontUnderline[6]; - static { - for (FontUnderline c : values()) { - _table[c.getValue()] = c; - } - } - - public static FontUnderline valueOf(int value){ - return _table[value]; - } - - public static FontUnderline valueOf(byte value){ - FontUnderline val; - switch (value) { - case Font.U_DOUBLE: - val = FontUnderline.DOUBLE; - break; - case Font.U_DOUBLE_ACCOUNTING: - val = FontUnderline.DOUBLE_ACCOUNTING; - break; - case Font.U_SINGLE_ACCOUNTING: - val = FontUnderline.SINGLE_ACCOUNTING; - break; - case Font.U_SINGLE: - val = FontUnderline.SINGLE; - break; - default: - val = FontUnderline.NONE; - break; - } - return val; - } - -} diff --git a/src/java/org/apache/poi/ss/usermodel/Footer.java b/src/java/org/apache/poi/ss/usermodel/Footer.java deleted file mode 100644 index f982b71e6e..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Footer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Common definition of a HSSF or XSSF page footer. - * For a list of all the different fields that can be - * placed into a footer, such as page number, - * bold, underline etc, see - * {@link org.apache.poi.ss.usermodel.HeaderFooter}. - */ -public interface Footer extends HeaderFooter { - /** - * Get the left side of the footer. - * @return The string representing the left side. - */ - String getLeft(); - - /** - * Sets the left string. - * @param newLeft The string to set as the left side. - */ - void setLeft(String newLeft); - - /** - * Get the center of the footer. - * @return The string representing the center. - */ - String getCenter(); - - /** - * Sets the center string. - * @param newCenter The string to set as the center. - */ - void setCenter(String newCenter); - - /** - * Get the right side of the footer. - * @return The string representing the right side. - */ - String getRight(); - - /** - * Sets the right string. - * @param newRight The string to set as the right side. - */ - void setRight(String newRight); -} diff --git a/src/java/org/apache/poi/ss/usermodel/FormulaError.java b/src/java/org/apache/poi/ss/usermodel/FormulaError.java deleted file mode 100644 index 996861e75a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FormulaError.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.util.Map; - -import org.apache.poi.util.Internal; - -import java.util.HashMap; - -/** - * Enumerates error values in SpreadsheetML formula calculations. - * - * See also OOO's excelfileformat.pdf (2.5.6) - */ -public enum FormulaError { - @Internal - _NO_ERROR(-1, "(no error)"), - - /** - * Intended to indicate when two areas are required to intersect, but do not. - * <p>Example: - * In the case of SUM(B1 C1), the space between B1 and C1 is treated as the binary - * intersection operator, when a comma was intended. end example] - * </p> - */ - NULL(0x00, "#NULL!"), - - /** - * Intended to indicate when any number, including zero, is divided by zero. - * Note: However, any error code divided by zero results in that error code. - */ - DIV0(0x07, "#DIV/0!"), - - /** - * Intended to indicate when an incompatible type argument is passed to a function, or - * an incompatible type operand is used with an operator. - * <p>Example: - * In the case of a function argument, text was expected, but a number was provided - * </p> - */ - VALUE(0x0F, "#VALUE!"), - - /** - * Intended to indicate when a cell reference is invalid. - * <p>Example: - * If a formula contains a reference to a cell, and then the row or column containing that cell is deleted, - * a #REF! error results. If a worksheet does not support 20,001 columns, - * OFFSET(A1,0,20000) will result in a #REF! error. - * </p> - */ - REF(0x17, "#REF!"), - - /** - * Intended to indicate when what looks like a name is used, but no such name has been defined. - * <p>Example: - * XYZ/3, where XYZ is not a defined name. Total is & A10, - * where neither Total nor is is a defined name. Presumably, "Total is " & A10 - * was intended. SUM(A1C10), where the range A1:C10 was intended. - * </p> - */ - NAME(0x1D, "#NAME?"), - - /** - * Intended to indicate when an argument to a function has a compatible type, but has a - * value that is outside the domain over which that function is defined. (This is known as - * a domain error.) - * <p>Example: - * Certain calls to ASIN, ATANH, FACT, and SQRT might result in domain errors. - * </p> - * Intended to indicate that the result of a function cannot be represented in a value of - * the specified type, typically due to extreme magnitude. (This is known as a range - * error.) - * <p>Example: FACT(1000) might result in a range error. </p> - */ - NUM(0x24, "#NUM!"), - - /** - * Intended to indicate when a designated value is not available. - * <p>Example: - * Some functions, such as SUMX2MY2, perform a series of operations on corresponding - * elements in two arrays. If those arrays do not have the same number of elements, then - * for some elements in the longer array, there are no corresponding elements in the - * shorter one; that is, one or more values in the shorter array are not available. - * </p> - * This error value can be produced by calling the function NA - */ - NA(0x2A, "#N/A"), - - // These are POI-specific error codes - // It is desirable to make these (arbitrary) strings look clearly different from any other - // value expression that might appear in a formula. In addition these error strings should - // look unlike the standard Excel errors. Hence tilde ('~') was used. - - /** - * POI specific code to indicate that there is a circular reference - * in the formula - */ - CIRCULAR_REF(0xFFFFFFC4, "~CIRCULAR~REF~"), - /** - * POI specific code to indicate that the funcition required is - * not implemented in POI - */ - FUNCTION_NOT_IMPLEMENTED(0xFFFFFFE2, "~FUNCTION~NOT~IMPLEMENTED~"); - - private final byte type; - private final int longType; - private final String repr; - - private FormulaError(int type, String repr) { - this.type = (byte)type; - this.longType = type; - this.repr = repr; - } - - /** - * @return numeric code of the error - */ - public byte getCode() { - return type; - } - /** - * @return long (internal) numeric code of the error - */ - public int getLongCode() { - return longType; - } - - /** - * @return string representation of the error - */ - public String getString() { - return repr; - } - - private static final Map<String, FormulaError> smap = new HashMap<>(); - private static final Map<Byte, FormulaError> bmap = new HashMap<>(); - private static final Map<Integer, FormulaError> imap = new HashMap<>(); - static{ - for (FormulaError error : values()) { - bmap.put(error.getCode(), error); - imap.put(error.getLongCode(), error); - smap.put(error.getString(), error); - } - } - - public static boolean isValidCode(int errorCode) { - for (FormulaError error : values()) { - if (error.getCode() == errorCode) return true; - if (error.getLongCode() == errorCode) return true; - } - return false; - } - - public static FormulaError forInt(byte type) throws IllegalArgumentException { - FormulaError err = bmap.get(type); - if(err == null) throw new IllegalArgumentException("Unknown error type: " + type); - return err; - } - public static FormulaError forInt(int type) throws IllegalArgumentException { - FormulaError err = imap.get(type); - if(err == null) err = bmap.get((byte)type); - if(err == null) throw new IllegalArgumentException("Unknown error type: " + type); - return err; - } - - public static FormulaError forString(String code) throws IllegalArgumentException { - FormulaError err = smap.get(code); - if(err == null) throw new IllegalArgumentException("Unknown error code: " + code); - return err; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/FormulaEvaluator.java b/src/java/org/apache/poi/ss/usermodel/FormulaEvaluator.java deleted file mode 100644 index 776c022d14..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FormulaEvaluator.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.util.Removal; - -import java.util.Map; - -/** - * 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 { - - /** - * Should be called whenever there are changes to input cells in the evaluated workbook. - * Failure to call this method after changing cell values will cause incorrect behaviour - * of the evaluate~ methods of this class - */ - void clearAllCachedResultValues(); - /** - * 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 - */ - void notifyDeleteCell(Cell 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 notifyUpdateCell(Cell cell); - - /** - * Loops over all cells in all sheets of the associated workbook. - * 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 - * 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 - * the cell and also its cell type. This method should be preferred over - * evaluateInCell() when the call should not modify the contents of the - * original cell. - * @param cell The {@link Cell} to evaluate - */ - CellValue evaluate(Cell cell); - - - /** - * If cell contains formula, it evaluates the formula, - * and saves the result of the formula. The cell - * remains as a formula cell. - * Else if cell does not contain formula, this method leaves - * the cell unchanged. - * Note that the type of the formula result is returned, - * so you know what kind of value is also stored with - * the formula. - * <pre> - * int evaluatedCellType = evaluator.evaluateFormulaCell(cell); - * </pre> - * Be aware that your cell will hold both the formula, - * 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, - * 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. - */ - CellType evaluateFormulaCell(Cell cell); - - /** - * If cell contains formula, it evaluates the formula, and - * puts the formula result back into the cell, in place - * of the old formula. - * Else if cell does not contain formula, this method leaves - * the cell unchanged. - * Note that the same instance of Cell is returned to - * allow chained calls like: - * <pre> - * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType(); - * </pre> - * Be aware that your cell value will be changed to hold the - * result of the formula. If you simply want the formula - * value computed for you, use {@link #evaluateFormulaCell(Cell)} - * @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. - * <p>For a workbook referenced as [Test.xls]Sheet1!A1, you should - * supply a map containing the key Test.xls (no square brackets), - * and an open FormulaEvaluator onto that Workbook. - * @param workbooks Map of workbook names (no square brackets) to an evaluator on that workbook - */ - void setupReferencedWorkbooks(Map<String,FormulaEvaluator> workbooks); - - /** - * Whether to ignore missing references to external workbooks and - * use cached formula results in the main workbook instead. - * <p> - * 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 - * {@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 - * that already exists in the main workbook</li> - * </ul> - * - * @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); -} diff --git a/src/java/org/apache/poi/ss/usermodel/FractionFormat.java b/src/java/org/apache/poi/ss/usermodel/FractionFormat.java deleted file mode 100644 index c89838a5da..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/FractionFormat.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.poi.ss.usermodel; - -import java.math.BigDecimal; -import java.text.FieldPosition; -import java.text.Format; -import java.text.ParsePosition; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.ss.format.SimpleFraction; -import org.apache.poi.ss.formula.eval.NotImplementedException; - -/** - * <p>Format class that handles Excel style fractions, such as "# #/#" and "#/###"</p> - * - * <p>As of this writing, this is still not 100% accurate, but it does a reasonable job - * of trying to mimic Excel's fraction calculations. It does not currently - * maintain Excel's spacing.</p> - * - * <p>This class relies on a method lifted nearly verbatim from org.apache.math.fraction. - * If further uses for Commons Math are found, we will consider adding it as a dependency. - * For now, we have in-lined the one method to keep things simple.</p> - */ - -@SuppressWarnings("serial") -public class FractionFormat extends Format { - private static final Logger LOGGER = LogManager.getLogger(FractionFormat.class); - private static final Pattern DENOM_FORMAT_PATTERN = Pattern.compile("(?:(#+)|(\\d+))"); - - //this was chosen to match the earlier limitation of max denom power - //it can be expanded to get closer to Excel's calculations - //with custom formats # #/######### - //but as of this writing, the numerators and denominators - //with formats of that nature on very small values were quite - //far from Excel's calculations - private static final int MAX_DENOM_POW = 4; - - //there are two options: - //a) an exact denominator is specified in the formatString - //b) the maximum denominator can be calculated from the formatString - private final int exactDenom; - private final int maxDenom; - - private final String wholePartFormatString; - - /** - * Single parameter ctor - * @param denomFormatString The format string for the denominator - */ - public FractionFormat(String wholePartFormatString, String denomFormatString) { - this.wholePartFormatString = wholePartFormatString; - - // initialize exactDenom and maxDenom - Matcher m = DENOM_FORMAT_PATTERN.matcher(denomFormatString); - int tmpExact = -1; - int tmpMax = -1; - if (m.find()){ - if (m.group(2) != null){ - try{ - tmpExact = Integer.parseInt(m.group(2)); - //if the denom is 0, fall back to the default: tmpExact=100 - - if (tmpExact == 0){ - tmpExact = -1; - } - } catch (NumberFormatException e){ - // should not happen because the pattern already verifies that this is a number, - // but a number larger than Integer.MAX_VALUE can cause it, - // so throw an exception if we somehow end up here - throw new IllegalStateException(e); - } - } else if (m.group(1) != null) { - int len = m.group(1).length(); - len = len > MAX_DENOM_POW ? MAX_DENOM_POW : len; - tmpMax = (int)Math.pow(10, len); - } else { - tmpExact = 100; - } - } - if (tmpExact <= 0 && tmpMax <= 0){ - //use 100 as the default denom if something went horribly wrong - tmpExact = 100; - } - exactDenom = tmpExact; - maxDenom = tmpMax; - } - - @SuppressWarnings("squid:S2111") - public String format(Number num) { - - final BigDecimal doubleValue = new BigDecimal(num.doubleValue()); - - final boolean isNeg = doubleValue.compareTo(BigDecimal.ZERO) < 0; - - final BigDecimal absValue = doubleValue.abs(); - final BigDecimal wholePart = new BigDecimal(absValue.toBigInteger()); - final BigDecimal decPart = absValue.remainder(BigDecimal.ONE); - - if (wholePart.add(decPart).compareTo(BigDecimal.ZERO) == 0) { - return "0"; - } - - // if the absolute value is smaller than 1 over the exact or maxDenom - // you can stop here and return "0" - // reciprocal is result of an int devision ... and so it's nearly always 0 - // double reciprocal = 1/Math.max(exactDenom, maxDenom); - // if (absDoubleValue < reciprocal) { - // return "0"; - // } - - //this is necessary to prevent overflow in the maxDenom calculation - if (decPart.compareTo(BigDecimal.ZERO) == 0){ - - StringBuilder sb = new StringBuilder(); - if (isNeg){ - sb.append("-"); - } - sb.append(wholePart); - return sb.toString(); - } - - final SimpleFraction fract; - try { - //this should be the case because of the constructor - if (exactDenom > 0){ - fract = SimpleFraction.buildFractionExactDenominator(decPart.doubleValue(), exactDenom); - } else { - fract = SimpleFraction.buildFractionMaxDenominator(decPart.doubleValue(), maxDenom); - } - } catch (RuntimeException e){ - LOGGER.atWarn().withThrowable(e).log("Can't format fraction"); - return Double.toString(doubleValue.doubleValue()); - } - - StringBuilder sb = new StringBuilder(); - - //now format the results - if (isNeg){ - sb.append("-"); - } - - //if whole part has to go into the numerator - if (wholePartFormatString == null || wholePartFormatString.isEmpty()){ - final int fden = fract.getDenominator(); - final int fnum = fract.getNumerator(); - BigDecimal trueNum = wholePart.multiply(new BigDecimal(fden)).add(new BigDecimal(fnum)); - sb.append(trueNum.toBigInteger()).append("/").append(fden); - return sb.toString(); - } - - - //short circuit if fraction is 0 or 1 - if (fract.getNumerator() == 0){ - sb.append(wholePart); - return sb.toString(); - } else if (fract.getNumerator() == fract.getDenominator()){ - sb.append(wholePart.add(BigDecimal.ONE)); - return sb.toString(); - } - //as mentioned above, this ignores the exact space formatting in Excel - if (wholePart.compareTo(BigDecimal.ZERO) > 0){ - sb.append(wholePart).append(" "); - } - sb.append(fract.getNumerator()).append("/").append(fract.getDenominator()); - return sb.toString(); - } - - public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { - return toAppendTo.append(format((Number)obj)); - } - - public Object parseObject(String source, ParsePosition pos) { - throw new NotImplementedException("Reverse parsing not supported"); - } - -} diff --git a/src/java/org/apache/poi/ss/usermodel/Header.java b/src/java/org/apache/poi/ss/usermodel/Header.java deleted file mode 100644 index 22f38a665c..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Header.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Common definition of a HSSF or XSSF page header. - * For a list of all the different fields that can be - * placed into a header, such as page number, - * bold, underline etc, see - * {@link org.apache.poi.ss.usermodel.HeaderFooter}. - */ -public interface Header extends HeaderFooter { - /** - * Get the left side of the header. - * - * @return The string representing the left side. - */ - String getLeft(); - - /** - * Sets the left string. - * - * @param newLeft The string to set as the left side. - */ - void setLeft(String newLeft); - - /** - * Get the center of the header. - * - * @return The string representing the center. - */ - String getCenter(); - - /** - * Sets the center string. - * - * @param newCenter The string to set as the center. - */ - void setCenter(String newCenter); - - /** - * Get the right side of the header. - * - * @return The string representing the right side. - */ - String getRight(); - - /** - * Sets the right string. - * - * @param newRight The string to set as the right side. - */ - void setRight(String newRight); -} diff --git a/src/java/org/apache/poi/ss/usermodel/HeaderFooter.java b/src/java/org/apache/poi/ss/usermodel/HeaderFooter.java deleted file mode 100644 index 41c0e9ea35..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/HeaderFooter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -/** - * Common interface for {@link org.apache.poi.ss.usermodel.Header} and - * {@link org.apache.poi.ss.usermodel.Footer}. - */ -public interface HeaderFooter { - /** - * Get the left side of the header or footer. - * - * @return The string representing the left side. - */ - String getLeft(); - - /** - * Sets the left string. - * - * @param newLeft The string to set as the left side. - */ - void setLeft(String newLeft); - - /** - * Get the center of the header or footer. - * - * @return The string representing the center. - */ - String getCenter(); - - /** - * Sets the center string. - * - * @param newCenter The string to set as the center. - */ - void setCenter(String newCenter); - - /** - * Get the right side of the header or footer. - * - * @return The string representing the right side. - */ - String getRight(); - - /** - * Sets the right string or footer. - * - * @param newRight The string to set as the right side. - */ - void setRight(String newRight); -} diff --git a/src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java b/src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java deleted file mode 100644 index 6b9a313261..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating horizontal alignment of a cell, - * i.e., whether it is aligned general, left, right, horizontally centered, filled (replicated), - * justified, centered across multiple cells, or distributed. - */ -public enum HorizontalAlignment { - /** - * The horizontal alignment is general-aligned. Text data is left-aligned. - * Numbers, dates, and times are rightaligned. Boolean types are centered. - * Changing the alignment does not change the type of data. - */ - GENERAL, - - /** - * The horizontal alignment is left-aligned, even in Rightto-Left mode. - * Aligns contents at the left edge of the cell. If an indent amount is specified, the contents of - * the cell is indented from the left by the specified number of character spaces. The character spaces are - * based on the default font and font size for the workbook. - */ - LEFT, - - /** - * The horizontal alignment is centered, meaning the text is centered across the cell. - */ - CENTER, - - /** - * The horizontal alignment is right-aligned, meaning that cell contents are aligned at the right edge of the cell, - * even in Right-to-Left mode. - */ - RIGHT, - - /** - * Indicates that the value of the cell should be filled - * across the entire width of the cell. If blank cells to the right also have the fill alignment, - * they are also filled with the value, using a convention similar to centerContinuous. - * <p> - * Additional rules: - * <ol> - * <li>Only whole values can be appended, not partial values.</li> - * <li>The column will not be widened to 'best fit' the filled value</li> - * <li>If appending an additional occurrence of the value exceeds the boundary of the cell - * left/right edge, don't append the additional occurrence of the value.</li> - * <li>The display value of the cell is filled, not the underlying raw number.</li> - * </ol> - * </p> - */ - FILL, - - /** - * The horizontal alignment is justified (flush left and right). - * For each line of text, aligns each line of the wrapped text in a cell to the right and left - * (except the last line). If no single line of text wraps in the cell, then the text is not justified. - */ - JUSTIFY, - - /** - * The horizontal alignment is centered across multiple cells. - * The information about how many cells to span is expressed in the Sheet Part, - * in the row of the cell in question. For each cell that is spanned in the alignment, - * a cell element needs to be written out, with the same style Id which references the centerContinuous alignment. - */ - CENTER_SELECTION, - - /** - * Indicates that each 'word' in each line of text inside the cell is evenly distributed - * across the width of the cell, with flush right and left margins. - * <p> - * When there is also an indent value to apply, both the left and right side of the cell - * are padded by the indent value. - * </p> - * <p> A 'word' is a set of characters with no space character in them. </p> - * <p> Two lines inside a cell are separated by a carriage return. </p> - */ - DISTRIBUTED; - - public short getCode() { - return (short) ordinal(); - } - public static HorizontalAlignment forInt(int code) { - if (code < 0 || code >= values().length) { - throw new IllegalArgumentException("Invalid HorizontalAlignment code: " + code); - } - return values()[code]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/Hyperlink.java b/src/java/org/apache/poi/ss/usermodel/Hyperlink.java deleted file mode 100644 index c067cc002c..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Hyperlink.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -/** - * Represents an Excel hyperlink. - */ -public interface Hyperlink extends org.apache.poi.common.usermodel.Hyperlink { - /** - * Return the row of the first cell that contains the hyperlink - * - * @return the 0-based row of the cell that contains the hyperlink - */ - public int getFirstRow(); - - /** - * Set the row of the first cell that contains the hyperlink - * - * @param row the 0-based row of the first cell that contains the hyperlink - */ - public void setFirstRow(int row); - - /** - * Return the row of the last cell that contains the hyperlink - * - * @return the 0-based row of the last cell that contains the hyperlink - */ - public int getLastRow(); - - /** - * Set the row of the last cell that contains the hyperlink - * - * @param row the 0-based row of the last cell that contains the hyperlink - */ - public void setLastRow(int row); - - /** - * Return the column of the first cell that contains the hyperlink - * - * @return the 0-based column of the first cell that contains the hyperlink - */ - public int getFirstColumn(); - - /** - * Set the column of the first cell that contains the hyperlink - * - * @param col the 0-based column of the first cell that contains the hyperlink - */ - public void setFirstColumn(int col); - - /** - * Return the column of the last cell that contains the hyperlink - * - * @return the 0-based column of the last cell that contains the hyperlink - */ - public int getLastColumn(); - - /** - * Set the column of the last cell that contains the hyperlink - * - * @param col the 0-based column of the last cell that contains the hyperlink - */ - public void setLastColumn(int col); -} diff --git a/src/java/org/apache/poi/ss/usermodel/IconMultiStateFormatting.java b/src/java/org/apache/poi/ss/usermodel/IconMultiStateFormatting.java deleted file mode 100644 index d99630996f..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/IconMultiStateFormatting.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * High level representation for the Icon / Multi-State Formatting - * component of Conditional Formatting settings - */ -public interface IconMultiStateFormatting { - enum IconSet { - /** Green Up / Yellow Side / Red Down arrows */ - GYR_3_ARROW(0, 3, "3Arrows"), - /** Grey Up / Side / Down arrows */ - GREY_3_ARROWS(1, 3, "3ArrowsGray"), - /** Green / Yellow / Red flags */ - GYR_3_FLAGS(2, 3, "3Flags"), - /** Green / Yellow / Red traffic lights (no background). Default */ - GYR_3_TRAFFIC_LIGHTS(3, 3, "3TrafficLights1"), - /** Green / Yellow / Red traffic lights on a black square background. - * Note, MS-XLS docs v20141018 say this is id=5 but seems to be id=4 */ - GYR_3_TRAFFIC_LIGHTS_BOX(4, 3, "3TrafficLights2"), - /** Green Circle / Yellow Triangle / Red Diamond. - * Note, MS-XLS docs v20141018 say this is id=4 but seems to be id=5 */ - GYR_3_SHAPES(5, 3, "3Signs"), - /** Green Tick / Yellow ! / Red Cross on a circle background */ - GYR_3_SYMBOLS_CIRCLE(6, 3, "3Symbols"), - /** Green Tick / Yellow ! / Red Cross (no background) */ - GYR_3_SYMBOLS(7, 3, "3Symbols2"), - /** Green Up / Yellow NE / Yellow SE / Red Down arrows */ - GYR_4_ARROWS(8, 4, "4Arrows"), - /** Grey Up / NE / SE / Down arrows */ - GREY_4_ARROWS(9, 4, "4ArrowsGray"), - /** Red / Light Red / Grey / Black traffic lights */ - RB_4_TRAFFIC_LIGHTS(0xA, 4, "4RedToBlack"), - RATINGS_4(0xB, 4, "4Rating"), - /** Green / Yellow / Red / Black traffic lights */ - GYRB_4_TRAFFIC_LIGHTS(0xC, 4, "4TrafficLights"), - GYYYR_5_ARROWS(0xD, 5, "5Arrows"), - GREY_5_ARROWS(0xE, 5, "5ArrowsGray"), - RATINGS_5(0xF, 5, "5Rating"), - QUARTERS_5(0x10, 5, "5Quarters"); - - /** Numeric ID of the icon set */ - public final int id; - /** How many icons in the set */ - public final int num; - /** Name (system) of the set */ - public final String name; - - public String toString() { - return id + " - " + name; - } - - public static IconSet byId(int id) { - return values()[id]; - } - public static IconSet byName(String name) { - for (IconSet set : values()) { - if (set.name.equals(name)) return set; - } - return null; - } - - IconSet(int id, int num, String name) { - this.id = id; this.num = num; this.name = name; - } - } - - /** - * Get the Icon Set used - */ - IconSet getIconSet(); - - /** - * Changes the Icon Set used - * - * <p>If the new Icon Set has a different number of - * icons to the old one, you <em>must</em> update the - * thresholds before saving!</p> - */ - void setIconSet(IconSet set); - - /** - * Should Icon + Value be displayed, or only the Icon? - */ - boolean isIconOnly(); - /** - * Control if only the Icon is shown, or Icon + Value - */ - void setIconOnly(boolean only); - - boolean isReversed(); - void setReversed(boolean reversed); - - /** - * Gets the list of thresholds - */ - ConditionalFormattingThreshold[] getThresholds(); - /** - * Sets the of thresholds. The number must match - * {@link IconSet#num} for the current {@link #getIconSet()} - */ - void setThresholds(ConditionalFormattingThreshold[] thresholds); - /** - * Creates a new, empty Threshold - */ - ConditionalFormattingThreshold createThreshold(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/IgnoredErrorType.java b/src/java/org/apache/poi/ss/usermodel/IgnoredErrorType.java deleted file mode 100644 index 2843de4de3..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/IgnoredErrorType.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Types of ignored workbook and worksheet error. - * - * TODO Implement these for HSSF too, using FeatFormulaErr2, - * see bugzilla bug #46136 for details - */ -public enum IgnoredErrorType { - /** - * ????. Probably XSSF-only. - */ - CALCULATED_COLUMN, - - /** - * Whether to check for references to empty cells. - * HSSF + XSSF. - */ - EMPTY_CELL_REFERENCE, - - /** - * Whether to check for calculation/evaluation errors. - * HSSF + XSSF. - */ - EVALUATION_ERROR, - - /** - * Whether to check formulas in the range of the shared feature - * that are inconsistent with formulas in neighbouring cells. - * HSSF + XSSF. - */ - FORMULA, - - /** - * Whether to check formulas in the range of the shared feature - * with references to less than the entirety of a range containing - * continuous data. - * HSSF + XSSF. - */ - FORMULA_RANGE, - - /** - * ????. Is this XSSF-specific the same as performDataValidation - * in HSSF? - */ - LIST_DATA_VALIDATION, - - /** - * Whether to check the format of string values and warn - * if they look to actually be numeric values. - * HSSF + XSSF. - */ - NUMBER_STORED_AS_TEXT, - - /** - * ????. Is this XSSF-specific the same as checkDateTimeFormats - * in HSSF? - */ - TWO_DIGIT_TEXT_YEAR, - - /** - * Whether to check for unprotected formulas. - * HSSF + XSSF. - */ - UNLOCKED_FORMULA -} diff --git a/src/java/org/apache/poi/ss/usermodel/IndexedColors.java b/src/java/org/apache/poi/ss/usermodel/IndexedColors.java deleted file mode 100644 index 19053f1cc1..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/IndexedColors.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * A deprecated indexing scheme for colours that is still required for some records, and for backwards - * compatibility with OLE2 formats. - * - * <p> - * 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 { - - // 0-7 duplicates of 8-15 for compatibility (OOXML spec pt.1 sec. 18.8.27) - BLACK1(0), - WHITE1(1), - RED1(2), - BRIGHT_GREEN1(3), - BLUE1(4), - YELLOW1(5), - PINK1(6), - TURQUOISE1(7), - BLACK(8), - WHITE(9), - RED(10), - BRIGHT_GREEN(11), - BLUE(12), - YELLOW(13), - PINK(14), - TURQUOISE(15), - DARK_RED(16), - GREEN(17), - DARK_BLUE(18), - DARK_YELLOW(19), - VIOLET(20), - TEAL(21), - GREY_25_PERCENT(22), - GREY_50_PERCENT(23), - CORNFLOWER_BLUE(24), - MAROON(25), - LEMON_CHIFFON(26), - LIGHT_TURQUOISE1(27), - ORCHID(28), - CORAL(29), - ROYAL_BLUE(30), - LIGHT_CORNFLOWER_BLUE(31), - SKY_BLUE(40), - LIGHT_TURQUOISE(41), - LIGHT_GREEN(42), - LIGHT_YELLOW(43), - PALE_BLUE(44), - ROSE(45), - LAVENDER(46), - TAN(47), - LIGHT_BLUE(48), - AQUA(49), - LIME(50), - GOLD(51), - LIGHT_ORANGE(52), - ORANGE(53), - BLUE_GREY(54), - GREY_40_PERCENT(55), - DARK_TEAL(56), - SEA_GREEN(57), - DARK_GREEN(58), - OLIVE_GREEN(59), - BROWN(60), - PLUM(61), - INDIGO(62), - GREY_80_PERCENT(63), - AUTOMATIC(64); - - private static final IndexedColors[] _values = new IndexedColors[65]; - static { - for (IndexedColors color : values()) { - _values[color.index] = color; - } - } - - public final short index; - - IndexedColors(int idx){ - index = (short)idx; - } - - /** - * Returns index of this color - * - * @return index of this color - */ - public short getIndex(){ - return index; - } - - /** - * - * - * @param index the index of the color - * @return the corresponding IndexedColors enum - * @throws IllegalArgumentException if index is not a valid IndexedColors - * @since 3.15-beta2 - */ - public static IndexedColors fromInt(int index) { - if (index < 0 || index >= _values.length) { - throw new IllegalArgumentException("Illegal IndexedColor index: " + index); - } - IndexedColors color = _values[index]; - if (color == null) { - throw new IllegalArgumentException("Illegal IndexedColor index: " + index); - } - return color; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/Name.java b/src/java/org/apache/poi/ss/usermodel/Name.java deleted file mode 100644 index 03e13a83d9..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Name.java +++ /dev/null @@ -1,205 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Represents a defined name for a range of cells. - * <p> - * A name is a meaningful shorthand that makes it easier to understand the purpose of a - * cell reference, constant or a formula. - * </p> - * Examples: - * <pre><blockquote> - * Sheet sheet = workbook.createSheet("Loan Calculator"); - * Name name; - * - * name = workbook.createName(); - * name.setNameName("Interest_Rate"); - * name.setRefersToFormula("'Loan Calculator'!$E$5"); - * - * name = wb.createName(); - * name.setNameName("Loan_Amount"); - * name.setRefersToFormula("'Loan Calculator'!$E$4"); - * - * name = wb.createName(); - * name.setNameName("Number_of_Payments"); - * name.setRefersToFormula("'Loan Calculator'!$E$10"); - * - * name = wb.createName(); - * name.setNameName("Monthly_Payment"); - * name.setRefersToFormula("-PMT(Interest_Rate/12,Number_of_Payments,Loan_Amount)"); - * - * name = wb.createName(); - * name.setNameName("Values_Entered"); - * name.setRefersToFormula("IF(Loan_Amount*Interest_Rate>0,1,0)"); - * - * </blockquote></pre> - */ -public interface Name { - - /** - * Get the sheets name which this named range is referenced to - * - * @return sheet name, which this named range referred to - */ - String getSheetName(); - - /** - * Gets the name of the named range - * - * @return named range name - */ - String getNameName(); - - /** - * Sets the name of the named range - * - * <p>The following is a list of syntax rules that you need to be aware of when you create and edit names.</p> - * <ul> - * <li><strong>Valid characters</strong> - * The first character of a name must be a letter, an underscore character (_), or a backslash (\). - * Remaining characters in the name can be letters, numbers, periods, and underscore characters. - * </li> - * <li><strong>Cell references disallowed</strong> - * Names cannot be the same as a cell reference, such as Z$100 or R1C1.</li> - * <li><strong>Spaces are not valid</strong> - * Spaces are not allowed as part of a name. Use the underscore character (_) and period (.) as word separators, such as, Sales_Tax or First.Quarter. - * </li> - * <li><strong>Name length</strong> - * A name can contain up to 255 characters. - * </li> - * <li><strong>Case sensitivity</strong> - * Names can contain uppercase and lowercase letters. - * </li> - * </ul> - * <p> - * A name must always be unique within its scope. POI prevents you from defining a name that is not unique - * within its scope. However you can use the same name in different scopes. Example: - * <pre><blockquote> - * //by default names are workbook-global - * Name name; - * name = workbook.createName(); - * name.setNameName("sales_08"); - * - * name = workbook.createName(); - * name.setNameName("sales_08"); //will throw an exception: "The workbook already contains this name (case-insensitive)" - * - * //create sheet-level name - * name = workbook.createName(); - * name.setSheetIndex(0); //the scope of the name is the first sheet - * name.setNameName("sales_08"); //ok - * - * name = workbook.createName(); - * name.setSheetIndex(0); - * name.setNameName("sales_08"); //will throw an exception: "The sheet already contains this name (case-insensitive)" - * - * </blockquote></pre> - * </p> - * @param name named range name to set - * @throws IllegalArgumentException if the name is invalid or the already exists within its scope (case-insensitive) - */ - void setNameName(String name); - - /** - * Returns the formula that the name is defined to refer to. - * - * @return the reference for this name, <code>null</code> if it has not been set yet. Never empty string - * @see #setRefersToFormula(String) - */ - String getRefersToFormula(); - - /** - * Sets the formula that the name is defined to refer to. The following are representative examples: - * - * <ul> - * <li><code>'My Sheet'!$A$3</code></li> - * <li><code>8.3</code></li> - * <li><code>HR!$A$1:$Z$345</code></li> - * <li><code>SUM(Sheet1!A1,Sheet2!B2)</li> - * <li><code>-PMT(Interest_Rate/12,Number_of_Payments,Loan_Amount)</li> - * </ul> - * - * Note: Using relative values like 'A1:B1' can lead to unexpected moving of - * the cell that the name points to when working with the workbook in Microsoft Excel, - * usually using absolute references like '$A$1:$B$1' avoids this, see also - * https://superuser.com/a/1031047/126954 - * - * @param formulaText the reference for this name - * @throws IllegalArgumentException if the specified formulaText is unparsable - */ - void setRefersToFormula(String formulaText); - - /** - * Checks if this name is a function name - * - * @return true if this name is a function name - */ - boolean isFunctionName(); - - /** - * Checks if this name points to a cell that no longer exists - * - * @return <code>true</code> if the name refers to a deleted cell, <code>false</code> otherwise - */ - boolean isDeleted(); - - /** - * Checks if this name is hidden, eg one of the built-in Excel - * internal names - * - * @return <code>true</code> if the name is a hidden name, <code>false</code> otherwise - */ - boolean isHidden(); - - /** - * Tell Excel that this name applies to the worksheet with the specified index instead of the entire workbook. - * - * @param sheetId the sheet index this name applies to, -1 unsets this property making the name workbook-global - * @throws IllegalArgumentException if the sheet index is invalid. - */ - public void setSheetIndex(int sheetId); - - /** - * Returns the sheet index this name applies to. - * - * @return the sheet index this name applies to, -1 if this name applies to the entire workbook - */ - public int getSheetIndex(); - - /** - * Returns the comment the user provided when the name was created. - * - * @return the user comment for this named range - */ - public String getComment(); - - /** - * Sets the comment the user provided when the name was created. - * - * @param comment the user comment for this named range - */ - public void setComment(String comment); - - /** - * Indicates that the defined name refers to a user-defined function. - * This attribute is used when there is an add-in or other code project associated with the file. - * - * @param value <code>true</code> indicates the name refers to a function. - */ - void setFunction(boolean value); -} diff --git a/src/java/org/apache/poi/ss/usermodel/ObjectData.java b/src/java/org/apache/poi/ss/usermodel/ObjectData.java deleted file mode 100644 index 3d21b1a8d2..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ObjectData.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.io.IOException; - -import org.apache.poi.poifs.filesystem.DirectoryEntry; - -/** - * Common interface for OLE shapes, i.e. shapes linked to embedded documents - * - * @since POI 3.16-beta2 - */ -public interface ObjectData extends SimpleShape { - /** - * @return the data portion, for an ObjectData that doesn't have an associated POIFS Directory Entry - */ - byte[] getObjectData() throws IOException; - - /** - * @return does this ObjectData have an associated POIFS Directory Entry? - * (Not all do, those that don't have a data portion) - */ - boolean hasDirectoryEntry(); - - /** - * Gets the object data. Only call for ones that have - * data though. See {@link #hasDirectoryEntry()}. - * The caller has to close the corresponding POIFSFileSystem - * - * @return the object data as an OLE2 directory. - * @throws IOException if there was an error reading the data. - */ - DirectoryEntry getDirectory() throws IOException; - - /** - * @return the OLE2 Class Name of the object - */ - String getOLE2ClassName(); - - /** - * @return a filename suggestion - inspecting/interpreting the Directory object probably gives a better result - */ - String getFileName(); - - /** - * @return the preview picture - */ - PictureData getPictureData(); - - default String getContentType() { - return "binary/octet-stream"; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/PageOrder.java b/src/java/org/apache/poi/ss/usermodel/PageOrder.java deleted file mode 100644 index c3faf36b3e..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PageOrder.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Specifies printed page order. - * - * @author Gisella Bronzetti - */ -public enum PageOrder { - - /** - * Order pages vertically first, then move horizontally. - */ - DOWN_THEN_OVER(1), - /** - * Order pages horizontally first, then move vertically - */ - OVER_THEN_DOWN(2); - - - private final int order; - - - private PageOrder(int order) { - this.order = order; - } - - public int getValue() { - return order; - } - - - private static PageOrder[] _table = new PageOrder[3]; - static { - for (PageOrder c : values()) { - _table[c.getValue()] = c; - } - } - - public static PageOrder valueOf(int value){ - return _table[value]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/PaperSize.java b/src/java/org/apache/poi/ss/usermodel/PaperSize.java deleted file mode 100644 index abd65f3eaa..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PaperSize.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating the possible paper size for a sheet - * - * @author Daniele Montagni - */ -public enum PaperSize { - LETTER_PAPER, - LETTER_SMALL_PAPER, - TABLOID_PAPER, - LEDGER_PAPER, - LEGAL_PAPER, - STATEMENT_PAPER, - EXECUTIVE_PAPER, - A3_PAPER, - A4_PAPER, - A4_SMALL_PAPER, - A5_PAPER, - B4_PAPER, - B5_PAPER, - FOLIO_PAPER, - QUARTO_PAPER, - STANDARD_PAPER_10_14, - STANDARD_PAPER_11_17 -} diff --git a/src/java/org/apache/poi/ss/usermodel/PatternFormatting.java b/src/java/org/apache/poi/ss/usermodel/PatternFormatting.java deleted file mode 100644 index 0eb0c589c7..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PatternFormatting.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -/** - * @author Yegor Kozlov - */ -public interface PatternFormatting { - /** No background */ - public static final short NO_FILL = 0 ; - /** Solidly filled */ - public static final short SOLID_FOREGROUND = 1 ; - /** Small fine dots */ - public static final short FINE_DOTS = 2 ; - /** Wide dots */ - public static final short ALT_BARS = 3 ; - /** Sparse dots */ - public static final short SPARSE_DOTS = 4 ; - /** Thick horizontal bands */ - public static final short THICK_HORZ_BANDS = 5 ; - /** Thick vertical bands */ - public static final short THICK_VERT_BANDS = 6 ; - /** Thick backward facing diagonals */ - public static final short THICK_BACKWARD_DIAG = 7 ; - /** Thick forward facing diagonals */ - public static final short THICK_FORWARD_DIAG = 8 ; - /** Large spots */ - public static final short BIG_SPOTS = 9 ; - /** Brick-like layout */ - public static final short BRICKS = 10 ; - /** Thin horizontal bands */ - public static final short THIN_HORZ_BANDS = 11 ; - /** Thin vertical bands */ - public static final short THIN_VERT_BANDS = 12 ; - /** Thin backward diagonal */ - public static final short THIN_BACKWARD_DIAG = 13 ; - /** Thin forward diagonal */ - public static final short THIN_FORWARD_DIAG = 14 ; - /** Squares */ - public static final short SQUARES = 15 ; - /** Diamonds */ - public static final short DIAMONDS = 16 ; - /** Less Dots */ - public static final short LESS_DOTS = 17 ; - /** Least Dots */ - public static final short LEAST_DOTS = 18 ; - - short getFillBackgroundColor(); - short getFillForegroundColor(); - Color getFillBackgroundColorColor(); - Color getFillForegroundColorColor(); - - short getFillPattern(); - - void setFillBackgroundColor(short bg); - void setFillForegroundColor(short fg); - void setFillBackgroundColor(Color bg); - void setFillForegroundColor(Color fg); - - void setFillPattern(short fp); -} diff --git a/src/java/org/apache/poi/ss/usermodel/Picture.java b/src/java/org/apache/poi/ss/usermodel/Picture.java deleted file mode 100644 index ac7d33dd21..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Picture.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.awt.Dimension; - - -/** - * Repersents a picture in a SpreadsheetML document - */ -public interface Picture extends Shape { - - /** - * Reset the image to the dimension of the embedded image - * - * @see #resize(double, double) - */ - void resize(); - - /** - * Resize the image proportionally. - * - * @see #resize(double, double) - */ - void resize(double scale); - - /** - * Resize the image. - * <p> - * Please note, that this method works correctly only for workbooks - * with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). - * If the default font is changed the resized image can be streched vertically or horizontally. - * </p> - * <p> - * <code>resize(1.0,1.0)</code> keeps the original size,<br> - * <code>resize(0.5,0.5)</code> resize to 50% of the original,<br> - * <code>resize(2.0,2.0)</code> resizes to 200% of the original.<br> - * <code>resize({@link Double#MAX_VALUE},{@link Double#MAX_VALUE})</code> resizes to the dimension of the embedded image. - * </p> - * - * @param scaleX the amount by which the image width is multiplied relative to the original width. - * @param scaleY the amount by which the image height is multiplied relative to the original height. - */ - void resize(double scaleX, double scaleY); - - /** - * Calculate the preferred size for this picture. - * - * @return XSSFClientAnchor with the preferred size for this image - */ - ClientAnchor getPreferredSize(); - - /** - * Calculate the preferred size for this picture. - * - * @param scaleX the amount by which image width is multiplied relative to the original width. - * @param scaleY the amount by which image height is multiplied relative to the original height. - * @return ClientAnchor with the preferred size for this image - */ - ClientAnchor getPreferredSize(double scaleX, double scaleY); - - /** - * Return the dimension of the embedded image in pixel - * - * @return image dimension in pixels - */ - Dimension getImageDimension(); - - /** - * Return picture data for this picture - * - * @return picture data for this picture - */ - PictureData getPictureData(); - - /** - * @return the anchor that is used by this picture - */ - ClientAnchor getClientAnchor(); - - - /** - * @return the sheet which contains the picture - */ - Sheet getSheet(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/PictureData.java b/src/java/org/apache/poi/ss/usermodel/PictureData.java deleted file mode 100644 index 67d3cefcd1..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PictureData.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -public interface PictureData { - - /** - * Gets the picture data. - * - * @return the picture data. - */ - byte[] getData(); - - /** - * Suggests a file extension for this image. - * - * @return the file extension. - */ - String suggestFileExtension(); - - /** - * Returns the mime type for the image - */ - String getMimeType(); - - /** - * @return the POI internal image type, 0 if unknown image type - * - * @see Workbook#PICTURE_TYPE_DIB - * @see Workbook#PICTURE_TYPE_EMF - * @see Workbook#PICTURE_TYPE_JPEG - * @see Workbook#PICTURE_TYPE_PICT - * @see Workbook#PICTURE_TYPE_PNG - * @see Workbook#PICTURE_TYPE_WMF - */ - int getPictureType(); -}
\ No newline at end of file diff --git a/src/java/org/apache/poi/ss/usermodel/PrintCellComments.java b/src/java/org/apache/poi/ss/usermodel/PrintCellComments.java deleted file mode 100644 index ecbea6dafe..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PrintCellComments.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * These enumerations specify how cell comments shall be displayed for paper printing purposes. - * - * @author Gisella Bronzetti - */ -public enum PrintCellComments { - - /** - * Do not print cell comments. - */ - NONE(1), - /** - * Print cell comments as displayed. - */ - AS_DISPLAYED(2), - /** - * Print cell comments at end of document. - */ - AT_END(3); - - - private int comments; - - private PrintCellComments(int comments) { - this.comments = comments; - } - - public int getValue() { - return comments; - } - - private static PrintCellComments[] _table = new PrintCellComments[4]; - static { - for (PrintCellComments c : values()) { - _table[c.getValue()] = c; - } - } - - public static PrintCellComments valueOf(int value){ - return _table[value]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/PrintOrientation.java b/src/java/org/apache/poi/ss/usermodel/PrintOrientation.java deleted file mode 100644 index 8d5716f31e..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PrintOrientation.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating the print orientation for a sheet. - * - * @author Gisella Bronzetti - */ -public enum PrintOrientation { - - /** - * orientation not specified - */ - DEFAULT(1), - /** - * portrait orientation - */ - PORTRAIT(2), - /** - * landscape orientations - */ - LANDSCAPE(3); - - - private int orientation; - - private PrintOrientation(int orientation) { - this.orientation = orientation; - } - - - public int getValue() { - return orientation; - } - - - private static PrintOrientation[] _table = new PrintOrientation[4]; - static { - for (PrintOrientation c : values()) { - _table[c.getValue()] = c; - } - } - - public static PrintOrientation valueOf(int value){ - return _table[value]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/PrintSetup.java b/src/java/org/apache/poi/ss/usermodel/PrintSetup.java deleted file mode 100644 index bba72c3951..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/PrintSetup.java +++ /dev/null @@ -1,303 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -public interface PrintSetup { - /** Whatever the printer's default paper size is */ - public static final short PRINTER_DEFAULT_PAPERSIZE = 0; - /** US Letter 8 1/2 x 11 in */ - public static final short LETTER_PAPERSIZE = 1; - /** US Letter Small 8 1/2 x 11 in */ - public static final short LETTER_SMALL_PAGESIZE = 2; - /** US Tabloid 11 x 17 in */ - public static final short TABLOID_PAPERSIZE = 3; - /** US Ledger 17 x 11 in */ - public static final short LEDGER_PAPERSIZE = 4; - /** US Legal 8 1/2 x 14 in */ - public static final short LEGAL_PAPERSIZE = 5; - /** US Statement 5 1/2 x 8 1/2 in */ - public static final short STATEMENT_PAPERSIZE = 6; - /** US Executive 7 1/4 x 10 1/2 in */ - public static final short EXECUTIVE_PAPERSIZE = 7; - /** A3 - 297x420 mm */ - public static final short A3_PAPERSIZE = 8; - /** A4 - 210x297 mm */ - public static final short A4_PAPERSIZE = 9; - /** A4 Small - 210x297 mm */ - public static final short A4_SMALL_PAPERSIZE = 10; - /** A5 - 148x210 mm */ - public static final short A5_PAPERSIZE = 11; - /** B4 (JIS) 250x354 mm */ - public static final short B4_PAPERSIZE = 12; - /** B5 (JIS) 182x257 mm */ - public static final short B5_PAPERSIZE = 13; - /** Folio 8 1/2 x 13 in */ - public static final short FOLIO8_PAPERSIZE = 14; - /** Quarto 215x275 mm */ - public static final short QUARTO_PAPERSIZE = 15; - /** 10 x 14 in */ - public static final short TEN_BY_FOURTEEN_PAPERSIZE = 16; - /** 11 x 17 in */ - public static final short ELEVEN_BY_SEVENTEEN_PAPERSIZE = 17; - /** US Note 8 1/2 x 11 in */ - public static final short NOTE8_PAPERSIZE = 18; - /** US Envelope #9 3 7/8 x 8 7/8 */ - public static final short ENVELOPE_9_PAPERSIZE = 19; - /** US Envelope #10 4 1/8 x 9 1/2 */ - public static final short ENVELOPE_10_PAPERSIZE = 20; - /** Envelope DL 110x220 mm */ - public static final short ENVELOPE_DL_PAPERSIZE = 27; - /** Envelope C5 162x229 mm */ - public static final short ENVELOPE_CS_PAPERSIZE = 28; - public static final short ENVELOPE_C5_PAPERSIZE = 28; - /** Envelope C3 324x458 mm */ - public static final short ENVELOPE_C3_PAPERSIZE = 29; - /** Envelope C4 229x324 mm */ - public static final short ENVELOPE_C4_PAPERSIZE = 30; - /** Envelope C6 114x162 mm */ - public static final short ENVELOPE_C6_PAPERSIZE = 31; - - public static final short ENVELOPE_MONARCH_PAPERSIZE = 37; - /** A4 Extra - 9.27 x 12.69 in */ - public static final short A4_EXTRA_PAPERSIZE = 53; - /** A4 Transverse - 210x297 mm */ - public static final short A4_TRANSVERSE_PAPERSIZE = 55; - /** A4 Plus - 210x330 mm */ - public static final short A4_PLUS_PAPERSIZE = 60; - /** US Letter Rotated 11 x 8 1/2 in */ - public static final short LETTER_ROTATED_PAPERSIZE = 75; - /** A4 Rotated - 297x210 mm */ - public static final short A4_ROTATED_PAPERSIZE = 77; - - /** - * Set the paper size. - * @param size the paper size. - */ - void setPaperSize(short size); - - /** - * Set the scale. - * @param scale the scale to use - */ - void setScale(short scale); - - /** - * Set the page numbering start. - * @param start the page numbering start - */ - void setPageStart(short start); - - /** - * Set the number of pages wide to fit the sheet in - * @param width the number of pages - */ - void setFitWidth(short width); - - /** - * Set the number of pages high to fit the sheet in - * @param height the number of pages - */ - void setFitHeight(short height); - - /** - * Set whether to go left to right or top down in ordering - * @param ltor left to right - */ - void setLeftToRight(boolean ltor); - - /** - * Set whether to print in landscape - * @param ls landscape - */ - void setLandscape(boolean ls); - - /** - * Valid settings. I'm not for sure. - * @param valid Valid - */ - void setValidSettings(boolean valid); - - /** - * Set whether it is black and white - * @param mono Black and white - */ - void setNoColor(boolean mono); - - /** - * Set whether it is in draft mode - * @param d draft - */ - void setDraft(boolean d); - - /** - * Print the include notes - * @param printnotes print the notes - */ - void setNotes(boolean printnotes); - - /** - * Set no orientation. ? - * @param orientation Orientation. - */ - void setNoOrientation(boolean orientation); - - /** - * Set whether to use page start - * @param page Use page start - */ - void setUsePage(boolean page); - - /** - * Sets the horizontal resolution. - * @param resolution horizontal resolution - */ - void setHResolution(short resolution); - - /** - * Sets the vertical resolution. - * @param resolution vertical resolution - */ - void setVResolution(short resolution); - - /** - * Sets the header margin. - * @param headermargin header margin - */ - void setHeaderMargin(double headermargin); - - /** - * Sets the footer margin. - * @param footermargin footer margin - */ - void setFooterMargin(double footermargin); - - /** - * Sets the number of copies. - * @param copies number of copies - */ - void setCopies(short copies); - - /** - * Returns the paper size. - * @return paper size - */ - short getPaperSize(); - - /** - * Returns the scale. - * @return scale - */ - short getScale(); - - /** - * Returns the page start. - * @return page start - */ - short getPageStart(); - - /** - * Returns the number of pages wide to fit sheet in. - * @return number of pages wide to fit sheet in - */ - short getFitWidth(); - - /** - * Returns the number of pages high to fit the sheet in. - * @return number of pages high to fit the sheet in - */ - short getFitHeight(); - - /** - * Returns the left to right print order. - * @return left to right print order - */ - boolean getLeftToRight(); - - /** - * Returns the landscape mode. - * @return landscape mode - */ - boolean getLandscape(); - - /** - * Returns the valid settings. - * @return valid settings - */ - boolean getValidSettings(); - - /** - * Returns the black and white setting. - * @return black and white setting - */ - boolean getNoColor(); - - /** - * Returns the draft mode. - * @return draft mode - */ - boolean getDraft(); - - /** - * Returns the print notes. - * @return print notes - */ - boolean getNotes(); - - /** - * Returns the no orientation. - * @return no orientation - */ - boolean getNoOrientation(); - - /** - * Returns the use page numbers. - * @return use page numbers - */ - boolean getUsePage(); - - /** - * Returns the horizontal resolution. - * @return horizontal resolution - */ - short getHResolution(); - - /** - * Returns the vertical resolution. - * @return vertical resolution - */ - short getVResolution(); - - /** - * Returns the header margin. - * @return header margin - */ - double getHeaderMargin(); - - /** - * Returns the footer margin. - * @return footer margin - */ - double getFooterMargin(); - - /** - * Returns the number of copies. - * @return number of copies - */ - short getCopies(); - -}
\ No newline at end of file diff --git a/src/java/org/apache/poi/ss/usermodel/RangeCopier.java b/src/java/org/apache/poi/ss/usermodel/RangeCopier.java deleted file mode 100644 index c6b82a6860..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/RangeCopier.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import java.util.HashMap; -import java.util.Map; -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.Beta; - -@Beta -public abstract class RangeCopier { - private Sheet sourceSheet; - private Sheet destSheet; - private FormulaShifter horizontalFormulaShifter; - private FormulaShifter verticalFormulaShifter; - - public RangeCopier(Sheet sourceSheet, Sheet destSheet) { - this.sourceSheet = sourceSheet; - this.destSheet = destSheet; - } - - public RangeCopier(Sheet sheet) { - this(sheet, sheet); - } - - /** Uses input pattern to tile destination region, overwriting existing content. Works in following manner : - * 1.Start from top-left of destination. - * 2.Paste source but only inside of destination borders. - * 3.If there is space left on right or bottom side of copy, process it as in step 2. - * @param tilePatternRange source range which should be copied in tiled manner - * @param tileDestRange destination range, which should be overridden - */ - public void copyRange(CellRangeAddress tilePatternRange, CellRangeAddress tileDestRange) { - copyRange(tilePatternRange, tileDestRange, false, false); - } - - /** Uses input pattern to tile destination region, overwriting existing content. Works in following manner : - * 1.Start from top-left of destination. - * 2.Paste source but only inside of destination borders. - * 3.If there is space left on right or bottom side of copy, process it as in step 2. - * @param tilePatternRange source range which should be copied in tiled manner - * @param tileDestRange destination range, which should be overridden - * @param copyStyles whether to copy the cell styles - * @param copyMergedRanges whether to copy merged ranges - * @since 5.0.0 - */ - public void copyRange(CellRangeAddress tilePatternRange, CellRangeAddress tileDestRange, boolean copyStyles, boolean copyMergedRanges) { - Sheet sourceCopy = sourceSheet.getWorkbook().cloneSheet(sourceSheet.getWorkbook().getSheetIndex(sourceSheet)); - Map<Integer, CellStyle> styleMap = copyStyles ? new HashMap<Integer, CellStyle>() {} : null; - int sourceWidthMinus1 = tilePatternRange.getLastColumn() - tilePatternRange.getFirstColumn(); - int sourceHeightMinus1 = tilePatternRange.getLastRow() - tilePatternRange.getFirstRow(); - int rightLimitToCopy; - int bottomLimitToCopy; - - int nextRowIndexToCopy = tileDestRange.getFirstRow(); - do { - int nextCellIndexInRowToCopy = tileDestRange.getFirstColumn(); - int heightToCopyMinus1 = Math.min(sourceHeightMinus1, tileDestRange.getLastRow() - nextRowIndexToCopy); - bottomLimitToCopy = tilePatternRange.getFirstRow() + heightToCopyMinus1; - do { - int widthToCopyMinus1 = Math.min(sourceWidthMinus1, tileDestRange.getLastColumn() - nextCellIndexInRowToCopy); - rightLimitToCopy = tilePatternRange.getFirstColumn() + widthToCopyMinus1; - CellRangeAddress rangeToCopy = new CellRangeAddress( - tilePatternRange.getFirstRow(), bottomLimitToCopy, - tilePatternRange.getFirstColumn(), rightLimitToCopy - ); - copyRange(rangeToCopy, nextCellIndexInRowToCopy - rangeToCopy.getFirstColumn(), nextRowIndexToCopy - rangeToCopy.getFirstRow(), sourceCopy, styleMap); - nextCellIndexInRowToCopy += widthToCopyMinus1 + 1; - } while (nextCellIndexInRowToCopy <= tileDestRange.getLastColumn()); - nextRowIndexToCopy += heightToCopyMinus1 + 1; - } while (nextRowIndexToCopy <= tileDestRange.getLastRow()); - - if (copyMergedRanges) { - sourceSheet.getMergedRegions().forEach((mergedRangeAddress) -> destSheet.addMergedRegion(mergedRangeAddress)); - } - - int tempCopyIndex = sourceSheet.getWorkbook().getSheetIndex(sourceCopy); - sourceSheet.getWorkbook().removeSheetAt(tempCopyIndex); - } - - private void copyRange(CellRangeAddress sourceRange, int deltaX, int deltaY, Sheet sourceClone, Map<Integer, CellStyle> styleMap) { //NOSONAR, it's a bit complex but monolith method, does not make much sense to divide it - if(deltaX != 0) - horizontalFormulaShifter = FormulaShifter.createForColumnCopy(sourceSheet.getWorkbook().getSheetIndex(sourceSheet), - sourceSheet.getSheetName(), sourceRange.getFirstColumn(), sourceRange.getLastColumn(), deltaX, sourceSheet.getWorkbook().getSpreadsheetVersion()); - if(deltaY != 0) - verticalFormulaShifter = FormulaShifter.createForRowCopy(sourceSheet.getWorkbook().getSheetIndex(sourceSheet), - sourceSheet.getSheetName(), sourceRange.getFirstRow(), sourceRange.getLastRow(), deltaY, sourceSheet.getWorkbook().getSpreadsheetVersion()); - - for(int rowNo = sourceRange.getFirstRow(); rowNo <= sourceRange.getLastRow(); rowNo++) { - // copy from source copy, original source might be overridden in process! - Row sourceRow = sourceClone.getRow(rowNo); - if(sourceRow == null) { - continue; - } - - for (int columnIndex = sourceRange.getFirstColumn(); columnIndex <= sourceRange.getLastColumn(); columnIndex++) { - Cell sourceCell = sourceRow.getCell(columnIndex); - if(sourceCell == null) - continue; - Row destRow = destSheet.getRow(rowNo + deltaY); - if(destRow == null) - destRow = destSheet.createRow(rowNo + deltaY); - - Cell newCell = destRow.getCell(columnIndex + deltaX); - if(newCell == null) { - newCell = destRow.createCell(columnIndex + deltaX); - } - - cloneCellContent(sourceCell, newCell, styleMap); - if(newCell.getCellType() == CellType.FORMULA) - adjustCellReferencesInsideFormula(newCell, destSheet, deltaX, deltaY); - } - } - } - - protected abstract void adjustCellReferencesInsideFormula(Cell cell, Sheet destSheet, int deltaX, int deltaY); // this part is different for HSSF and XSSF - - protected boolean adjustInBothDirections(Ptg[] ptgs, int sheetIndex, int deltaX, int deltaY) { - boolean adjustSucceeded = true; - if(deltaY != 0) - adjustSucceeded = verticalFormulaShifter.adjustFormula(ptgs, sheetIndex); - if(deltaX != 0) - adjustSucceeded = adjustSucceeded && horizontalFormulaShifter.adjustFormula(ptgs, sheetIndex); - return adjustSucceeded; - } - - // TODO clone some more properties ? - public static void cloneCellContent(Cell srcCell, Cell destCell, Map<Integer, CellStyle> styleMap) { - if(styleMap != null) { - if(srcCell.getSheet().getWorkbook() == destCell.getSheet().getWorkbook()){ - destCell.setCellStyle(srcCell.getCellStyle()); - } else { - int stHashCode = srcCell.getCellStyle().hashCode(); - CellStyle newCellStyle = styleMap.get(stHashCode); - if(newCellStyle == null){ - newCellStyle = destCell.getSheet().getWorkbook().createCellStyle(); - newCellStyle.cloneStyleFrom(srcCell.getCellStyle()); - styleMap.put(stHashCode, newCellStyle); - } - destCell.setCellStyle(newCellStyle); - } - } - switch(srcCell.getCellType()) { - case STRING: - destCell.setCellValue(srcCell.getStringCellValue()); - break; - case NUMERIC: - destCell.setCellValue(srcCell.getNumericCellValue()); - break; - case BLANK: - destCell.setBlank(); - break; - case BOOLEAN: - destCell.setCellValue(srcCell.getBooleanCellValue()); - break; - case ERROR: - destCell.setCellErrorValue(srcCell.getErrorCellValue()); - break; - case FORMULA: - String oldFormula = srcCell.getCellFormula(); - destCell.setCellFormula(oldFormula); - break; - default: - break; - } - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/ReadingOrder.java b/src/java/org/apache/poi/ss/usermodel/ReadingOrder.java deleted file mode 100644 index 0544cb1542..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ReadingOrder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * The enumeration value indicating reading order of a cell, - * i.e., whether the reading order is Context(Default), Left To Right or Right To Left - */ -public enum ReadingOrder { - /** - * The reading order is Context(Default). - */ - CONTEXT, - - /** - * The reading order is Left To Right. - */ - LEFT_TO_RIGHT, - - /** - * The reading order is Right To Left. - */ - RIGHT_TO_LEFT; - - public short getCode() { - return (short) ordinal(); - } - - public static ReadingOrder forLong(long code) { - if (code < 0 || code >= values().length) { - throw new IllegalArgumentException("Invalid ReadingOrder code: " + code); - } - return values()[(int)code]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/RichTextString.java b/src/java/org/apache/poi/ss/usermodel/RichTextString.java deleted file mode 100644 index 551fede973..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/RichTextString.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * 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. - * - * @param startIndex The start index to apply the font to (inclusive) - * @param endIndex The end index to apply the font to (exclusive) - * @param fontIndex The font to use. - */ - void applyFont(int startIndex, int endIndex, short fontIndex); - - /** - * Applies a font to the specified characters of a string. - * - * @param startIndex The start index to apply the font to (inclusive) - * @param endIndex The end index to apply to font to (exclusive) - * @param font The index of the font to use. - */ - void applyFont(int startIndex, int endIndex, Font font); - - /** - * Sets the font of the entire string. - * @param font The font to use. - */ - void applyFont(Font font); - - /** - * Removes any formatting that may have been applied to the string. - */ - void clearFormatting(); - - /** - * Returns the plain string representation. - */ - String getString(); - - /** - * @return the number of characters in the font. - */ - int length(); - - /** - * @return The number of formatting runs used. - * - */ - int numFormattingRuns(); - - /** - * The index within the string to which the specified formatting run applies. - * @param index the index of the formatting run - * @return the index within the string. - */ - int getIndexOfFormattingRun(int index); - - /** - * Applies the specified font to the entire string. - * - * @param fontIndex the font to apply. - */ - void applyFont(short fontIndex); - -}
\ No newline at end of file diff --git a/src/java/org/apache/poi/ss/usermodel/Row.java b/src/java/org/apache/poi/ss/usermodel/Row.java deleted file mode 100644 index ff27f4e826..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Row.java +++ /dev/null @@ -1,240 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.util.Iterator; - -/** - * High level representation of a row of a spreadsheet. - */ -public interface Row extends Iterable<Cell> { - - /** - * Use this to create new cells within the row and return it. - * <p> - * The cell that is returned is a {@link CellType#BLANK}. The type can be changed - * either through calling <code>setCellValue</code> or <code>setCellType</code>. - * - * @param column - the column number this cell represents - * @return Cell a high level representation of the created cell. - * @throws IllegalArgumentException if columnIndex < 0 or greater than the maximum number of supported columns - * (255 for *.xls, 1048576 for *.xlsx) - */ - Cell createCell(int column); - - /** - * Use this to create new cells within the row and return it. - * <p> - * The cell that is returned will be of the requested type. - * The type can be changed either through calling setCellValue - * or setCellType, but there is a small overhead to doing this, - * so it is best to create of the required type up front. - * - * @param column - the column number this cell represents - * @param type - the cell's data type - * @return Cell a high level representation of the created cell. - * @throws IllegalArgumentException if columnIndex < 0 or greater than a maximum number of supported columns - * (255 for *.xls, 1048576 for *.xlsx) - */ - Cell createCell(int column, CellType type); - - /** - * Remove the Cell from this row. - * - * @param cell the cell to remove - */ - void removeCell(Cell cell); - - /** - * Set the row number of this row. - * - * @param rowNum the row number (0-based) - * @throws IllegalArgumentException if rowNum < 0 - */ - void setRowNum(int rowNum); - - /** - * Get row number this row represents - * - * @return the row number (0 based) - */ - int getRowNum(); - - /** - * Get the cell representing a given column (logical cell) 0-based. If you - * ask for a cell that is not defined....you get a null. - * - * @param cellnum 0 based column number - * @return Cell representing that column or null if undefined. - * @see #getCell(int, org.apache.poi.ss.usermodel.Row.MissingCellPolicy) - */ - Cell getCell(int cellnum); - - /** - * Returns the cell at the given (0 based) index, with the specified {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy} - * - * @return the cell at the given (0 based) index - * @throws IllegalArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid - */ - Cell getCell(int cellnum, MissingCellPolicy policy); - - /** - * Get the number of the first cell contained in this row. - * - * Note: cells which had content before and were set to empty later might - * still be counted as cells by Excel and Apache POI, so the result of this - * method will include such rows and thus the returned value might be lower - * than expected! - * - * @return short representing the first logical cell in the row, - * or -1 if the row does not contain any cells. - */ - short getFirstCellNum(); - - /** - * Gets the index of the last cell contained in this row <b>PLUS ONE</b>. The result also - * happens to be the 1-based column number of the last cell. This value can be used as a - * standard upper bound when iterating over cells: - * <pre> - * short minColIx = row.getFirstCellNum(); - * short maxColIx = row.getLastCellNum(); - * for(short colIx=minColIx; colIx<maxColIx; colIx++) { - * Cell cell = row.getCell(colIx); - * if(cell == null) { - * continue; - * } - * //... do something with cell - * } - * </pre> - * - * Note: cells which had content before and were set to empty later might - * still be counted as cells by Excel and Apache POI, so the result of this - * method will include such rows and thus the returned value might be higher - * than expected! - * - * @return short representing the last logical cell in the row <b>PLUS ONE</b>, - * or -1 if the row does not contain any cells. - */ - short getLastCellNum(); - - /** - * Gets the number of defined cells (NOT number of cells in the actual row!). - * That is to say if only columns 0,4,5 have values then there would be 3. - * - * @return int representing the number of defined cells in the row. - */ - int getPhysicalNumberOfCells(); - - /** - * Set the row's height or set to ff (-1) for undefined/default-height. Set the height in "twips" or - * 1/20th of a point. - * - * @param height rowheight or 0xff for undefined (use sheet default) - */ - void setHeight(short height); - - /** - * Set whether or not to display this row with 0 height - * - * @param zHeight height is zero or not. - */ - void setZeroHeight(boolean zHeight); - - /** - * Get whether or not to display this row with 0 height - * - * @return - zHeight height is zero or not. - */ - boolean getZeroHeight(); - - /** - * Set the row's height in points. - * - * @param height the height in points. <code>-1</code> resets to the default height - */ - void setHeightInPoints(float height); - - /** - * Get the row's height measured in twips (1/20th of a point). If the height is not set, the default worksheet value is returned, - * See {@link Sheet#getDefaultRowHeightInPoints()} - * - * @return row height measured in twips (1/20th of a point) - */ - short getHeight(); - - /** - * Returns row height measured in point size. If the height is not set, the default worksheet value is returned, - * See {@link Sheet#getDefaultRowHeightInPoints()} - * - * @return row height measured in point size - * @see Sheet#getDefaultRowHeightInPoints() - */ - float getHeightInPoints(); - - /** - * Is this row formatted? Most aren't, but some rows - * do have whole-row styles. For those that do, you - * can get the formatting from {@link #getRowStyle()} - */ - boolean isFormatted(); - - /** - * Returns the whole-row cell styles. Most rows won't - * have one of these, so will return null. Call - * {@link #isFormatted()} to check first. - */ - CellStyle getRowStyle(); - - /** - * Applies a whole-row cell styling to the row. - */ - void setRowStyle(CellStyle style); - - /** - * @return Cell iterator of the physically defined cells. Note element 4 may - * actually be row cell depending on how many are defined! - */ - Iterator<Cell> cellIterator(); - - /** - * Returns the Sheet this row belongs to - * - * @return the Sheet that owns this row - */ - Sheet getSheet(); - - /** - * Used to specify the different possible policies - * if for the case of null and blank cells - */ - public enum MissingCellPolicy { - RETURN_NULL_AND_BLANK, - RETURN_BLANK_AS_NULL, - CREATE_NULL_AS_BLANK - } - - /** - * Returns the rows outline level. Increased as you - * put it into more groups (outlines), reduced as - * you take it out of them. - */ - public int getOutlineLevel(); - - public void shiftCellsRight(int firstShiftColumnIndex, int lastShiftColumnIndex, int step); - public void shiftCellsLeft(int firstShiftColumnIndex, int lastShiftColumnIndex, int step); -} diff --git a/src/java/org/apache/poi/ss/usermodel/Shape.java b/src/java/org/apache/poi/ss/usermodel/Shape.java deleted file mode 100644 index f9e3874a75..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Shape.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Common interface for all drawing shapes - * - * @since POI 3.16-beta2 - */ -public interface Shape { - /** - * @return the name of this shape - */ - String getShapeName(); - - /** - * @return the parent shape. - */ - Shape getParent(); - - /** - * @return the anchor that is used by this shape. - */ - ChildAnchor getAnchor(); - - /** - * Whether this shape is not filled with a color - * - * @return true if this shape is not filled with a color. - */ - boolean isNoFill(); - - /** - * Sets whether this shape is filled or transparent. - * - * @param noFill if true then no fill will be applied to the shape element. - */ - void setNoFill(boolean noFill); - - /** - * Sets the color used to fill this shape using the solid fill pattern. - */ - void setFillColor(int red, int green, int blue); - - /** - * The color applied to the lines of this shape. - */ - void setLineStyleColor(int red, int green, int blue); -} diff --git a/src/java/org/apache/poi/ss/usermodel/ShapeContainer.java b/src/java/org/apache/poi/ss/usermodel/ShapeContainer.java deleted file mode 100644 index d0867b9b07..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ShapeContainer.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * A common interface for shape groups. - * - * @since POI 3.16-beta2 - */ -public interface ShapeContainer<T extends Shape> extends Iterable<T> { - -} diff --git a/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java b/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java deleted file mode 100644 index 3c5747ee5a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java +++ /dev/null @@ -1,212 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -/** - * All known types of automatic shapes in DrawingML - * - * @author Yegor Kozlov - */ -public class ShapeTypes { - public static final int LINE = 1; - public static final int LINE_INV = 2; - public static final int TRIANGLE = 3; - public static final int RT_TRIANGLE = 4; - public static final int RECT = 5; - public static final int DIAMOND = 6; - public static final int PARALLELOGRAM = 7; - public static final int TRAPEZOID = 8; - public static final int NON_ISOSCELES_TRAPEZOID = 9; - public static final int PENTAGON = 10; - public static final int HEXAGON = 11; - public static final int HEPTAGON = 12; - public static final int OCTAGON = 13; - public static final int DECAGON = 14; - public static final int DODECAGON = 15; - public static final int STAR_4 = 16; - public static final int STAR_5 = 17; - public static final int STAR_6 = 18; - public static final int STAR_7 = 19; - public static final int STAR_8 = 20; - public static final int STAR_10 = 21; - public static final int STAR_12 = 22; - public static final int STAR_16 = 23; - public static final int STAR_24 = 24; - public static final int STAR_32 = 25; - public static final int ROUND_RECT = 26; - public static final int ROUND_1_RECT = 27; - public static final int ROUND_2_SAME_RECT = 28; - public static final int ROUND_2_DIAG_RECT = 29; - public static final int SNIP_ROUND_RECT = 30; - public static final int SNIP_1_RECT = 31; - public static final int SNIP_2_SAME_RECT = 32; - public static final int SNIP_2_DIAG_RECT = 33; - public static final int PLAQUE = 34; - public static final int ELLIPSE = 35; - public static final int TEARDROP = 36; - public static final int HOME_PLATE = 37; - public static final int CHEVRON = 38; - public static final int PIE_WEDGE = 39; - public static final int PIE = 40; - public static final int BLOCK_ARC = 41; - public static final int DONUT = 42; - public static final int NO_SMOKING = 43; - public static final int RIGHT_ARROW = 44; - public static final int LEFT_ARROW = 45; - public static final int UP_ARROW = 46; - public static final int DOWN_ARROW = 47; - public static final int STRIPED_RIGHT_ARROW = 48; - public static final int NOTCHED_RIGHT_ARROW = 49; - public static final int BENT_UP_ARROW = 50; - public static final int LEFT_RIGHT_ARROW = 51; - public static final int UP_DOWN_ARROW = 52; - public static final int LEFT_UP_ARROW = 53; - public static final int LEFT_RIGHT_UP_ARROW = 54; - public static final int QUAD_ARROW = 55; - public static final int LEFT_ARROW_CALLOUT = 56; - public static final int RIGHT_ARROW_CALLOUT = 57; - public static final int UP_ARROW_CALLOUT = 58; - public static final int DOWN_ARROW_CALLOUT = 59; - public static final int LEFT_RIGHT_ARROW_CALLOUT = 60; - public static final int UP_DOWN_ARROW_CALLOUT = 61; - public static final int QUAD_ARROW_CALLOUT = 62; - public static final int BENT_ARROW = 63; - public static final int UTURN_ARROW = 64; - public static final int CIRCULAR_ARROW = 65; - public static final int LEFT_CIRCULAR_ARROW = 66; - public static final int LEFT_RIGHT_CIRCULAR_ARROW = 67; - public static final int CURVED_RIGHT_ARROW = 68; - public static final int CURVED_LEFT_ARROW = 69; - public static final int CURVED_UP_ARROW = 70; - public static final int CURVED_DOWN_ARROW = 71; - public static final int SWOOSH_ARROW = 72; - public static final int CUBE = 73; - public static final int CAN = 74; - public static final int LIGHTNING_BOLT = 75; - public static final int HEART = 76; - public static final int SUN = 77; - public static final int MOON = 78; - public static final int SMILEY_FACE = 79; - public static final int IRREGULAR_SEAL_1 = 80; - public static final int IRREGULAR_SEAL_2 = 81; - public static final int FOLDED_CORNER = 82; - public static final int BEVEL = 83; - public static final int FRAME = 84; - public static final int HALF_FRAME = 85; - public static final int CORNER = 86; - public static final int DIAG_STRIPE = 87; - public static final int CHORD = 88; - public static final int ARC = 89; - public static final int LEFT_BRACKET = 90; - public static final int RIGHT_BRACKET = 91; - public static final int LEFT_BRACE = 92; - public static final int RIGHT_BRACE = 93; - public static final int BRACKET_PAIR = 94; - public static final int BRACE_PAIR = 95; - public static final int STRAIGHT_CONNECTOR_1 = 96; - public static final int BENT_CONNECTOR_2 = 97; - public static final int BENT_CONNECTOR_3 = 98; - public static final int BENT_CONNECTOR_4 = 99; - public static final int BENT_CONNECTOR_5 = 100; - public static final int CURVED_CONNECTOR_2 = 101; - public static final int CURVED_CONNECTOR_3 = 102; - public static final int CURVED_CONNECTOR_4 = 103; - public static final int CURVED_CONNECTOR_5 = 104; - public static final int CALLOUT_1 = 105; - public static final int CALLOUT_2 = 106; - public static final int CALLOUT_3 = 107; - public static final int ACCENT_CALLOUT_1 = 108; - public static final int ACCENT_CALLOUT_2 = 109; - public static final int ACCENT_CALLOUT_3 = 110; - public static final int BORDER_CALLOUT_1 = 111; - public static final int BORDER_CALLOUT_2 = 112; - public static final int BORDER_CALLOUT_3 = 113; - public static final int ACCENT_BORDER_CALLOUT_1 = 114; - public static final int ACCENT_BORDER_CALLOUT_2 = 115; - public static final int ACCENT_BORDER_CALLOUT_3 = 116; - public static final int WEDGE_RECT_CALLOUT = 117; - public static final int WEDGE_ROUND_RECT_CALLOUT = 118; - public static final int WEDGE_ELLIPSE_CALLOUT = 119; - public static final int CLOUD_CALLOUT = 120; - public static final int CLOUD = 121; - public static final int RIBBON = 122; - public static final int RIBBON_2 = 123; - public static final int ELLIPSE_RIBBON = 124; - public static final int ELLIPSE_RIBBON_2 = 125; - public static final int LEFT_RIGHT_RIBBON = 126; - public static final int VERTICAL_SCROLL = 127; - public static final int HORIZONTAL_SCROLL = 128; - public static final int WAVE = 129; - public static final int DOUBLE_WAVE = 130; - public static final int PLUS = 131; - public static final int FLOW_CHART_PROCESS = 132; - public static final int FLOW_CHART_DECISION = 133; - public static final int FLOW_CHART_INPUT_OUTPUT = 134; - public static final int FLOW_CHART_PREDEFINED_PROCESS = 135; - public static final int FLOW_CHART_INTERNAL_STORAGE = 136; - public static final int FLOW_CHART_DOCUMENT = 137; - public static final int FLOW_CHART_MULTIDOCUMENT = 138; - public static final int FLOW_CHART_TERMINATOR = 139; - public static final int FLOW_CHART_PREPARATION = 140; - public static final int FLOW_CHART_MANUAL_INPUT = 141; - public static final int FLOW_CHART_MANUAL_OPERATION = 142; - public static final int FLOW_CHART_CONNECTOR = 143; - public static final int FLOW_CHART_PUNCHED_CARD = 144; - public static final int FLOW_CHART_PUNCHED_TAPE = 145; - public static final int FLOW_CHART_SUMMING_JUNCTION = 146; - public static final int FLOW_CHART_OR = 147; - public static final int FLOW_CHART_COLLATE = 148; - public static final int FLOW_CHART_SORT = 149; - public static final int FLOW_CHART_EXTRACT = 150; - public static final int FLOW_CHART_MERGE = 151; - public static final int FLOW_CHART_OFFLINE_STORAGE = 152; - public static final int FLOW_CHART_ONLINE_STORAGE = 153; - public static final int FLOW_CHART_MAGNETIC_TAPE = 154; - public static final int FLOW_CHART_MAGNETIC_DISK = 155; - public static final int FLOW_CHART_MAGNETIC_DRUM = 156; - public static final int FLOW_CHART_DISPLAY = 157; - public static final int FLOW_CHART_DELAY = 158; - public static final int FLOW_CHART_ALTERNATE_PROCESS = 159; - public static final int FLOW_CHART_OFFPAGE_CONNECTOR = 160; - public static final int ACTION_BUTTON_BLANK = 161; - public static final int ACTION_BUTTON_HOME = 162; - public static final int ACTION_BUTTON_HELP = 163; - public static final int ACTION_BUTTON_INFORMATION = 164; - public static final int ACTION_BUTTON_FORWARD_NEXT = 165; - public static final int ACTION_BUTTON_BACK_PREVIOUS = 166; - public static final int ACTION_BUTTON_END = 167; - public static final int ACTION_BUTTON_BEGINNING = 168; - public static final int ACTION_BUTTON_RETURN = 169; - public static final int ACTION_BUTTON_DOCUMENT = 170; - public static final int ACTION_BUTTON_SOUND = 171; - public static final int ACTION_BUTTON_MOVIE = 172; - public static final int GEAR_6 = 173; - public static final int GEAR_9 = 174; - public static final int FUNNEL = 175; - public static final int MATH_PLUS = 176; - public static final int MATH_MINUS = 177; - public static final int MATH_MULTIPLY = 178; - public static final int MATH_DIVIDE = 179; - public static final int MATH_EQUAL = 180; - public static final int MATH_NOT_EQUAL = 181; - public static final int CORNER_TABS = 182; - public static final int SQUARE_TABS = 183; - public static final int PLAQUE_TABS = 184; - public static final int CHART_X = 185; - public static final int CHART_STAR = 186; - public static final int CHART_PLUS = 187; -} diff --git a/src/java/org/apache/poi/ss/usermodel/Sheet.java b/src/java/org/apache/poi/ss/usermodel/Sheet.java deleted file mode 100644 index bc93818a5c..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Sheet.java +++ /dev/null @@ -1,1199 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.PaneInformation; - -/** - * High level representation of a Excel worksheet. - * - * <p> - * Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. - * The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can - * contain text, numbers, dates, and formulas. Cells can also be formatted. - * </p> - */ -public interface Sheet extends Iterable<Row> { - - /* Constants for margins */ - short LeftMargin = 0; - - short RightMargin = 1; - - short TopMargin = 2; - - short BottomMargin = 3; - - short HeaderMargin = 4; - - short FooterMargin = 5; - - byte PANE_LOWER_RIGHT = (byte) 0; - - byte PANE_UPPER_RIGHT = (byte) 1; - - byte PANE_LOWER_LEFT = (byte) 2; - - byte PANE_UPPER_LEFT = (byte) 3; - - /** - * Create a new row within the sheet and return the high level representation - * - * @param rownum row number - * @return high level Row object representing a row in the sheet - * @see #removeRow(Row) - */ - Row createRow(int rownum); - - /** - * Remove a row from this sheet. All cells contained in the row are removed as well - * - * @param row representing a row to remove. - */ - void removeRow(Row row); - - /** - * Returns the logical row (not physical) 0-based. If you ask for a row that is not - * defined you get a null. This is to say row 4 represents the fifth row on a sheet. - * - * @param rownum row to get (0-based) - * @return Row representing the row-number or null if its not defined on the sheet - */ - Row getRow(int rownum); - - /** - * Returns the number of physically defined rows (NOT the number of rows in the sheet) - * - * @return the number of physically defined rows in this sheet - */ - int getPhysicalNumberOfRows(); - - /** - * Gets the first row on the sheet. - * - * Note: rows which had content before and were set to empty later might - * still be counted as rows by Excel and Apache POI, so the result of this - * method will include such rows and thus the returned value might be lower - * than expected! - * - * @return the number of the first logical row on the sheet (0-based) - * or -1 if no row exists - */ - int getFirstRowNum(); - - /** - * Gets the last row on the sheet - * - * Note: rows which had content before and were set to empty later might - * still be counted as rows by Excel and Apache POI, so the result of this - * method will include such rows and thus the returned value might be higher - * than expected! - * - * @return last row contained on this sheet (0-based) or -1 if no row exists - */ - int getLastRowNum(); - - /** - * Get the visibility state for a given column - * - * @param columnIndex - the column to get (0-based) - * @param hidden - the visibility state of the column - */ - void setColumnHidden(int columnIndex, boolean hidden); - - /** - * 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 - */ - boolean isColumnHidden(int columnIndex); - - /** - * Sets whether the worksheet is displayed from right to left instead of from left to right. - * - * @param value true for right to left, false otherwise. - */ - void setRightToLeft(boolean value); - - /** - * Whether the text is displayed in right-to-left mode in the window - * - * @return whether the text is displayed in right-to-left mode in the window - */ - boolean isRightToLeft(); - - /** - * Set the width (in units of 1/256th of a character width)<p> - * - * The maximum column width for an individual cell is 255 characters. - * This value represents the number of characters that can be displayed - * 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 - * using the default font (first font in the workbook).<p> - * - * Unless you are using a very special font, the default character is '0' (zero), - * this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)<p> - * - * Please note, that the width set by this method includes 4 pixels of margin padding (two on each side), - * plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec). - * This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).<p> - * - * To compute the actual number of visible characters, - * Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):<p> - * - * <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>, - * then the actual value of visible characters (the value shown in Excel) is derived from the following equation: - * <code> - * Truncate([numChars*7+5]/7*256)/256 = 8; - * </code> - * - * which gives <code>7.29</code>. - * - * @param columnIndex - the column to set (0-based) - * @param width - the width in units of 1/256th of a character width - * @throws IllegalArgumentException if width > 255*256 (the maximum column width in Excel is 255 characters) - */ - void setColumnWidth(int columnIndex, int width); - - /** - * get 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 - * using the default font (first font in the workbook) - * </p> - * - * @param columnIndex - the column to get (0-based) - * @return width - the width in units of 1/256th of a character width - */ - int getColumnWidth(int columnIndex); - - /** - * get the width in pixel - * - * <p> - * Please note, that this method works correctly only for workbooks - * with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). - * If the default font is changed the column width can be stretched - * </p> - * - * @param columnIndex - the column to set (0-based) - * @return width in pixels - */ - float getColumnWidthInPixels(int columnIndex); - - - /** - * Set the default column width for the sheet (if the columns do not define their own width) - * in characters - * - * @param width default column width measured in characters - */ - void setDefaultColumnWidth(int width); - - /** - * Get the default column width for the sheet (if the columns do not define their own width) - * in characters - * - * @return default column width measured in characters - */ - int getDefaultColumnWidth(); - - /** - * Get the default row height for the sheet (if the rows do not define their own height) in - * twips (1/20 of a point) - * - * @return default row height measured in twips (1/20 of a point) - */ - short getDefaultRowHeight(); - - /** - * Get the default row height for the sheet (if the rows do not define their own height) in - * points. - * - * @return default row height in points - */ - float getDefaultRowHeightInPoints(); - - /** - * Set the default row height for the sheet (if the rows do not define their own height) in - * twips (1/20 of a point) - * - * @param height default row height measured in twips (1/20 of a point) - */ - void setDefaultRowHeight(short height); - - /** - * Set the default row height for the sheet (if the rows do not define their own height) in - * points - * @param height default row height - */ - void setDefaultRowHeightInPoints(float height); - - /** - * Returns the CellStyle that applies to the given - * (0 based) column, or null if no style has been - * set for that column - */ - CellStyle getColumnStyle(int column); - - /* - * Sets the CellStyle that applies to the given - * (0 based) column. - */ -// public CellStyle setColumnStyle(int column, CellStyle style); - - /** - * Adds a merged region of cells (hence those cells form one) - * - * @param region (rowfrom/colfrom-rowto/colto) to merge - * @return index of this region - */ - int addMergedRegion(CellRangeAddress region); - - /** - * Adds a merged region of cells (hence those cells form one). - * Skips validation. It is possible to create overlapping merged regions - * or create a merged region that intersects a multi-cell array formula - * with this formula, which may result in a corrupt workbook. - * - * To check for merged regions overlapping array formulas or other merged regions - * after addMergedRegionUnsafe has been called, call {@link #validateMergedRegions()}, which runs in O(n^2) time. - * - * @param region to merge - * @return index of this region - * @throws IllegalArgumentException if region contains fewer than 2 cells - */ - int addMergedRegionUnsafe(CellRangeAddress region); - - /** - * Verify that merged regions do not intersect multi-cell array formulas and - * no merged regions intersect another merged region in this sheet. - * - * @throws IllegalStateException if region intersects with a multi-cell array formula - * @throws IllegalStateException if at least one region intersects with another merged region in this sheet - */ - void validateMergedRegions(); - - /** - * Determines whether the output is vertically centered on the page. - * - * @param value true to vertically center, false otherwise. - */ - void setVerticallyCenter(boolean value); - - /** - * Determines whether the output is horizontally centered on the page. - * - * @param value true to horizontally center, false otherwise. - */ - void setHorizontallyCenter(boolean value); - - /** - * Determine whether printed output for this sheet will be horizontally centered. - */ - - boolean getHorizontallyCenter(); - - /** - * Determine whether printed output for this sheet will be vertically centered. - */ - boolean getVerticallyCenter(); - - /** - * Removes a merged region of cells (hence letting them free) - * - * @param index of the region to unmerge - */ - void removeMergedRegion(int index); - - /** - * Removes a number of merged regions of cells (hence letting them free) - * - * @param indices A set of the regions to unmerge - */ - void removeMergedRegions(Collection<Integer> indices); - - /** - * Returns the number of merged regions - * - * @return number of merged regions - */ - int getNumMergedRegions(); - - /** - * Returns the merged region at the specified index - * - * @return the merged region at the specified index - */ - CellRangeAddress getMergedRegion(int index); - - /** - * Returns the list of merged regions. - * - * @return the list of merged regions - */ - List<CellRangeAddress> getMergedRegions(); - - /** - * Returns an iterator of the physical rows - * - * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not - * be the third row if say for instance the second row is undefined. - */ - Iterator<Row> rowIterator(); - - /** - * Control if Excel should be asked to recalculate all formulas on this sheet - * when the workbook is opened. - * - * <p> - * Calculating the formula values with {@link FormulaEvaluator} is the - * recommended solution, but this may be used for certain cases where - * evaluation in POI is not possible. - * </p> - * - * To force recalculation of formulas in the entire workbook - * use {@link Workbook#setForceFormulaRecalculation(boolean)} instead. - * - * @param value true if the application will perform a full recalculation of - * this worksheet values when the workbook is opened - * - * @see Workbook#setForceFormulaRecalculation(boolean) - */ - void setForceFormulaRecalculation(boolean value); - - /** - * Whether Excel will be asked to recalculate all formulas in this sheet when the - * workbook is opened. - * - * Note: This just returns if the sheet has the recalculate flag set and - * will still return false even if recalculation is enabled on workbook-level. - * - * @return true if the Sheet has the recalculate-flag set. - */ - boolean getForceFormulaRecalculation(); - - /** - * Flag indicating whether the sheet displays Automatic Page Breaks. - * - * @param value <code>true</code> if the sheet displays Automatic Page Breaks. - */ - void setAutobreaks(boolean value); - - /** - * Set whether to display the guts or not - * - * @param value - guts or no guts - */ - void setDisplayGuts(boolean value); - - /** - * Set whether the window should show 0 (zero) in cells containing zero value. - * When false, cells with zero value appear blank instead of showing the number zero. - * - * @param value whether to display or hide all zero values on the worksheet - */ - void setDisplayZeros(boolean value); - - - /** - * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value. - * When false, cells with zero value appear blank instead of showing the number zero. - * - * @return whether all zero values on the worksheet are displayed - */ - boolean isDisplayZeros(); - - /** - * 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. - */ - void setFitToPage(boolean value); - - /** - * Flag indicating whether summary rows appear below detail in an outline, when applying an outline. - * - * <p> - * When true a summary row is inserted below the detailed data being summarized and a - * new outline level is established on that row. - * </p> - * <p> - * 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 - */ - void setRowSumsBelow(boolean value); - - /** - * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. - * - * <p> - * When true a summary column is inserted to the right of the detailed data being summarized - * and a new outline level is established on that column. - * </p> - * <p> - * 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 - */ - void setRowSumsRight(boolean value); - - /** - * Flag indicating whether the sheet displays Automatic Page Breaks. - * - * @return <code>true</code> if the sheet displays Automatic Page Breaks. - */ - boolean getAutobreaks(); - - /** - * Get whether to display the guts or not, - * default value is true - * - * @return boolean - guts or no guts - */ - boolean getDisplayGuts(); - - /** - * Flag indicating whether the Fit to Page print option is enabled. - * - * @return <code>true</code> if the Fit to Page print option is enabled. - */ - boolean getFitToPage(); - - /** - * Flag indicating whether summary rows appear below detail in an outline, when applying an outline. - * - * <p> - * When true a summary row is inserted below the detailed data being summarized and a - * new outline level is established on that row. - * </p> - * <p> - * 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 - */ - boolean getRowSumsBelow(); - - /** - * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. - * - * <p> - * When true a summary column is inserted to the right of the detailed data being summarized - * and a new outline level is established on that column. - * </p> - * <p> - * 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 - */ - 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. - * @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. - * @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. - */ - 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. - */ - void setPrintRowAndColumnHeadings(boolean show); - - /** - * Gets the print setup object. - * - * @return The user model for the print setup object. - */ - PrintSetup getPrintSetup(); - - /** - * Gets the user model for the default document header.<p> - * - * Note that XSSF offers more kinds of document headers than HSSF does - * - * @return the document header. Never <code>null</code> - */ - Header getHeader(); - - /** - * Gets the user model for the default document footer.<p> - * - * Note that XSSF offers more kinds of document footers than HSSF does. - * - * @return the document footer. Never <code>null</code> - */ - Footer getFooter(); - - /** - * Sets a flag indicating whether this sheet is selected.<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 - * @see Workbook#setActiveSheet(int) - */ - void setSelected(boolean value); - - /** - * Gets the size of the margin in inches. - * - * @param margin which margin to get - * @return the size of the margin - */ - double getMargin(short margin); - - /** - * Sets the size of the margin in inches. - * - * @param margin which margin to get - * @param size the size of the margin - */ - void setMargin(short margin, double size); - - /** - * Answer whether protection is enabled or disabled - * - * @return true => protection enabled; false => protection disabled - */ - boolean getProtect(); - - /** - * Sets the protection enabled as well as the password - * @param password to set for protection. Pass <code>null</code> to remove protection - */ - void protectSheet(String password); - - /** - * Answer whether scenario protection is enabled or disabled - * - * @return true => protection enabled; false => protection disabled - */ - boolean getScenarioProtect(); - - /** - * Window zoom magnification for current view representing percent values. - * Valid values range from 10 to 400. Horizontal & Vertical scale together. - * - * For example: - * <pre> - * 10 - 10% - * 20 - 20% - * ... - * 100 - 100% - * ... - * 400 - 400% - * </pre> - * - * @param scale window zoom magnification - * @throws IllegalArgumentException if scale is invalid - */ - void setZoom(int scale); - - /** - * The top row in the visible view when the sheet is - * first viewed after opening it in a viewer - * - * @return short indicating the rownum (0 based) of the top row - */ - short getTopRow(); - - /** - * The left col in the visible view when the sheet is - * first viewed after opening it in a viewer - * - * @return short indicating the rownum (0 based) of the top row - */ - short getLeftCol(); - - /** - * Sets desktop window pane display area, when the - * file is first opened in a viewer. - * - * @param topRow the top row to show in desktop window pane - * @param leftCol the left column to show in desktop window pane - */ - void showInPane(int topRow, int leftCol); - - /** - * Shifts rows between startRow and endRow n number of rows. - * If you use a negative number, it will shift rows up. - * Code ensures that rows don't wrap around. - * - * Calls shiftRows(startRow, endRow, n, false, false); - * - * <p> - * Additionally shifts merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - */ - void shiftRows(int startRow, int endRow, int n); - - /** - * Shifts rows between startRow and endRow n number of rows. - * If you use a negative number, it will shift rows up. - * Code ensures that rows don't wrap around - * - * <p> - * Additionally shifts merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). All merged regions that are - * completely overlaid by shifting will be deleted. - * <p> - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - * @param copyRowHeight whether to copy the row height during the shift - * @param resetOriginalRowHeight whether to set the original row's height to the default - */ - void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight); - - /** - * Shifts columns between startColumn and endColumn, n number of columns. - * If you use a negative number, it will shift columns left. - * Code ensures that columns don't wrap around - * - * @param startColumn the column to start shifting - * @param endColumn the column to end shifting - * @param n the number of columns to shift - */ - void shiftColumns(int startColumn, int endColumn, int n); - - /** - * Creates a split (freezepane). Any existing freezepane or split pane is overwritten. - * <p> - * If both colSplit and rowSplit are zero then the existing freeze pane is removed - * </p> - * @param colSplit Horizontal position of split. - * @param rowSplit Vertical position of split. - * @param leftmostColumn Left column visible in right pane. - * @param topRow Top row visible in bottom pane - */ - void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow); - - /** - * Creates a split (freezepane). Any existing freezepane or split pane is overwritten. - * <p> - * If both colSplit and rowSplit are zero then the existing freeze pane is removed - * </p> - * @param colSplit Horizontal position of split. - * @param rowSplit Vertical position of split. - */ - void createFreezePane(int colSplit, int rowSplit); - - /** - * Creates a split pane. Any existing freezepane or split pane is overwritten. - * @param xSplitPos Horizontal position of split (in 1/20th of a point). - * @param ySplitPos Vertical position of split (in 1/20th of a point). - * @param topRow Top row visible in bottom pane - * @param leftmostColumn Left column visible in right pane. - * @param activePane Active pane. One of: PANE_LOWER_RIGHT, - * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT - * @see #PANE_LOWER_LEFT - * @see #PANE_LOWER_RIGHT - * @see #PANE_UPPER_LEFT - * @see #PANE_UPPER_RIGHT - */ - void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane); - - /** - * Returns the information regarding the currently configured pane (split or freeze) - * - * @return null if no pane configured, or the pane information. - */ - PaneInformation getPaneInformation(); - - /** - * Sets whether the gridlines are shown in a viewer - * - * @param show whether to show gridlines or not - */ - void setDisplayGridlines(boolean show); - - /** - * Returns if gridlines are displayed - * - * @return whether gridlines are displayed - */ - boolean isDisplayGridlines(); - - /** - * Sets whether the formulas are shown in a viewer - * - * @param show whether to show formulas or not - */ - void setDisplayFormulas(boolean show); - - /** - * Returns if formulas are displayed - * - * @return whether formulas are displayed - */ - boolean isDisplayFormulas(); - - /** - * Sets whether the RowColHeadings are shown in a viewer - * - * @param show whether to show RowColHeadings or not - */ - void setDisplayRowColHeadings(boolean show); - - /** - * Returns if RowColHeadings are displayed. - * @return whether RowColHeadings are displayed - */ - boolean isDisplayRowColHeadings(); - - /** - * 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> - * 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. - * - * @param row the row to break, inclusive - */ - void setRowBreak(int row); - - /** - * Determines if there is a page break at the indicated row - * @param row FIXME: Document this! - * @return FIXME: Document this! - */ - boolean isRowBroken(int row); - - /** - * Removes the page break at the indicated row - * @param row The 0-based index of the row. - */ - void removeRowBreak(int row); - - /** - * Retrieves all the horizontal page breaks - * @return all the horizontal page breaks, or null if there are no row page breaks - */ - int[] getRowBreaks(); - - /** - * Retrieves all the vertical page breaks - * @return all the vertical page breaks, or null if there are no column page breaks - */ - int[] getColumnBreaks(); - - /** - * 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> - * 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. - * - * @param column the column to break, inclusive - */ - void setColumnBreak(int column); - - /** - * Determines if there is a page break at the indicated column - * @param column FIXME: Document this! - * @return FIXME: Document this! - */ - boolean isColumnBroken(int column); - - /** - * Removes a page break at the indicated column - * @param column The 0-based index of the column. - */ - void removeColumnBreak(int column); - - /** - * Expands or collapses a column group. - * - * @param columnNumber One of the columns in the group. - * @param collapsed true = collapse group, false = expand group. - */ - void setColumnGroupCollapsed(int columnNumber, boolean collapsed); - - /** - * Create an outline for the provided column range. - * - * @param fromColumn beginning of the column range. - * @param toColumn end of the column range. - */ - void groupColumn(int fromColumn, int toColumn); - - /** - * Ungroup a range of columns that were previously grouped - * - * @param fromColumn start column (0-based) - * @param toColumn end column (0-based) - */ - void ungroupColumn(int fromColumn, int toColumn); - - /** - * Tie a range of rows together so that they can be collapsed or expanded - * - * @param fromRow start row (0-based) - * @param toRow end row (0-based) - */ - void groupRow(int fromRow, int toRow); - - /** - * Ungroup a range of rows that were previously grouped - * - * @param fromRow start row (0-based) - * @param toRow end row (0-based) - */ - void ungroupRow(int fromRow, int toRow); - - /** - * Set view state of a grouped range of rows - * - * @param row start row of a grouped range of rows (0-based) - * @param collapse whether to expand/collapse the detail rows - */ - void setRowGroupCollapsed(int row, boolean collapse); - - /** - * Sets the default column style for a given column. POI will only apply this style to new cells added to the sheet. - * - * @param column the column index - * @param style the style to set - */ - void setDefaultColumnStyle(int column, CellStyle style); - - /** - * Adjusts the column width to fit the contents. - * - * <p> - * This process can be relatively slow on large sheets, so this should - * normally only be called once per column, at the end of your - * processing. - * </p> - * You can specify whether the content of merged cells should be considered or ignored. - * Default is to ignore merged cells. - * - * @param column the column index - */ - void autoSizeColumn(int column); - - /** - * Adjusts the column width to fit the contents. - * <p> - * This process can be relatively slow on large sheets, so this should - * normally only be called once per column, at the end of your - * processing. - * </p> - * You can specify whether the content of merged cells should be considered or ignored. - * Default is to ignore merged cells. - * - * @param column the column index - * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column - */ - void autoSizeColumn(int column, boolean useMergedCells); - - /** - * Returns cell comment for the specified location - * - * @return cell comment or <code>null</code> if not found - */ - Comment getCellComment(CellAddress ref); - - /** - * Returns all cell comments on this sheet. - * @return A map of each Comment in the sheet, keyed on the cell address where - * the comment is located. - */ - Map<CellAddress, ? extends Comment> getCellComments(); - - /** - * Return the sheet's existing drawing, or null if there isn't yet one. - * - * Use {@link #createDrawingPatriarch()} to get or create - * - * @return a SpreadsheetML drawing - */ - Drawing<?> getDrawingPatriarch(); - - /** - * Creates the top-level drawing patriarch. - * <p>This may then be used to add graphics or charts.</p> - * <p>Note that this will normally have the effect of removing - * any existing drawings on this sheet.</p> - * - * @return The new drawing patriarch. - */ - Drawing<?> createDrawingPatriarch(); - - - /** - * Return the parent workbook - * - * @return the parent workbook - */ - Workbook getWorkbook(); - - /** - * Returns the name of this sheet - * - * @return the name of this sheet - */ - String getSheetName(); - - /** - * Note - this is not the same as whether the sheet is focused (isActive) - * @return <code>true</code> if this sheet is currently selected - */ - boolean isSelected(); - - - /** - * Sets array formula to specified region for result. - * <p> - * Note if there are shared formulas this will invalidate any - * {@link FormulaEvaluator} instances based on this workbook - *</p> - * @param formula text representation of the formula - * @param range Region of array formula for result. - * @return the {@link CellRange} of cells affected by this change - */ - CellRange<? extends Cell> setArrayFormula(String formula, CellRangeAddress range); - - /** - * Remove a Array Formula from this sheet. All cells contained in the Array Formula range are removed as well - * - * @param cell any cell within Array Formula range - * @return the {@link CellRange} of cells affected by this change - */ - CellRange<? extends Cell> removeArrayFormula(Cell cell); - - DataValidationHelper getDataValidationHelper(); - - /** - * Returns the list of DataValidation in the sheet. - * @return list of DataValidation in the sheet - */ - List<? extends DataValidation> getDataValidations(); - - /** - * Creates a data validation object - * @param dataValidation The Data validation object settings - */ - void addValidationData(DataValidation dataValidation); - - /** - * Enable filtering for a range of cells - * - * @param range the range of cells to filter - */ - AutoFilter setAutoFilter(CellRangeAddress range); - - /** - * The 'Conditional Formatting' facet for this <tt>Sheet</tt> - * - * @return conditional formatting rule for this sheet - */ - SheetConditionalFormatting getSheetConditionalFormatting(); - - - /** - * Gets the repeating rows used when printing the sheet, as found in - * File->PageSetup->Sheet.<p> - * - * Repeating rows cover a range of contiguous rows, e.g.: - * <pre> - * Sheet1!$1:$1 - * Sheet2!$5:$8 - * </pre> - * The {@link CellRangeAddress} returned contains a column part which spans - * all columns, and a row part which specifies the contiguous range of - * repeating rows.<p> - * - * If the Sheet does not have any repeating rows defined, null is returned. - * - * @return an {@link CellRangeAddress} containing the repeating rows for the - * Sheet, or null. - */ - CellRangeAddress getRepeatingRows(); - - - /** - * Gets the repeating columns used when printing the sheet, as found in - * File->PageSetup->Sheet.<p> - * - * Repeating columns cover a range of contiguous columns, e.g.: - * <pre> - * Sheet1!$A:$A - * Sheet2!$C:$F - * </pre> - * The {@link CellRangeAddress} returned contains a row part which spans all - * rows, and a column part which specifies the contiguous range of - * repeating columns.<p> - * - * If the Sheet does not have any repeating columns defined, null is - * returned. - * - * @return an {@link CellRangeAddress} containing the repeating columns for - * the Sheet, or null. - */ - CellRangeAddress getRepeatingColumns(); - - - /** - * Sets the repeating rows used when printing the sheet, as found in - * File->PageSetup->Sheet.<p> - * - * Repeating rows cover a range of contiguous rows, e.g.: - * <pre> - * Sheet1!$1:$1 - * Sheet2!$5:$8</pre> - * The parameter {@link CellRangeAddress} should specify a column part - * which spans all columns, and a row part which specifies the contiguous - * range of repeating rows, e.g.: - * <pre> - * sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3"));</pre> - * A null parameter value indicates that repeating rows should be removed - * from the Sheet: - * <pre> - * sheet.setRepeatingRows(null);</pre> - * - * @param rowRangeRef a {@link CellRangeAddress} containing the repeating - * rows for the Sheet, or null. - */ - void setRepeatingRows(CellRangeAddress rowRangeRef); - - - /** - * Sets the repeating columns used when printing the sheet, as found in - * File->PageSetup->Sheet.<p> - * - * Repeating columns cover a range of contiguous columns, e.g.: - * <pre> - * Sheet1!$A:$A - * Sheet2!$C:$F</pre> - * The parameter {@link CellRangeAddress} should specify a row part - * which spans all rows, and a column part which specifies the contiguous - * range of repeating columns, e.g.: - * <pre> - * sheet.setRepeatingColumns(CellRangeAddress.valueOf("B:C"));</pre> - * A null parameter value indicates that repeating columns should be removed - * from the Sheet: - * <pre> - * sheet.setRepeatingColumns(null);</pre> - * - * @param columnRangeRef a {@link CellRangeAddress} containing the repeating - * columns for the Sheet, or null. - */ - void setRepeatingColumns(CellRangeAddress columnRangeRef); - - /** - * Returns the column outline level. Increased as you - * put it into more groups (outlines), reduced as - * you take it out of them. - */ - int getColumnOutlineLevel(int columnIndex); - - /** - * Get a Hyperlink in this sheet anchored at row, column - * - * @param row The 0-based index of the row to look at. - * @param column The 0-based index of the column to look at. - * @return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null - */ - Hyperlink getHyperlink(int row, int column); - - /** - * Get a Hyperlink in this sheet located in a cell specified by {code addr} - * - * @param addr The address of the cell containing the hyperlink - * @return hyperlink if there is a hyperlink anchored at {@code addr}; otherwise returns {@code null} - * @since POI 3.15 beta 3 - */ - Hyperlink getHyperlink(CellAddress addr); - - /** - * Get a list of Hyperlinks in this sheet - * - * @return Hyperlinks for the sheet - */ - List<? extends Hyperlink> getHyperlinkList(); - - /** - * Return location of the active cell, e.g. <code>A1</code>. - * - * @return the location of the active cell. - * @since 3.14beta1 - */ - CellAddress getActiveCell(); - - /** - * Sets location of the active cell - * - * @param address the location of the active cell, e.g. <code>A1</code>. - * @since 3.14beta1 - */ - void setActiveCell(CellAddress address); -} diff --git a/src/java/org/apache/poi/ss/usermodel/SheetConditionalFormatting.java b/src/java/org/apache/poi/ss/usermodel/SheetConditionalFormatting.java deleted file mode 100644 index 98e2aa7846..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/SheetConditionalFormatting.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * The 'Conditional Formatting' facet of <tt>Sheet</tt> - * - * @since 3.8 - */ -public interface SheetConditionalFormatting { - /** - * Add a new Conditional Formatting to the sheet. - * - * @param regions - list of rectangular regions to apply conditional formatting rules - * @param rule - the rule to apply - * - * @return index of the newly created Conditional Formatting object - */ - int addConditionalFormatting(CellRangeAddress[] regions, - ConditionalFormattingRule rule); - - /** - * Add a new Conditional Formatting consisting of two rules. - * - * @param regions - list of rectangular regions to apply conditional formatting rules - * @param rule1 - the first rule - * @param rule2 - the second rule - * - * @return index of the newly created Conditional Formatting object - */ - int addConditionalFormatting(CellRangeAddress[] regions, - ConditionalFormattingRule rule1, - ConditionalFormattingRule rule2); - - /** - * Add a new Conditional Formatting set to the sheet. - * - * @param regions - list of rectangular regions to apply conditional formatting rules - * @param cfRules - set of up to conditional formatting rules (max 3 for Excel pre-2007) - * - * @return index of the newly created Conditional Formatting object - */ - int addConditionalFormatting(CellRangeAddress[] regions, ConditionalFormattingRule[] cfRules); - - /** - * Adds a copy of a ConditionalFormatting object to the sheet - * <p> - * This method could be used to copy ConditionalFormatting object - * from one sheet to another. For example: - * </p> - * <pre> - * ConditionalFormatting cf = sheet.getConditionalFormattingAt(index); - * newSheet.addConditionalFormatting(cf); - * </pre> - * - * @param cf the Conditional Formatting to clone - * @return index of the new Conditional Formatting object - */ - int addConditionalFormatting(ConditionalFormatting cf); - - /** - * A factory method allowing to create a conditional formatting rule - * with a cell comparison operator - * <p> - * The created conditional formatting rule compares a cell value - * to a formula calculated result, using the specified operator. - * The type of the created condition is {@link ConditionType#CELL_VALUE_IS} - * </p> - * - * @param comparisonOperation - MUST be a constant value from - * <tt>{@link ComparisonOperator}</tt>: <p> - * <ul> - * <li>BETWEEN</li> - * <li>NOT_BETWEEN</li> - * <li>EQUAL</li> - * <li>NOT_EQUAL</li> - * <li>GT</li> - * <li>LT</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) - */ - ConditionalFormattingRule createConditionalFormattingRule( - byte comparisonOperation, - String formula1, - String formula2); - - /** - * Create a conditional formatting rule that compares a cell value - * to a formula calculated result, using an operator * - * <p> - * The type of the created condition is {@link ConditionType#CELL_VALUE_IS} - * </p> - * - * @param comparisonOperation MUST be a constant value from - * <tt>{@link ComparisonOperator}</tt> except BETWEEN and NOT_BETWEEN - * - * @param formula the formula to determine if the conditional formatting is applied - */ - ConditionalFormattingRule createConditionalFormattingRule( - byte comparisonOperation, - String formula); - - /** - * Create a conditional formatting rule based on a Boolean formula. - * When the formula result is true, the cell is highlighted. - * - * <p> - * The type of the created format condition is {@link ConditionType#FORMULA} - * </p> - * @param formula the formula to evaluate. MUST be a Boolean function. - */ - ConditionalFormattingRule createConditionalFormattingRule(String formula); - - /** - * Create a Databar conditional formatting rule. - * <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 - * {@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 - * {@link ConditionalFormattingRule#getMultiStateFormatting()} - * then - * {@link IconMultiStateFormatting#getThresholds()} - */ - ConditionalFormattingRule createConditionalFormattingRule(IconSet iconSet); - - /** - * 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 - * {@link ConditionalFormattingRule#getColorScaleFormatting()} - * then - * {@link ColorScaleFormatting#getThresholds()} - * and - * {@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 - * @throws IllegalArgumentException if the index is outside of the allowable range (0 ... numberOfFormats-1) - */ - ConditionalFormatting getConditionalFormattingAt(int index); - - /** - * - * @return the number of conditional formats in this sheet - */ - int getNumConditionalFormattings(); - - /** - * Removes a Conditional Formatting object by index - * - * @param index 0-based index of the Conditional Formatting object to remove - * @throws IllegalArgumentException if the index is outside of the allowable range (0 ... numberOfFormats-1) - */ - void removeConditionalFormatting(int index); -} diff --git a/src/java/org/apache/poi/ss/usermodel/SheetVisibility.java b/src/java/org/apache/poi/ss/usermodel/SheetVisibility.java deleted file mode 100644 index 8f8ab9138a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/SheetVisibility.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Specifies sheet visibility - * - * @see Workbook#getSheetVisibility(int) - * @see Workbook#setSheetVisibility(int, SheetVisibility) - */ -public enum SheetVisibility { - - /** - * Indicates the sheet is visible. - */ - VISIBLE, - /** - * Indicates the book window is hidden, but can be shown by the user via the user interface. - */ - HIDDEN, - - /** - * Indicates the sheet is hidden and cannot be shown in the user interface (UI). - * - * <p> - * In Excel this state is only available programmatically in VBA: - * <code>ThisWorkbook.Sheets("MySheetName").Visible = xlSheetVeryHidden </code> - * </p> - */ - VERY_HIDDEN -} diff --git a/src/java/org/apache/poi/ss/usermodel/SimpleShape.java b/src/java/org/apache/poi/ss/usermodel/SimpleShape.java deleted file mode 100644 index fe97c850f3..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/SimpleShape.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * A common interface for simple shapes. - * - * @since POI 3.16-beta2 - */ -public interface SimpleShape extends Shape { - /** - * @return the shape id, which is unique within the sheet - * - * @since POI 3.17-beta1 - */ - int getShapeId(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/Table.java b/src/java/org/apache/poi/ss/usermodel/Table.java deleted file mode 100644 index ef7fe33797..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Table.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.util.regex.Pattern; - -import org.apache.poi.ss.util.CellReference; - -/** - * XSSF Only! - * High level abstraction of table in a workbook. - */ -public interface Table { - /** - * Regular expression matching a Structured Reference (Table syntax) for XSSF table expressions. - * Public for unit tests - * @see <a href="https://support.office.com/en-us/article/Using-structured-references-with-Excel-tables-F5ED2452-2337-4F71-BED3-C8AE6D2B276E"> - * Excel Structured Reference Syntax - * </a> - */ - Pattern isStructuredReference = Pattern.compile("[a-zA-Z_\\\\][a-zA-Z0-9._]*\\[.*\\]"); - - /** - * Get the top-left column index relative to the sheet - * @return table start column index on sheet - */ - int getStartColIndex(); - /** - * Get the top-left row index on the sheet - * @return table start row index on sheet - */ - int getStartRowIndex(); - /** - * Get the bottom-right column index on the sheet - * @return table end column index on sheet - */ - int getEndColIndex(); - /** - * Get the bottom-right row index - * @return table end row index on sheet - */ - int getEndRowIndex(); - /** - * Get the name of the table. - * @return table name - */ - String getName(); - - /** - * @return name of the table style, if there is one. May be a built-in name or user-defined. - * @since 3.17 beta 1 - */ - String getStyleName(); - - /** - * Returns the index of a given named column in the table (names are case insensitive in XSSF). - * Note this list is lazily loaded and cached for performance. - * Changes to the underlying table structure are not reflected in later calls - * unless <code>XSSFTable.updateHeaders()</code> is called to reset the cache. - * @param columnHeader the column header name to get the table column index of - * @return column index corresponding to <code>columnHeader</code> - */ - int findColumnIndex(String columnHeader); - /** - * Returns the sheet name that the table belongs to. - * @return sheet name - */ - String getSheetName(); - - /** - * Note: This is misleading. The OOXML spec indicates this is true if the totals row - * has <b><i>ever</i></b> been shown, not whether or not it is currently displayed. - * Use {@link #getTotalsRowCount()} > 0 to decide whether or not the totals row is visible. - * @return true if a totals row has ever been shown for this table - * @since 3.15 beta 2 - * @see #getTotalsRowCount() - */ - boolean isHasTotalsRow(); - - /** - * @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 - * doesn't define how they would be implemented. - * @since 3.17 beta 1 - */ - int getTotalsRowCount(); - - /** - * @return 0 for no header rows, 1 for table headers shown. - * Values > 1 might be used by Excel for pivot tables? - * @since 3.17 beta 1 - */ - int getHeaderRowCount(); - - /** - * @return TableStyleInfo for this instance - * @since 3.17 beta 1 - */ - TableStyleInfo getStyle(); - - /** - * checks if the given cell is part of the table. Includes checking that they are on the same sheet. - * @param cell - * @return true if the table and cell are on the same sheet and the cell is within the table range. - * @since 3.17 beta 1 - * @see #contains(CellReference) (prefered, faster execution and handles undefined cells) - */ - default boolean contains(Cell cell) { - if (cell == null) return false; - return contains(new CellReference(cell.getSheet().getSheetName(), cell.getRowIndex(), cell.getColumnIndex(), true, true)); - } - - /** - * checks if the given cell is part of the table. Includes checking that they are on the same sheet. - * @param cell reference to a possibly undefined cell location - * @return true if the table and cell are on the same sheet and the cell is within the table range. - * @since 3.17 beta 1 - */ - boolean contains(CellReference cell); -} diff --git a/src/java/org/apache/poi/ss/usermodel/TableStyle.java b/src/java/org/apache/poi/ss/usermodel/TableStyle.java deleted file mode 100644 index b4e5e19835..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/TableStyle.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * Data table style definition. Includes style elements for various table components. - * Any number of style elements may be represented, and any cell may be styled by - * multiple elements. The order of elements in {@link TableStyleType} defines precedence. - * - * @since 3.17 beta 1 - */ -public interface TableStyle { - - /** - * @return name (may be a built-in name) - */ - String getName(); - - /** - * Some clients may care where in the table style list this definition came from, so we'll track it. - * The spec only references these by name, unlike Dxf records, which these definitions reference by index - * (XML definition order). Nice of MS to be consistent when defining the ECMA standard. - * Use org.apache.poi.xssf.usermodel.XSSFBuiltinTableStyle.isBuiltinStyle(TableStyle) to determine whether the index is for a built-in style or explicit user style - * @return index from org.apache.poi.xssf.model.StylesTable.getExplicitTableStyle(String) or org.apache.poi.xssf.usermodel.XSSFBuiltinTableStyle.ordinal() - */ - int getIndex(); - - /** - * - * @return true if this is a built-in style defined in the OOXML specification, false if it is a user style - */ - boolean isBuiltin(); - - /** - * - * @param type - * @return style definition for the given type, or null if not defined in this style. - */ - DifferentialStyleProvider getStyle(TableStyleType type); -} diff --git a/src/java/org/apache/poi/ss/usermodel/TableStyleInfo.java b/src/java/org/apache/poi/ss/usermodel/TableStyleInfo.java deleted file mode 100644 index a24ce05bd1..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/TableStyleInfo.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * style information for a specific table instance, referencing the document style - * and indicating which optional portions of the style to apply. - * - * @since 3.17 beta 1 - */ -public interface TableStyleInfo { - - /** - * @return true if alternating column styles should be applied - */ - boolean isShowColumnStripes(); - - /** - * @return true if alternating row styles should be applied - */ - boolean isShowRowStripes(); - - /** - * @return true if the distinct first column style should be applied - */ - boolean isShowFirstColumn(); - - /** - * @return true if the distinct last column style should be applied - */ - boolean isShowLastColumn(); - - /** - * @return the name of the style (may reference a built-in style) - */ - String getName(); - - /** - * @return style definition - */ - TableStyle getStyle(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/TableStyleType.java b/src/java/org/apache/poi/ss/usermodel/TableStyleType.java deleted file mode 100644 index 870436a3b4..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/TableStyleType.java +++ /dev/null @@ -1,319 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressBase; -import org.apache.poi.ss.util.CellReference; - -/** - * Ordered list of table style elements, for both data tables and pivot tables. - * Some elements only apply to pivot tables, but any style definition can omit any number, - * so having them in one list should not be a problem. - * <p> - * The order is the specification order of application, with later elements overriding previous - * ones, if style properties conflict. - * <p> - * Processing could iterate bottom-up if looking for specific properties, and stop when the - * first style is found defining a value for that property. - * <p> - * Enum names match the OOXML spec values exactly, so {@link #valueOf(String)} will work. - * - * @since 3.17 beta 1 - */ -public enum TableStyleType { - /***/ - wholeTable { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - return new CellRangeAddress(table.getStartRowIndex(), table.getEndRowIndex(), table.getStartColIndex(), table.getEndColIndex()); - } - }, - /***/ - pageFieldLabels, // pivot only - /***/ - pageFieldValues, // pivot only - /***/ - firstColumnStripe{ - public CellRangeAddressBase getRange(Table table, CellReference cell) { - TableStyleInfo info = table.getStyle(); - if (! info.isShowColumnStripes()) return null; - DifferentialStyleProvider c1Style = info.getStyle().getStyle(firstColumnStripe); - DifferentialStyleProvider c2Style = info.getStyle().getStyle(secondColumnStripe); - int c1Stripe = c1Style == null ? 1 : Math.max(1, c1Style.getStripeSize()); - int c2Stripe = c2Style == null ? 1 : Math.max(1, c2Style.getStripeSize()); - - int firstStart = table.getStartColIndex(); - int secondStart = firstStart + c1Stripe; - final int c = cell.getCol(); - - // look for the stripe containing c, accounting for the style element stripe size - // could do fancy math, but tables can't be that wide, a simple loop is fine - // if not in this type of stripe, return null - while (firstStart <= c) { - if (c <= secondStart -1) { - return new CellRangeAddress(table.getStartRowIndex(), table.getEndRowIndex(), firstStart, secondStart - 1); - } - firstStart = secondStart + c2Stripe; - secondStart = firstStart + c1Stripe; - } - return null; - } - }, - /***/ - secondColumnStripe{ - public CellRangeAddressBase getRange(Table table, CellReference cell) { - TableStyleInfo info = table.getStyle(); - if (! info.isShowColumnStripes()) return null; - - DifferentialStyleProvider c1Style = info.getStyle().getStyle(firstColumnStripe); - DifferentialStyleProvider c2Style = info.getStyle().getStyle(secondColumnStripe); - int c1Stripe = c1Style == null ? 1 : Math.max(1, c1Style.getStripeSize()); - int c2Stripe = c2Style == null ? 1 : Math.max(1, c2Style.getStripeSize()); - - int firstStart = table.getStartColIndex(); - int secondStart = firstStart + c1Stripe; - final int c = cell.getCol(); - - // look for the stripe containing c, accounting for the style element stripe size - // could do fancy math, but tables can't be that wide, a simple loop is fine - // if not in this type of stripe, return null - while (firstStart <= c) { - if (c >= secondStart && c <= secondStart + c2Stripe -1) { - return new CellRangeAddress(table.getStartRowIndex(), table.getEndRowIndex(), secondStart, secondStart + c2Stripe - 1); - } - firstStart = secondStart + c2Stripe; - secondStart = firstStart + c1Stripe; - } - return null; - } - }, - /***/ - firstRowStripe { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - TableStyleInfo info = table.getStyle(); - if (! info.isShowRowStripes()) return null; - - DifferentialStyleProvider c1Style = info.getStyle().getStyle(firstRowStripe); - DifferentialStyleProvider c2Style = info.getStyle().getStyle(secondRowStripe); - int c1Stripe = c1Style == null ? 1 : Math.max(1, c1Style.getStripeSize()); - int c2Stripe = c2Style == null ? 1 : Math.max(1, c2Style.getStripeSize()); - - int firstStart = table.getStartRowIndex() + table.getHeaderRowCount(); - int secondStart = firstStart + c1Stripe; - final int c = cell.getRow(); - - // look for the stripe containing c, accounting for the style element stripe size - // could do fancy math, but tables can't be that wide, a simple loop is fine - // if not in this type of stripe, return null - while (firstStart <= c) { - if (c <= secondStart -1) { - return new CellRangeAddress(firstStart, secondStart - 1, table.getStartColIndex(), table.getEndColIndex()); - } - firstStart = secondStart + c2Stripe; - secondStart = firstStart + c1Stripe; - } - return null; - } - }, - /***/ - secondRowStripe{ - public CellRangeAddressBase getRange(Table table, CellReference cell) { - TableStyleInfo info = table.getStyle(); - if (! info.isShowRowStripes()) return null; - - DifferentialStyleProvider c1Style = info.getStyle().getStyle(firstRowStripe); - DifferentialStyleProvider c2Style = info.getStyle().getStyle(secondRowStripe); - int c1Stripe = c1Style == null ? 1 : Math.max(1, c1Style.getStripeSize()); - int c2Stripe = c2Style == null ? 1 : Math.max(1, c2Style.getStripeSize()); - - int firstStart = table.getStartRowIndex() + table.getHeaderRowCount(); - int secondStart = firstStart + c1Stripe; - final int c = cell.getRow(); - - // look for the stripe containing c, accounting for the style element stripe size - // could do fancy math, but tables can't be that wide, a simple loop is fine - // if not in this type of stripe, return null - while (firstStart <= c) { - if (c >= secondStart && c <= secondStart +c2Stripe -1) { - return new CellRangeAddress(secondStart, secondStart + c2Stripe - 1, table.getStartColIndex(), table.getEndColIndex()); - } - firstStart = secondStart + c2Stripe; - secondStart = firstStart + c1Stripe; - } - return null; - } - }, - /***/ - lastColumn { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (! table.getStyle().isShowLastColumn()) return null; - return new CellRangeAddress(table.getStartRowIndex(), table.getEndRowIndex(), table.getEndColIndex(), table.getEndColIndex()); - } - }, - /***/ - firstColumn { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (! table.getStyle().isShowFirstColumn()) return null; - return new CellRangeAddress(table.getStartRowIndex(), table.getEndRowIndex(), table.getStartColIndex(), table.getStartColIndex()); - } - }, - /***/ - headerRow { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (table.getHeaderRowCount() < 1) return null; - return new CellRangeAddress(table.getStartRowIndex(), table.getStartRowIndex() + table.getHeaderRowCount() -1, table.getStartColIndex(), table.getEndColIndex()); - } - }, - /***/ - totalRow { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (table.getTotalsRowCount() < 1) return null; - return new CellRangeAddress(table.getEndRowIndex() - table.getTotalsRowCount() +1, table.getEndRowIndex(), table.getStartColIndex(), table.getEndColIndex()); - } - }, - /***/ - firstHeaderCell { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (table.getHeaderRowCount() < 1) return null; - return new CellRangeAddress(table.getStartRowIndex(), table.getStartRowIndex(), table.getStartColIndex(), table.getStartColIndex()); - } - }, - /***/ - lastHeaderCell { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (table.getHeaderRowCount() < 1) return null; - return new CellRangeAddress(table.getStartRowIndex(), table.getStartRowIndex(), table.getEndColIndex(), table.getEndColIndex()); - } - }, - /***/ - firstTotalCell { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (table.getTotalsRowCount() < 1) return null; - return new CellRangeAddress(table.getEndRowIndex() - table.getTotalsRowCount() +1, table.getEndRowIndex(), table.getStartColIndex(), table.getStartColIndex()); - } - }, - /***/ - lastTotalCell { - public CellRangeAddressBase getRange(Table table, CellReference cell) { - if (table.getTotalsRowCount() < 1) return null; - return new CellRangeAddress(table.getEndRowIndex() - table.getTotalsRowCount() +1, table.getEndRowIndex(), table.getEndColIndex(), table.getEndColIndex()); - } - }, - /* these are for pivot tables only */ - /***/ - firstSubtotalColumn, - /***/ - secondSubtotalColumn, - /***/ - thirdSubtotalColumn, - /***/ - blankRow, - /***/ - firstSubtotalRow, - /***/ - secondSubtotalRow, - /***/ - thirdSubtotalRow, - /***/ - firstColumnSubheading, - /***/ - secondColumnSubheading, - /***/ - thirdColumnSubheading, - /***/ - firstRowSubheading, - /***/ - secondRowSubheading, - /***/ - thirdRowSubheading, - ; - - /** - * A range is returned only for the part of the table matching this enum instance and containing the given cell. - * Null is returned for all other cases, such as: - * <ul> - * <li>Cell on a different sheet than the table - * <li>Cell outside the table - * <li>this Enum part is not included in the table (i.e. no header/totals row) - * <li>this Enum is for a table part not yet implemented in POI, such as pivot table elements - * </ul> - * The returned range can be used to determine how style options may or may not apply to this cell. - * For example, {@link #wholeTable} borders only apply to the outer boundary of a table, while the - * rest of the styling, such as font and color, could apply to all the interior cells as well. - * - * @param table table to evaluate - * @param cell to evaluate - * @return range in the table representing this class of cells, if it contains the given cell, or null if not applicable. - * Stripe style types return only the stripe range containing the given cell, or null. - */ - public CellRangeAddressBase appliesTo(Table table, Cell cell) { - if (cell == null) return null; - return appliesTo(table, new CellReference(cell.getSheet().getSheetName(), cell.getRowIndex(), cell.getColumnIndex(), true, true)); - } - - /** - * A range is returned only for the part of the table matching this enum instance and containing the given cell reference. - * Null is returned for all other cases, such as: - * <ul> - * <li>Cell on a different sheet than the table - * <li>Cell outside the table - * <li>this Enum part is not included in the table (i.e. no header/totals row) - * <li>this Enum is for a table part not yet implemented in POI, such as pivot table elements - * </ul> - * The returned range can be used to determine how style options may or may not apply to this cell. - * For example, {@link #wholeTable} borders only apply to the outer boundary of a table, while the - * rest of the styling, such as font and color, could apply to all the interior cells as well. - * - * @param table table to evaluate - * @param cell CellReference to evaluate - * @return range in the table representing this class of cells, if it contains the given cell, or null if not applicable. - * Stripe style types return only the stripe range containing the given cell, or null. - */ - public CellRangeAddressBase appliesTo(Table table, CellReference cell) { - if (table == null || cell == null) return null; - if ( ! cell.getSheetName().equals(table.getSheetName())) return null; - if ( ! table.contains(cell)) return null; - - final CellRangeAddressBase range = getRange(table, cell); - if (range != null && range.isInRange(cell.getRow(), cell.getCol())) return range; - // else - return null; - } - - /** - * Calls {@link #getRange(Table, CellReference)}. Use that instead for performance. - * @param table - * @param cell - * @return default is unimplemented/null - * @see #getRange(Table, CellReference) - */ - public final CellRangeAddressBase getRange(Table table, Cell cell) { - if (cell == null) return null; - return getRange(table, new CellReference(cell.getSheet().getSheetName(), cell.getRowIndex(), cell.getColumnIndex(), true, true)); - } - - /** - * - * @param table - * @param cell - * @return default is unimplemented/null - */ - public CellRangeAddressBase getRange(Table table, CellReference cell) { - return null; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java b/src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java deleted file mode 100644 index f8976d1307..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -/** - * This enumeration value indicates the type of vertical alignment for a cell, i.e., - * whether it is aligned top, bottom, vertically centered, justified or distributed. - * - * <!-- FIXME: Identical to {@link org.apache.poi.ss.usermodel.VerticalAlignment}. Should merge these to - * {@link org.apache.poi.common.usermodel}.VerticalAlignment in the future. --> - */ -public enum VerticalAlignment { - /** - * The vertical alignment is aligned-to-top. - */ - TOP, - - /** - * The vertical alignment is centered across the height of the cell. - */ - CENTER, - - /** - * The vertical alignment is aligned-to-bottom. (typically the default value) - */ - BOTTOM, - - /** - * <p> - * When text direction is horizontal: the vertical alignment of lines of text is distributed vertically, - * where each line of text inside the cell is evenly distributed across the height of the cell, - * with flush top and bottom margins. - * </p> - * <p> - * When text direction is vertical: similar behavior as horizontal justification. - * The alignment is justified (flush top and bottom in this case). For each line of text, each - * line of the wrapped text in a cell is aligned to the top and bottom (except the last line). - * If no single line of text wraps in the cell, then the text is not justified. - * </p> - */ - JUSTIFY, - - /** - * <p> - * When text direction is horizontal: the vertical alignment of lines of text is distributed vertically, - * where each line of text inside the cell is evenly distributed across the height of the cell, - * with flush top - * </p> - * <p> - * When text direction is vertical: behaves exactly as distributed horizontal alignment. - * The first words in a line of text (appearing at the top of the cell) are flush - * with the top edge of the cell, and the last words of a line of text are flush with the bottom edge of the cell, - * and the line of text is distributed evenly from top to bottom. - * </p> - */ - DISTRIBUTED; - - public short getCode() { - return (short) ordinal(); - } - public static VerticalAlignment forInt(int code) { - if (code < 0 || code >= values().length) { - throw new IllegalArgumentException("Invalid VerticalAlignment code: " + code); - } - return values()[code]; - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/Workbook.java b/src/java/org/apache/poi/ss/usermodel/Workbook.java deleted file mode 100644 index 156d1b0d7a..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/Workbook.java +++ /dev/null @@ -1,607 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.io.Closeable; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.EvaluationWorkbook; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.util.Removal; - -/** - * High level representation of a Excel workbook. This is the first object most users - * will construct whether they are reading or writing a workbook. It is also the - * top level object for creating new sheets/etc. - */ -public interface Workbook extends Closeable, Iterable<Sheet> { - - /** Extended windows meta file */ - int PICTURE_TYPE_EMF = 2; - - /** Windows Meta File */ - int PICTURE_TYPE_WMF = 3; - - /** Mac PICT format */ - int PICTURE_TYPE_PICT = 4; - - /** JPEG format */ - int PICTURE_TYPE_JPEG = 5; - - /** PNG format */ - int PICTURE_TYPE_PNG = 6; - - /** Device independent bitmap */ - int PICTURE_TYPE_DIB = 7; - - /** - * Convenience method to get the active sheet. The active sheet is is the sheet - * which is currently displayed when the workbook is viewed in Excel. - * 'Selected' sheet(s) is a distinct concept. - * - * @return the index of the active sheet (0-based) - */ - int getActiveSheetIndex(); - - /** - * Convenience method to set the active sheet. The active sheet is is the sheet - * which is currently displayed when the workbook is viewed in Excel. - * 'Selected' sheet(s) is a distinct concept. - * - * @param sheetIndex index of the active sheet (0-based) - */ - void setActiveSheet(int sheetIndex); - - /** - * Gets the first tab that is displayed in the list of tabs in excel. - * - * @return the first tab that to display in the list of tabs (0-based). - */ - int getFirstVisibleTab(); - - /** - * Sets the first tab that is displayed in the list of tabs in excel. - * - * @param sheetIndex the first tab that to display in the list of tabs (0-based) - */ - void setFirstVisibleTab(int sheetIndex); - - /** - * Sets the order of appearance for a given sheet. - * - * @param sheetname the name of the sheet to reorder - * @param pos the position that we want to insert the sheet into (0 based) - */ - void setSheetOrder(String sheetname, int pos); - - /** - * Sets the tab whose data is actually seen when the sheet is opened. - * This may be different from the "selected sheet" since excel seems to - * allow you to show the data of one sheet when another is seen "selected" - * in the tabs (at the bottom). - * - * @see Sheet#setSelected(boolean) - * @param index the index of the sheet to select (0 based) - */ - void setSelectedTab(int index); - - /** - * Set the sheet name. - * <p> - * See {@link org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)} - * for a safe way to create valid names - * </p> - * @param sheet number (0 based) - * @throws IllegalArgumentException if the name is null or invalid - * or workbook already contains a sheet with this name - * @see #createSheet(String) - * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal) - */ - void setSheetName(int sheet, String name); - - /** - * Get the sheet name - * - * @param sheet sheet number (0 based) - * @return Sheet name - */ - String getSheetName(int sheet); - - /** - * Returns the index of the sheet by his name - * - * @param name the sheet name - * @return index of the sheet (0 based) - */ - 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) - */ - int getSheetIndex(Sheet sheet); - - /** - * Create a Sheet for this Workbook, adds it to the sheets and returns - * the high level representation. Use this to create new sheets. - * - * @return Sheet representing the new sheet. - */ - Sheet createSheet(); - - /** - * Create a new sheet for this Workbook and return the high level representation. - * Use this to create new sheets. - * - * <p> - * Note that Excel allows sheet names up to 31 chars in length but other applications - * (such as OpenOffice) allow more. Some versions of Excel crash with names longer than 31 chars, - * others - truncate such names to 31 character. - * </p> - * <p> - * POI's SpreadsheetAPI silently truncates the input argument to 31 characters. - * Example: - * - * <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> - * </p> - * - * Except the 31-character constraint, Excel applies some other rules: - * <p> - * Sheet name MUST be unique in the workbook and MUST NOT contain the any of the following characters: - * <ul> - * <li> 0x0000 </li> - * <li> 0x0003 </li> - * <li> colon (:) </li> - * <li> backslash (\) </li> - * <li> asterisk (*) </li> - * <li> question mark (?) </li> - * <li> forward slash (/) </li> - * <li> opening square bracket ([) </li> - * <li> closing square bracket (]) </li> - * </ul> - * The string MUST NOT begin or end with the single quote (') character. - * </p> - * - * <p> - * See {@link org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)} - * for a safe way to create valid names - * </p> - * @param sheetname The name to set for the sheet. - * @return Sheet representing the new sheet. - * @throws IllegalArgumentException if the name is null or invalid - * or workbook already contains a sheet with this name - * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal) - */ - Sheet createSheet(String sheetname); - - /** - * Create a Sheet from an existing sheet in the Workbook. - * - * @return Sheet representing the cloned sheet. - */ - Sheet cloneSheet(int sheetNum); - - - /** - * Returns an iterator of the sheets in the workbook - * in sheet order. Includes hidden and very hidden sheets. - * - * @return an iterator of the sheets. - */ - Iterator<Sheet> sheetIterator(); - - /** - * Get the number of spreadsheets in the workbook - * - * @return the number of sheets - */ - int getNumberOfSheets(); - - /** - * Get the Sheet object at the given index. - * - * @param index of the sheet number (0-based physical & logical) - * @return Sheet at the provided index - * @throws IllegalArgumentException if the index is out of range (index - * < 0 || index >= getNumberOfSheets()). - */ - Sheet getSheetAt(int index); - - /** - * Get sheet with the given name - * - * @param name of the sheet - * @return Sheet with the name provided or <code>null</code> if it does not exist - */ - Sheet getSheet(String name); - - /** - * Removes sheet at the given index - * - * @param index of the sheet to remove (0-based) - */ - void removeSheetAt(int index); - - /** - * Create a new Font and add it to the workbook's font table - * - * @return new font object - */ - Font createFont(); - - /** - * Finds a font that matches the one with the supplied attributes - * - * @return the font with the matched attributes or <code>null</code> - */ - Font findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline); - - /** - * Get the number of fonts in the font table - * - * @return number of fonts (as int since POI 5.0.0) - */ - int getNumberOfFonts(); - - /** - * Get the number of fonts in the font table - * - * @return number of fonts - * @since 4.0.0 - */ - @Deprecated - @Removal(version = "6.0.0") - int getNumberOfFontsAsInt(); - - /** - * Get the font at the given index number - * - * @param idx index number (0-based) - * @return font at the index - * @since 4.0.0 - */ - Font getFontAt(int idx); - - /** - * Create a new Cell style and add it to the workbook's style table - * - * @return the new Cell Style object - * @throws IllegalStateException if the number of cell styles exceeded the limit for this type of Workbook. - */ - CellStyle createCellStyle(); - - /** - * Get the number of styles the workbook contains - * - * @return count of cell styles - */ - int getNumCellStyles(); - - /** - * Get the cell style object at the given index - * - * @param idx index within the set of styles (0-based) - * @return CellStyle object at the index - */ - CellStyle getCellStyleAt(int idx); - - /** - * Write out this workbook to an Outputstream. - * - * @param stream - the java OutputStream you wish to write to - * @exception IOException if anything can't be written. - */ - void write(OutputStream stream) throws IOException; - - /** - * Close the underlying input resource (File or Stream), - * from which the Workbook was read. - * - * <p>Once this has been called, no further - * operations, updates or reads should be performed on the - * Workbook. - */ - @Override - void close() throws IOException; - - /** - * @return the total number of defined names in this workbook - */ - int getNumberOfNames(); - - /** - * @param name the name of the defined name - * @return the defined name with the specified name. <code>null</code> if not found. - */ - Name getName(String name); - - /** - * Returns all defined names with the given name. - * - * @param name the name of the defined name - * @return a list of the defined names with the specified name. An empty list is returned if none is found. - */ - List<? extends Name> getNames(String name); - - /** - * Returns all defined names. - * - * @return a list of the defined names. An empty list is returned if none is found. - */ - List<? extends Name> getAllNames(); - - /** - * Creates a new (uninitialised) defined name in this workbook - * - * @return new defined name object - */ - Name createName(); - - /** - * Remove a defined name - * - * @param name the name of the defined name - */ - void removeName(Name name); - - /** - * Adds the linking required to allow formulas referencing - * the specified external workbook to be added to this one. - * <p>In order for formulas such as "[MyOtherWorkbook]Sheet3!$A$5" - * to be added to the file, some linking information must first - * be recorded. Once a given external workbook has been linked, - * then formulas using it can added. Each workbook needs linking - * only once. - * <p>This linking only applies for writing formulas. To link things - * for evaluation, see {@link FormulaEvaluator#setupReferencedWorkbooks(java.util.Map)} - * - * @param name The name the workbook will be referenced as in formulas - * @param workbook The open workbook to fetch the link required information from - */ - int linkExternalWorkbook(String name, Workbook workbook); - - /** - * Sets the printarea for the sheet provided - * <p> - * i.e. Reference = $A$1:$B$2 - * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java) - * @param reference Valid name Reference for the Print Area - */ - void setPrintArea(int sheetIndex, String reference); - - /** - * For the Convenience of Java Programmers maintaining pointers. - * @see #setPrintArea(int, String) - * @param sheetIndex Zero-based sheet index (0 = First Sheet) - * @param startColumn Column to begin printarea - * @param endColumn Column to end the printarea - * @param startRow Row to begin the printarea - * @param endRow Row to end the printarea - */ - void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow); - - /** - * Retrieves the reference for the printarea of the specified sheet, - * the sheet name is appended to the reference even if it was not specified. - * - * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java) - * @return String Null if no print area has been defined - */ - String getPrintArea(int sheetIndex); - - /** - * Delete the printarea for the sheet specified - * - * @param sheetIndex Zero-based sheet index (0 = First Sheet) - */ - void removePrintArea(int sheetIndex); - - /** - * Retrieves the current policy on what to do when - * getting missing or blank cells from a row. - * <p> - * The default is to return blank and null cells. - * {@link MissingCellPolicy} - * </p> - */ - MissingCellPolicy getMissingCellPolicy(); - - /** - * Sets the policy on what to do when - * getting missing or blank cells from a row. - * - * This will then apply to all calls to - * {@link Row#getCell(int)} }. See - * {@link MissingCellPolicy} - */ - void setMissingCellPolicy(MissingCellPolicy missingCellPolicy); - - /** - * Returns the instance of DataFormat for this workbook. - * - * @return the DataFormat object - */ - DataFormat createDataFormat(); - - /** - * Adds a picture to the workbook. - * - * @param pictureData The bytes of the picture - * @param format The format of the picture. - * - * @return the index to this picture (1 based). - * @see #PICTURE_TYPE_EMF - * @see #PICTURE_TYPE_WMF - * @see #PICTURE_TYPE_PICT - * @see #PICTURE_TYPE_JPEG - * @see #PICTURE_TYPE_PNG - * @see #PICTURE_TYPE_DIB - */ - int addPicture(byte[] pictureData, int format); - - /** - * Gets all pictures from the Workbook. - * - * @return the list of pictures (a list of {@link PictureData} objects.) - */ - List<? extends PictureData> getAllPictures(); - - /** - * Returns an object that handles instantiating concrete - * classes of the various instances one needs for HSSF and XSSF. - */ - CreationHelper getCreationHelper(); - - /** - * @return <code>false</code> if this workbook is not visible in the GUI - */ - boolean isHidden(); - - /** - * @param hiddenFlag pass <code>false</code> to make the workbook visible in the GUI - */ - void setHidden(boolean hiddenFlag); - - /** - * Check whether a sheet is hidden. - * <p> - * Note that a sheet could instead be set to be very hidden, which is different - * ({@link #isSheetVeryHidden(int)}) - * </p> - * @param sheetIx Number - * @return <code>true</code> if sheet is hidden - * @see #getSheetVisibility(int) - */ - boolean isSheetHidden(int sheetIx); - - /** - * Check whether a sheet is very hidden. - * <p> - * This is different from the normal hidden status - * ({@link #isSheetHidden(int)}) - * </p> - * @param sheetIx sheet index to check - * @return <code>true</code> if sheet is very hidden - * @see #getSheetVisibility(int) - */ - boolean isSheetVeryHidden(int sheetIx); - - /** - * Hide or unhide a sheet. - * - * Please note that the sheet currently set as active sheet (sheet 0 in a newly - * created workbook or the one set via setActiveSheet()) cannot be hidden. - * - * @param sheetIx the sheet index (0-based) - * @param hidden True to mark the sheet as hidden, false otherwise - * @see #setSheetVisibility(int, SheetVisibility) - */ - void setSheetHidden(int sheetIx, boolean hidden); - - /** - * Get the visibility (visible, hidden, very hidden) of a sheet in this workbook - * - * @param sheetIx the index of the sheet - * @return the sheet visibility - * @since POI 3.16 beta 2 - */ - SheetVisibility getSheetVisibility(int sheetIx); - - /** - * Hide or unhide a sheet. - * - * Please note that the sheet currently set as active sheet (sheet 0 in a newly - * created workbook or the one set via setActiveSheet()) cannot be hidden. - * - * @param sheetIx the sheet index (0-based) - * @param visibility the sheet visibility to set - * @since POI 3.16 beta 2 - */ - void setSheetVisibility(int sheetIx, SheetVisibility visibility); - - /** - * Register a new toolpack in this workbook. - * - * @param toopack the toolpack to register - */ - void addToolPack(UDFFinder toopack); - - /** - * Whether the application shall perform a full recalculation when the workbook is opened. - * <p> - * Typically you want to force formula recalculation when you modify cell formulas or values - * of a workbook previously created by Excel. When set to true, this flag will tell Excel - * that it needs to recalculate all formulas in the workbook the next time the file is opened. - * </p> - * <p> - * Note, that recalculation updates cached formula results and, thus, modifies the workbook. - * Depending on the version, Excel may prompt you with "Do you want to save the changes in <em>filename</em>?" - * on close. - * </p> - * - * @param value true if the application will perform a full recalculation of - * workbook values when the workbook is opened - * @since 3.8 - */ - void setForceFormulaRecalculation(boolean value); - - /** - * Whether Excel will be asked to recalculate all formulas when the workbook is opened. - * - * @since 3.8 - */ - boolean getForceFormulaRecalculation(); - - /** - * Returns the spreadsheet version of this workbook - * - * @return SpreadsheetVersion enum - * @since 3.14 beta 2 - */ - SpreadsheetVersion getSpreadsheetVersion(); - - /** - * Adds an OLE package manager object with the given content to the sheet - * - * @param oleData the payload - * @param label the label of the payload - * @param fileName the original filename - * @param command the command to open the payload - * - * @return the index of the added ole object, i.e. the storage id - * - * @throws IOException if the object can't be embedded - */ - int addOlePackage(byte[] oleData, String label, String fileName, String command) throws IOException; - - /** - * @return an evaluation workbook - */ - EvaluationWorkbook createEvaluationWorkbook(); -} diff --git a/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java b/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java deleted file mode 100644 index 3e9b887179..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/WorkbookFactory.java +++ /dev/null @@ -1,310 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.extractor.ExtractorFactory.OOXML_PACKAGE; -import static org.apache.poi.poifs.crypt.Decryptor.DEFAULT_POIFS_ENTRY; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.ServiceLoader; - -import org.apache.poi.EmptyFileException; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.FileMagic; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * Factory for creating the appropriate kind of Workbook - * (be it {@link HSSFWorkbook} or XSSFWorkbook), - * by auto-detecting from the supplied input. - */ -public final class WorkbookFactory { - - private static class Singleton { - private static final WorkbookFactory INSTANCE = new WorkbookFactory(); - } - - private interface ProviderMethod { - Workbook create(WorkbookProvider prov) throws IOException; - } - - private final List<WorkbookProvider> provider = new ArrayList<>(); - - private WorkbookFactory() { - ClassLoader cl = WorkbookFactory.class.getClassLoader(); - ServiceLoader.load(WorkbookProvider.class, cl).forEach(provider::add); - } - - - /** - * Create a new empty Workbook, either XSSF or HSSF depending - * on the parameter - * - * @param xssf If an XSSFWorkbook or a HSSFWorkbook should be created - * - * @return The created workbook - * - * @throws IOException if an error occurs while creating the objects - */ - public static Workbook create(boolean xssf) throws IOException { - return wp(xssf ? FileMagic.OOXML : FileMagic.OLE2, WorkbookProvider::create); - } - - /** - * Creates a HSSFWorkbook from the given POIFSFileSystem<p> - * - * Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param fs The {@link POIFSFileSystem} to read the document from - * - * @return The created workbook - * - * @throws IOException if an error occurs while reading the data - */ - public static Workbook create(POIFSFileSystem fs) throws IOException { - return create(fs, null); - } - - /** - * Creates a Workbook from the given POIFSFileSystem, which may - * be password protected - * - * @param fs The {@link POIFSFileSystem} to read the document from - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - */ - private static Workbook create(final POIFSFileSystem fs, String password) throws IOException { - return create(fs.getRoot(), password); - } - - - /** - * Creates a Workbook from the given DirectoryNode. - * - * @param root The {@link DirectoryNode} to start reading the document from - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - */ - public static Workbook create(final DirectoryNode root) throws IOException { - return create(root, null); - } - - - /** - * Creates a Workbook from the given DirectoryNode, which may - * be password protected - * - * @param root The {@link DirectoryNode} to start reading the document from - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - */ - public static Workbook create(final DirectoryNode root, String password) throws IOException { - // Encrypted OOXML files go inside OLE2 containers, is this one? - if (root.hasEntry(DEFAULT_POIFS_ENTRY) || root.hasEntry(OOXML_PACKAGE)) { - return wp(FileMagic.OOXML, w -> w.create(root, password)); - } else { - return wp(FileMagic.OLE2, w -> w.create(root, password)); - } - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given InputStream. - * - * <p>Your input stream MUST either support mark/reset, or - * be wrapped as a {@link BufferedInputStream}! - * Note that using an {@link InputStream} has a higher memory footprint - * than using a {@link File}.</p> - * - * <p>Note that in order to properly release resources the - * Workbook should be closed after use. Note also that loading - * from an InputStream requires more memory than loading - * from a File, so prefer {@link #create(File)} where possible. - * - * @param inp The {@link InputStream} to read data from. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the Workbook given is password protected - */ - public static Workbook create(InputStream inp) throws IOException, EncryptedDocumentException { - return create(inp, null); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given InputStream, which may be password protected. - * - * <p>Your input stream MUST either support mark/reset, or - * be wrapped as a {@link BufferedInputStream}! - * Note that using an {@link InputStream} has a higher memory footprint - * than using a {@link File}.</p> - * - * <p>Note that in order to properly release resources the - * Workbook should be closed after use. Note also that loading - * from an InputStream requires more memory than loading - * from a File, so prefer {@link #create(File)} where possible.</p> - * - * @param inp The {@link InputStream} to read data from. - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - public static Workbook create(InputStream inp, String password) throws IOException, EncryptedDocumentException { - InputStream is = FileMagic.prepareToCheckMagic(inp); - byte[] emptyFileCheck = new byte[1]; - is.mark(emptyFileCheck.length); - if (is.read(emptyFileCheck) < emptyFileCheck.length) { - throw new EmptyFileException(); - } - is.reset(); - - final FileMagic fm = FileMagic.valueOf(is); - if (FileMagic.OOXML == fm) { - return wp(fm, w -> w.create(is)); - } - - if (FileMagic.OLE2 != fm) { - throw new IOException("Can't open workbook - unsupported file type: "+fm); - } - - POIFSFileSystem poifs = new POIFSFileSystem(is); - DirectoryNode root = poifs.getRoot(); - boolean isOOXML = root.hasEntry(DEFAULT_POIFS_ENTRY) || root.hasEntry(OOXML_PACKAGE); - - return wp(isOOXML ? FileMagic.OOXML : fm, w -> w.create(root, password)); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given File, which must exist and be readable. - * <p>Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param file The file to read data from. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the Workbook given is password protected - */ - public static Workbook create(File file) throws IOException, EncryptedDocumentException { - return create(file, null); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given File, which must exist and be readable, and - * may be password protected - * <p>Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param file The file to read data from. - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - public static Workbook create(File file, String password) throws IOException, EncryptedDocumentException { - return create(file, password, false); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given File, which must exist and be readable, and - * may be password protected - * <p>Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param file The file to read data from. - * @param password The password that should be used or null if no password is necessary. - * @param readOnly If the Workbook should be opened in read-only mode to avoid writing back - * changes when the document is closed. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - public static Workbook create(File file, String password, boolean readOnly) throws IOException, EncryptedDocumentException { - if (!file.exists()) { - throw new FileNotFoundException(file.toString()); - } - - if (file.length() == 0) { - throw new EmptyFileException(file); - } - - FileMagic fm = FileMagic.valueOf(file); - if (fm == FileMagic.OOXML) { - return wp(fm, w -> w.create(file, password, readOnly)); - } else if (fm == FileMagic.OLE2) { - final boolean ooxmlEnc; - try (POIFSFileSystem fs = new POIFSFileSystem(file, true)) { - DirectoryNode root = fs.getRoot(); - ooxmlEnc = root.hasEntry(DEFAULT_POIFS_ENTRY) || root.hasEntry(OOXML_PACKAGE); - } - return wp(ooxmlEnc ? FileMagic.OOXML : fm, w -> w.create(file, password, readOnly)); - } - - return null; - } - - - private static Workbook wp(FileMagic fm, ProviderMethod fun) throws IOException { - - for (WorkbookProvider prov : Singleton.INSTANCE.provider) { - if (prov.accepts(fm)) { - return fun.create(prov); - } - } - throw new IOException("Your InputStream was neither an OLE2 stream, nor an OOXML stream " + - "or you haven't provide the poi-ooxml*.jar in the classpath/modulepath - FileMagic: " + fm + - ", having providers: " + Singleton.INSTANCE.provider); - } - - public static void addProvider(WorkbookProvider provider){ - Singleton.INSTANCE.provider.add(provider); - } - - public static void removeProvider(Class<? extends WorkbookProvider> provider){ - Singleton.INSTANCE.provider.removeIf(p -> p.getClass().isAssignableFrom(provider)); - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/WorkbookProvider.java b/src/java/org/apache/poi/ss/usermodel/WorkbookProvider.java deleted file mode 100644 index 12b8cc8dee..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/WorkbookProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.FileMagic; - -public interface WorkbookProvider { - boolean accepts(FileMagic fm); - - Workbook create(); - - Workbook create(InputStream inp) throws IOException; - - Workbook create(InputStream inp, String password) throws IOException; - - Workbook create(DirectoryNode root, String password) throws IOException; - - Workbook create(File file, String password, boolean readOnly) throws IOException; -} diff --git a/src/java/org/apache/poi/ss/usermodel/helpers/BaseRowColShifter.java b/src/java/org/apache/poi/ss/usermodel/helpers/BaseRowColShifter.java deleted file mode 100644 index a044932cb8..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/helpers/BaseRowColShifter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel.helpers; - - -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.formula.ptg.AreaErrPtg; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.Internal; - -import java.util.List; - -/** - * Class for code common to {@link RowShifter} and {@link ColumnShifter} - * Helper for shifting rows up or down and columns left and right - * - * @since POI 4.0.0 - */ -@Internal -public abstract class BaseRowColShifter { - - /** - * Update named ranges - */ - public abstract void updateNamedRanges(FormulaShifter formulaShifter); - - /** - * Update formulas. - */ - public abstract void updateFormulas(FormulaShifter formulaShifter); - - /** - * Shifts, grows, or shrinks the merged regions due to a row shift - * ({@link RowShifter}) or column shift ({@link ColumnShifter}). - * Merged regions that are completely overlaid by shifting will be deleted. - * - * @param start the first row or column to be shifted - * @param end the last row or column to be shifted - * @param n the number of rows or columns to shift - * @return a list of affected merged regions, excluding contain deleted ones - */ - public abstract List<CellRangeAddress> shiftMergedRegions(int start, int end, int n); - - /** - * Update conditional formatting - * @param formulaShifter The {@link FormulaShifter} to use - */ - public abstract void updateConditionalFormatting(FormulaShifter formulaShifter); - - /** - * Shift the Hyperlink anchors (not the hyperlink text, even if the hyperlink - * is of type LINK_DOCUMENT and refers to a cell that was shifted). Hyperlinks - * do not track the content they point to. - * - * @param formulaShifter the formula shifting policy - */ - public abstract void updateHyperlinks(FormulaShifter formulaShifter); - - public static CellRangeAddress shiftRange(FormulaShifter formulaShifter, CellRangeAddress cra, int currentExternSheetIx) { - // FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here - AreaPtg aptg = new AreaPtg(cra.getFirstRow(), cra.getLastRow(), cra.getFirstColumn(), cra.getLastColumn(), false, false, false, false); - Ptg[] ptgs = { aptg, }; - - if (!formulaShifter.adjustFormula(ptgs, currentExternSheetIx)) { - return cra; - } - Ptg ptg0 = ptgs[0]; - if (ptg0 instanceof AreaPtg) { - AreaPtg bptg = (AreaPtg) ptg0; - return new CellRangeAddress(bptg.getFirstRow(), bptg.getLastRow(), bptg.getFirstColumn(), bptg.getLastColumn()); - } - if (ptg0 instanceof AreaErrPtg) { - return null; - } - throw new IllegalStateException("Unexpected shifted ptg class (" + ptg0.getClass().getName() + ")"); - } - -} diff --git a/src/java/org/apache/poi/ss/usermodel/helpers/ColumnShifter.java b/src/java/org/apache/poi/ss/usermodel/helpers/ColumnShifter.java deleted file mode 100644 index c6d97f3ff6..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/helpers/ColumnShifter.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel.helpers; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.Beta; - -/** - * Helper for shifting columns up or down - * - * @since POI 4.0.0 - */ -// non-Javadoc: This abstract class exists to consolidate duplicated code between XSSFColumnShifter and HSSFColumnShifter -// (currently methods sprinkled throughout HSSFSheet) -@Beta -public abstract class ColumnShifter extends BaseRowColShifter { - protected final Sheet sheet; - - public ColumnShifter(Sheet sh) { - sheet = sh; - } - - /** - * Shifts, grows, or shrinks the merged regions due to a column shift. - * Merged regions that are completely overlaid by shifting will be deleted. - * - * @param startColumn the column to start shifting - * @param endColumn the column to end shifting - * @param n the number of columns to shift - * @return an array of affected merged regions, doesn't contain deleted ones - * @since POI 4.0.0 - */ - // Keep this code in sync with {@link RowShifter#shiftMergedRegions} - @Override - public List<CellRangeAddress> shiftMergedRegions(int startColumn, int endColumn, int n) { - List<CellRangeAddress> shiftedRegions = new ArrayList<>(); - Set<Integer> removedIndices = new HashSet<>(); - //move merged regions completely if they fall within the new region boundaries when they are shifted - int size = sheet.getNumMergedRegions(); - for (int i = 0; i < size; i++) { - CellRangeAddress merged = sheet.getMergedRegion(i); - - // remove merged region that are replaced by the shifting, - // i.e. where the area includes something in the overwritten area - if(removalNeeded(merged, startColumn, endColumn, n)) { - removedIndices.add(i); - continue; - } - - boolean inStart = (merged.getFirstColumn() >= startColumn || merged.getLastColumn() >= startColumn); - boolean inEnd = (merged.getFirstColumn() <= endColumn || merged.getLastColumn() <= endColumn); - - //don't check if it's not within the shifted area - if (!inStart || !inEnd) { - continue; - } - - //only shift if the region outside the shifted columns is not merged too - if (!merged.containsColumn(startColumn - 1) && !merged.containsColumn(endColumn + 1)) { - merged.setFirstColumn(merged.getFirstColumn() + n); - merged.setLastColumn(merged.getLastColumn() + n); - //have to remove/add it back - shiftedRegions.add(merged); - removedIndices.add(i); - } - } - - if(!removedIndices.isEmpty()) { - sheet.removeMergedRegions(removedIndices); - } - - //read so it doesn't get shifted again - for (CellRangeAddress region : shiftedRegions) { - sheet.addMergedRegion(region); - } - return shiftedRegions; - } - - // Keep in sync with {@link RowShifter#removalNeeded} - private boolean removalNeeded(CellRangeAddress merged, int startColumn, int endColumn, int n) { - final int movedColumns = endColumn - startColumn + 1; - - // build a range of the columns that are overwritten, i.e. the target-area, but without - // columns that are moved along - final CellRangeAddress overwrite; - if(n > 0) { - // area is moved down => overwritten area is [endColumn + n - movedColumns, endColumn + n] - final int firstCol = Math.max(endColumn + 1, endColumn + n - movedColumns); - final int lastCol = endColumn + n; - overwrite = new CellRangeAddress(0, 0, firstCol, lastCol); - } else { - // area is moved up => overwritten area is [startColumn + n, startColumn + n + movedColumns] - final int firstCol = startColumn + n; - final int lastCol = Math.min(startColumn - 1, startColumn + n + movedColumns); - overwrite = new CellRangeAddress(0, 0, firstCol, lastCol); - } - - // if the merged-region and the overwritten area intersect, we need to remove it - return merged.intersects(overwrite); - } - - public void shiftColumns(int firstShiftColumnIndex, int lastShiftColumnIndex, int step){ - if(step > 0){ - for (Row row : sheet) - if(row != null) - row.shiftCellsRight(firstShiftColumnIndex, lastShiftColumnIndex, step); - } - else if(step < 0){ - for (Row row : sheet) - if(row != null) - row.shiftCellsLeft(firstShiftColumnIndex, lastShiftColumnIndex, -step); - } - //else step == 0 => nothing to shift - } -} diff --git a/src/java/org/apache/poi/ss/usermodel/helpers/RowShifter.java b/src/java/org/apache/poi/ss/usermodel/helpers/RowShifter.java deleted file mode 100644 index 2c4b3fa507..0000000000 --- a/src/java/org/apache/poi/ss/usermodel/helpers/RowShifter.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - 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. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel.helpers; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LocaleUtil; - -/** - * Helper for shifting rows up or down - */ -// non-Javadoc: This abstract class exists to consolidate duplicated code between -// {@link org.apache.poi.hssf.usermodel.helpers.HSSFRowShifter} and -// {@link org.apache.poi.xssf.usermodel.helpers.XSSFRowShifter} -// (currently methods sprinkled throughout HSSFSheet) -public abstract class RowShifter extends BaseRowColShifter { - protected final Sheet sheet; - - public RowShifter(Sheet sh) { - sheet = sh; - } - - /** - * Shifts, grows, or shrinks the merged regions due to a row shift. - * Merged regions that are completely overlaid by shifting will be deleted. - * - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - * @return an array of affected merged regions, doesn't contain deleted ones - */ - // Keep this code in sync with {@link ColumnShifter#shiftMergedRegions} - @Override - public List<CellRangeAddress> shiftMergedRegions(int startRow, int endRow, int n) { - List<CellRangeAddress> shiftedRegions = new ArrayList<>(); - Set<Integer> removedIndices = new HashSet<>(); - //move merged regions completely if they fall within the new region boundaries when they are shifted - int size = sheet.getNumMergedRegions(); - for (int i = 0; i < size; i++) { - CellRangeAddress merged = sheet.getMergedRegion(i); - - // remove merged region that are replaced by the shifting, - // i.e. where the area includes something in the overwritten area - if(removalNeeded(merged, startRow, endRow, n)) { - removedIndices.add(i); - continue; - } - - boolean inStart = (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow); - boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow); - - //don't check if it's not within the shifted area - if (!inStart || !inEnd) { - continue; - } - - //only shift if the region outside the shifted rows is not merged too - if (!merged.containsRow(startRow - 1) && !merged.containsRow(endRow + 1)) { - merged.setFirstRow(merged.getFirstRow() + n); - merged.setLastRow(merged.getLastRow() + n); - //have to remove/add it back - shiftedRegions.add(merged); - removedIndices.add(i); - } - } - - if(!removedIndices.isEmpty()) { - sheet.removeMergedRegions(removedIndices); - } - - //read so it doesn't get shifted again - for (CellRangeAddress region : shiftedRegions) { - sheet.addMergedRegion(region); - } - return shiftedRegions; - } - - // Keep in sync with {@link ColumnShifter#removalNeeded} - private boolean removalNeeded(CellRangeAddress merged, int startRow, int endRow, int n) { - final int movedRows = endRow - startRow + 1; - - // build a range of the rows that are overwritten, i.e. the target-area, but without - // rows that are moved along - final CellRangeAddress overwrite; - if(n > 0) { - // area is moved down => overwritten area is [endRow + n - movedRows, endRow + n] - final int firstRow = Math.max(endRow + 1, endRow + n - movedRows); - final int lastRow = endRow + n; - overwrite = new CellRangeAddress(firstRow, lastRow, 0, 0); - } else { - // area is moved up => overwritten area is [startRow + n, startRow + n + movedRows] - final int firstRow = startRow + n; - final int lastRow = Math.min(startRow - 1, startRow + n + movedRows); - overwrite = new CellRangeAddress(firstRow, lastRow, 0, 0); - } - - // if the merged-region and the overwritten area intersect, we need to remove it - return merged.intersects(overwrite); - } - - /** - * Verify that the given column indices and step denote a valid range of columns to shift - * - * @param firstShiftColumnIndex the column to start shifting - * @param lastShiftColumnIndex the column to end shifting - * @param step length of the shifting step - */ - public static void validateShiftParameters(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) { - if(step < 0) { - throw new IllegalArgumentException("Shifting step may not be negative, but had " + step); - } - if(firstShiftColumnIndex > lastShiftColumnIndex) { - throw new IllegalArgumentException(String.format(LocaleUtil.getUserLocale(), - "Incorrect shifting range : %d-%d", firstShiftColumnIndex, lastShiftColumnIndex)); - } - } - - /** - * Verify that the given column indices and step denote a valid range of columns to shift to the left - * - * @param firstShiftColumnIndex the column to start shifting - * @param lastShiftColumnIndex the column to end shifting - * @param step length of the shifting step - */ - public static void validateShiftLeftParameters(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) { - validateShiftParameters(firstShiftColumnIndex, lastShiftColumnIndex, step); - - if(firstShiftColumnIndex - step < 0) { - throw new IllegalStateException("Column index less than zero: " + (firstShiftColumnIndex + step)); - } - } -} |