diff options
Diffstat (limited to 'src/java/org/apache/poi/ss')
26 files changed, 3048 insertions, 3049 deletions
diff --git a/src/java/org/apache/poi/ss/SpreadsheetVersion.java b/src/java/org/apache/poi/ss/SpreadsheetVersion.java index 4a7b2bbe4f..316e5af06f 100755 --- a/src/java/org/apache/poi/ss/SpreadsheetVersion.java +++ b/src/java/org/apache/poi/ss/SpreadsheetVersion.java @@ -1,120 +1,119 @@ -/* ====================================================================
- 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;
-
-import org.apache.poi.ss.util.CellReference;
-
-/**
- * This enum allows spreadsheets from multiple Excel versions to be handled by the common code.
- * Properties of this enum correspond to attributes of the <i>spreadsheet</i> that are easily
- * discernable to the user. It is not intended to deal with low-level issues like file formats.
- * <p/>
- *
- * @author Josh Micich
- * @author Yegor Kozlov
- */
-public enum SpreadsheetVersion {
- /**
- * Excel97 format aka BIFF8
- * <ul>
- * <li>The total number of available columns is 256 (2^8)</li>
- * <li>The total number of available rows is 64k (2^16)</li>
- * <li>The maximum number of arguments to a function is 30</li>
- * <li>Number of conditional format conditions on a cell is 3</li>
- * </ul>
- */
- EXCEL97(0x10000, 0x0100, 30, 3),
-
- /**
- * Excel2007
- *
- * <ul>
- * <li>The total number of available columns is 16K (2^14)</li>
- * <li>The total number of available rows is 1M (2^20)</li>
- * <li>The maximum number of arguments to a function is 255</li>
- * <li>Number of conditional format conditions on a cell is unlimited
- * (actually limited by available memory in Excel)</li>
- * <ul>
- */
- EXCEL2007(0x100000, 0x4000, 255, Integer.MAX_VALUE);
-
- private final int _maxRows;
- private final int _maxColumns;
- private final int _maxFunctionArgs;
- private final int _maxCondFormats;
-
- private SpreadsheetVersion(int maxRows, int maxColumns, int maxFunctionArgs, int maxCondFormats) {
- _maxRows = maxRows;
- _maxColumns = maxColumns;
- _maxFunctionArgs = maxFunctionArgs;
- _maxCondFormats = maxCondFormats;
- }
-
- /**
- * @return the maximum number of usable rows in each spreadsheet
- */
- public int getMaxRows() {
- return _maxRows;
- }
-
- /**
- * @return the last (maximum) valid row index, equals to <code> getMaxRows() - 1 </code>
- */
- public int getLastRowIndex() {
- return _maxRows - 1;
- }
-
- /**
- * @return the maximum number of usable columns in each spreadsheet
- */
- public int getMaxColumns() {
- return _maxColumns;
- }
-
- /**
- * @return the last (maximum) valid column index, equals to <code> getMaxColumns() - 1 </code>
- */
- public int getLastColumnIndex() {
- return _maxColumns - 1;
- }
-
- /**
- * @return the maximum number arguments that can be passed to a multi-arg
- * function (e.g. COUNTIF)
- */
- public int getMaxFunctionArgs() {
- return _maxFunctionArgs;
- }
-
- /**
- *
- * @return the maximum number of conditional format conditions on a cell
- */
- public int getMaxConditionalFormats() {
- return _maxCondFormats;
- }
-
- /**
- *
- * @return the last valid column index in a ALPHA-26 representation
- * ( <code>IV</code> or <code>XFD</code>).
- */
- public String getLastColumnName() {
- return CellReference.convertNumToColString(getLastColumnIndex());
- }
-}
+/* ==================================================================== + 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; + +import org.apache.poi.ss.util.CellReference; + +/** + * This enum allows spreadsheets from multiple Excel versions to be handled by the common code. + * Properties of this enum correspond to attributes of the <i>spreadsheet</i> that are easily + * discernable to the user. It is not intended to deal with low-level issues like file formats. + * <p/> + * + * @author Josh Micich + * @author Yegor Kozlov + */ +public enum SpreadsheetVersion { + /** + * Excel97 format aka BIFF8 + * <ul> + * <li>The total number of available columns is 256 (2^8)</li> + * <li>The total number of available rows is 64k (2^16)</li> + * <li>The maximum number of arguments to a function is 30</li> + * <li>Number of conditional format conditions on a cell is 3</li> + * </ul> + */ + EXCEL97(0x10000, 0x0100, 30, 3), + + /** + * Excel2007 + * + * <ul> + * <li>The total number of available columns is 16K (2^14)</li> + * <li>The total number of available rows is 1M (2^20)</li> + * <li>The maximum number of arguments to a function is 255</li> + * <li>Number of conditional format conditions on a cell is unlimited + * (actually limited by available memory in Excel)</li> + * <ul> + */ + EXCEL2007(0x100000, 0x4000, 255, Integer.MAX_VALUE); + + private final int _maxRows; + private final int _maxColumns; + private final int _maxFunctionArgs; + private final int _maxCondFormats; + + private SpreadsheetVersion(int maxRows, int maxColumns, int maxFunctionArgs, int maxCondFormats) { + _maxRows = maxRows; + _maxColumns = maxColumns; + _maxFunctionArgs = maxFunctionArgs; + _maxCondFormats = maxCondFormats; + } + + /** + * @return the maximum number of usable rows in each spreadsheet + */ + public int getMaxRows() { + return _maxRows; + } + + /** + * @return the last (maximum) valid row index, equals to <code> getMaxRows() - 1 </code> + */ + public int getLastRowIndex() { + return _maxRows - 1; + } + + /** + * @return the maximum number of usable columns in each spreadsheet + */ + public int getMaxColumns() { + return _maxColumns; + } + + /** + * @return the last (maximum) valid column index, equals to <code> getMaxColumns() - 1 </code> + */ + public int getLastColumnIndex() { + return _maxColumns - 1; + } + + /** + * @return the maximum number arguments that can be passed to a multi-arg function (e.g. COUNTIF) + */ + public int getMaxFunctionArgs() { + return _maxFunctionArgs; + } + + /** + * + * @return the maximum number of conditional format conditions on a cell + */ + public int getMaxConditionalFormats() { + return _maxCondFormats; + } + + /** + * + * @return the last valid column index in a ALPHA-26 representation + * (<code>IV</code> or <code>XFD</code>). + */ + public String getLastColumnName() { + return CellReference.convertNumToColString(getLastColumnIndex()); + } +} diff --git a/src/java/org/apache/poi/ss/formula/CellEvaluationFrame.java b/src/java/org/apache/poi/ss/formula/CellEvaluationFrame.java index a9f79e9e64..186fe6e1c8 100644 --- a/src/java/org/apache/poi/ss/formula/CellEvaluationFrame.java +++ b/src/java/org/apache/poi/ss/formula/CellEvaluationFrame.java @@ -1,77 +1,77 @@ -/* ====================================================================
- 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.formula;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.poi.hssf.record.formula.eval.ValueEval;
-
-/**
- * Stores details about the current evaluation of a cell.<br/>
- */
-final class CellEvaluationFrame {
-
- private final FormulaCellCacheEntry _cce;
- private final Set<CellCacheEntry> _sensitiveInputCells;
- private FormulaUsedBlankCellSet _usedBlankCellGroup;
-
- public CellEvaluationFrame(FormulaCellCacheEntry cce) {
- _cce = cce;
- _sensitiveInputCells = new HashSet<CellCacheEntry>();
- }
- public CellCacheEntry getCCE() {
- return _cce;
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer(64);
- sb.append(getClass().getName()).append(" [");
- sb.append("]");
- return sb.toString();
- }
- /**
- * @param inputCell a cell directly used by the formula of this evaluation frame
- */
- public void addSensitiveInputCell(CellCacheEntry inputCell) {
- _sensitiveInputCells.add(inputCell);
- }
- /**
- * @return never <code>null</code>, (possibly empty) array of all cells directly used while
- * evaluating the formula of this frame.
- */
- private CellCacheEntry[] getSensitiveInputCells() {
- int nItems = _sensitiveInputCells.size();
- if (nItems < 1) {
- return CellCacheEntry.EMPTY_ARRAY;
- }
- CellCacheEntry[] result = new CellCacheEntry[nItems];
- _sensitiveInputCells.toArray(result);
- return result;
- }
- public void addUsedBlankCell(int bookIndex, int sheetIndex, int rowIndex, int columnIndex) {
- if (_usedBlankCellGroup == null) {
- _usedBlankCellGroup = new FormulaUsedBlankCellSet();
- }
- _usedBlankCellGroup.addCell(bookIndex, sheetIndex, rowIndex, columnIndex);
- }
-
- public void updateFormulaResult(ValueEval result) {
- _cce.updateFormulaResult(result, getSensitiveInputCells(), _usedBlankCellGroup);
- }
-}
\ No newline at end of file +/* ==================================================================== + 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.formula; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.poi.hssf.record.formula.eval.ValueEval; + +/** + * Stores details about the current evaluation of a cell.<br/> + */ +final class CellEvaluationFrame { + + private final FormulaCellCacheEntry _cce; + private final Set<CellCacheEntry> _sensitiveInputCells; + private FormulaUsedBlankCellSet _usedBlankCellGroup; + + public CellEvaluationFrame(FormulaCellCacheEntry cce) { + _cce = cce; + _sensitiveInputCells = new HashSet<CellCacheEntry>(); + } + public CellCacheEntry getCCE() { + return _cce; + } + + public String toString() { + StringBuffer sb = new StringBuffer(64); + sb.append(getClass().getName()).append(" ["); + sb.append("]"); + return sb.toString(); + } + /** + * @param inputCell a cell directly used by the formula of this evaluation frame + */ + public void addSensitiveInputCell(CellCacheEntry inputCell) { + _sensitiveInputCells.add(inputCell); + } + /** + * @return never <code>null</code>, (possibly empty) array of all cells directly used while + * evaluating the formula of this frame. + */ + private CellCacheEntry[] getSensitiveInputCells() { + int nItems = _sensitiveInputCells.size(); + if (nItems < 1) { + return CellCacheEntry.EMPTY_ARRAY; + } + CellCacheEntry[] result = new CellCacheEntry[nItems]; + _sensitiveInputCells.toArray(result); + return result; + } + public void addUsedBlankCell(int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { + if (_usedBlankCellGroup == null) { + _usedBlankCellGroup = new FormulaUsedBlankCellSet(); + } + _usedBlankCellGroup.addCell(bookIndex, sheetIndex, rowIndex, columnIndex); + } + + public void updateFormulaResult(ValueEval result) { + _cce.updateFormulaResult(result, getSensitiveInputCells(), _usedBlankCellGroup); + } +} diff --git a/src/java/org/apache/poi/ss/formula/EvaluationName.java b/src/java/org/apache/poi/ss/formula/EvaluationName.java index ae8624c7b8..7d6688bb82 100644 --- a/src/java/org/apache/poi/ss/formula/EvaluationName.java +++ b/src/java/org/apache/poi/ss/formula/EvaluationName.java @@ -1,41 +1,41 @@ -/* ====================================================================
- 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.formula;
-
-import org.apache.poi.hssf.record.formula.NamePtg;
-import org.apache.poi.hssf.record.formula.Ptg;
-/**
- * Abstracts a name record for formula evaluation.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public interface EvaluationName {
-
- String getNameText();
-
- boolean isFunctionName();
-
- boolean hasFormula();
-
- Ptg[] getNameDefinition();
-
- boolean isRange();
- NamePtg createPtg();
-}
+/* ==================================================================== + 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.formula; + +import org.apache.poi.hssf.record.formula.NamePtg; +import org.apache.poi.hssf.record.formula.Ptg; +/** + * Abstracts a name record for formula evaluation.<br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public interface EvaluationName { + + String getNameText(); + + boolean isFunctionName(); + + boolean hasFormula(); + + Ptg[] getNameDefinition(); + + boolean isRange(); + NamePtg createPtg(); +} diff --git a/src/java/org/apache/poi/ss/formula/EvaluationWorkbook.java b/src/java/org/apache/poi/ss/formula/EvaluationWorkbook.java index 45b0c918f2..28f31eb497 100644 --- a/src/java/org/apache/poi/ss/formula/EvaluationWorkbook.java +++ b/src/java/org/apache/poi/ss/formula/EvaluationWorkbook.java @@ -1,65 +1,65 @@ -/* ====================================================================
- 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.formula;
-
-import org.apache.poi.hssf.record.formula.NamePtg;
-import org.apache.poi.hssf.record.formula.NameXPtg;
-import org.apache.poi.hssf.record.formula.Ptg;
-
-/**
- * Abstracts a workbook for the purpose of formula evaluation.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public interface EvaluationWorkbook {
- String getSheetName(int sheetIndex);
- /**
- * @return -1 if the specified sheet is from a different book
- */
- int getSheetIndex(EvaluationSheet sheet);
- int getSheetIndex(String sheetName);
-
- EvaluationSheet getSheet(int sheetIndex);
-
- /**
- * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook
- */
- ExternalSheet getExternalSheet(int externSheetIndex);
- int convertFromExternSheetIndex(int externSheetIndex);
- EvaluationName getName(NamePtg namePtg);
- String resolveNameXText(NameXPtg ptg);
- Ptg[] getFormulaTokens(EvaluationCell cell);
-
- class ExternalSheet {
- private final String _workbookName;
- private final String _sheetName;
-
- public ExternalSheet(String workbookName, String sheetName) {
- _workbookName = workbookName;
- _sheetName = sheetName;
- }
- public String getWorkbookName() {
- return _workbookName;
- }
- public String getSheetName() {
- return _sheetName;
- }
- }
-}
+/* ==================================================================== + 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.formula; + +import org.apache.poi.hssf.record.formula.NamePtg; +import org.apache.poi.hssf.record.formula.NameXPtg; +import org.apache.poi.hssf.record.formula.Ptg; + +/** + * Abstracts a workbook for the purpose of formula evaluation.<br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public interface EvaluationWorkbook { + String getSheetName(int sheetIndex); + /** + * @return -1 if the specified sheet is from a different book + */ + int getSheetIndex(EvaluationSheet sheet); + int getSheetIndex(String sheetName); + + EvaluationSheet getSheet(int sheetIndex); + + /** + * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook + */ + ExternalSheet getExternalSheet(int externSheetIndex); + int convertFromExternSheetIndex(int externSheetIndex); + EvaluationName getName(NamePtg namePtg); + String resolveNameXText(NameXPtg ptg); + Ptg[] getFormulaTokens(EvaluationCell cell); + + class ExternalSheet { + private final String _workbookName; + private final String _sheetName; + + public ExternalSheet(String workbookName, String sheetName) { + _workbookName = workbookName; + _sheetName = sheetName; + } + public String getWorkbookName() { + return _workbookName; + } + public String getSheetName() { + return _sheetName; + } + } +} diff --git a/src/java/org/apache/poi/ss/formula/Formula.java b/src/java/org/apache/poi/ss/formula/Formula.java index f2cef2cb42..0eb8a7f6dc 100644 --- a/src/java/org/apache/poi/ss/formula/Formula.java +++ b/src/java/org/apache/poi/ss/formula/Formula.java @@ -1,197 +1,197 @@ -/* ====================================================================
- 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.formula;
-
-import java.util.Arrays;
-
-import org.apache.poi.hssf.record.ArrayRecord;
-import org.apache.poi.hssf.record.SharedFormulaRecord;
-import org.apache.poi.hssf.record.TableRecord;
-import org.apache.poi.hssf.record.formula.ExpPtg;
-import org.apache.poi.hssf.record.formula.Ptg;
-import org.apache.poi.hssf.record.formula.TblPtg;
-import org.apache.poi.hssf.util.CellReference;
-import org.apache.poi.util.LittleEndian;
-import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianInput;
-import org.apache.poi.util.LittleEndianOutput;
-
-/**
- * Encapsulates an encoded formula token array.
- *
- * @author Josh Micich
- */
-public class Formula {
-
- private static final Formula EMPTY = new Formula(new byte[0], 0);
-
- /** immutable */
- private final byte[] _byteEncoding;
- private final int _encodedTokenLen;
-
- private Formula(byte[] byteEncoding, int encodedTokenLen) {
- _byteEncoding = byteEncoding;
- _encodedTokenLen = encodedTokenLen;
- if (false) { // set to true to eagerly check Ptg decoding
- LittleEndianByteArrayInputStream in = new LittleEndianByteArrayInputStream(byteEncoding);
- Ptg.readTokens(encodedTokenLen, in);
- int nUnusedBytes = _byteEncoding.length - in.getReadIndex();
- if (nUnusedBytes > 0) {
- // TODO - this seems to occur when IntersectionPtg is present
- // This example file "IntersectionPtg.xls"
- // used by test: TestIntersectionPtg.testReading()
- // has 10 bytes unused at the end of the formula
- // 10 extra bytes are just 0x01 and 0x00
- System.out.println(nUnusedBytes + " unused bytes at end of formula");
- }
- }
- }
- /**
- * Convenience method for {@link #read(int, LittleEndianInput, int)}
- */
- public static Formula read(int encodedTokenLen, LittleEndianInput in) {
- return read(encodedTokenLen, in, encodedTokenLen);
- }
- /**
- * When there are no array constants present, <tt>encodedTokenLen</tt>==<tt>totalEncodedLen</tt>
- * @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens
- * @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding
- * for array constants, but does not include 2 bytes for initial <tt>ushort encodedTokenLen</tt> field.
- * @return A new formula object as read from the stream. Possibly empty, never <code>null</code>.
- */
- public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) {
- byte[] byteEncoding = new byte[totalEncodedLen];
- in.readFully(byteEncoding);
- return new Formula(byteEncoding, encodedTokenLen);
- }
-
- public Ptg[] getTokens() {
- LittleEndianInput in = new LittleEndianByteArrayInputStream(_byteEncoding);
- return Ptg.readTokens(_encodedTokenLen, in);
- }
- /**
- * Writes The formula encoding is includes:
- * <ul>
- * <li>ushort tokenDataLen</li>
- * <li>tokenData</li>
- * <li>arrayConstantData (if present)</li>
- * </ul>
- */
- public void serialize(LittleEndianOutput out) {
- out.writeShort(_encodedTokenLen);
- out.write(_byteEncoding);
- }
-
- public void serializeTokens(LittleEndianOutput out) {
- out.write(_byteEncoding, 0, _encodedTokenLen);
- }
- public void serializeArrayConstantData(LittleEndianOutput out) {
- int len = _byteEncoding.length-_encodedTokenLen;
- out.write(_byteEncoding, _encodedTokenLen, len);
- }
-
-
- /**
- * @return total formula encoding length. The formula encoding includes:
- * <ul>
- * <li>ushort tokenDataLen</li>
- * <li>tokenData</li>
- * <li>arrayConstantData (optional)</li>
- * </ul>
- * Note - this value is different to <tt>tokenDataLength</tt>
- */
- public int getEncodedSize() {
- return 2 + _byteEncoding.length;
- }
- /**
- * This method is often used when the formula length does not appear immediately before
- * the encoded token data.
- *
- * @return the encoded length of the plain formula tokens. This does <em>not</em> include
- * the leading ushort field, nor any trailing array constant data.
- */
- public int getEncodedTokenSize() {
- return _encodedTokenLen;
- }
-
- /**
- * Creates a {@link Formula} object from a supplied {@link Ptg} array.
- * Handles <code>null</code>s OK.
- * @param ptgs may be <code>null</code>
- * @return Never <code>null</code> (Possibly empty if the supplied <tt>ptgs</tt> is <code>null</code>)
- */
- public static Formula create(Ptg[] ptgs) {
- if (ptgs == null || ptgs.length < 1) {
- return EMPTY;
- }
- int totalSize = Ptg.getEncodedSize(ptgs);
- byte[] encodedData = new byte[totalSize];
- Ptg.serializePtgs(ptgs, encodedData, 0);
- int encodedTokenLen = Ptg.getEncodedSizeWithoutArrayData(ptgs);
- return new Formula(encodedData, encodedTokenLen);
- }
- /**
- * Gets the {@link Ptg} array from the supplied {@link Formula}.
- * Handles <code>null</code>s OK.
- *
- * @param formula may be <code>null</code>
- * @return possibly <code>null</code> (if the supplied <tt>formula</tt> is <code>null</code>)
- */
- public static Ptg[] getTokens(Formula formula) {
- if (formula == null) {
- return null;
- }
- return formula.getTokens();
- }
-
- public Formula copy() {
- // OK to return this because immutable
- return this;
- }
-
- /**
- * Gets the locator for the corresponding {@link SharedFormulaRecord}, {@link ArrayRecord} or
- * {@link TableRecord} if this formula belongs to such a grouping. The {@link CellReference}
- * returned by this method will match the top left corner of the range of that grouping.
- * The return value is usually not the same as the location of the cell containing this formula.
- *
- * @return the firstRow & firstColumn of an array formula or shared formula that this formula
- * belongs to. <code>null</code> if this formula is not part of an array or shared formula.
- */
- public CellReference getExpReference() {
- byte[] data = _byteEncoding;
- if (data.length != 5) {
- // tExp and tTbl are always 5 bytes long, and the only ptg in the formula
- return null;
- }
- switch (data[0]) {
- case ExpPtg.sid:
- break;
- case TblPtg.sid:
- break;
- default:
- return null;
- }
- int firstRow = LittleEndian.getUShort(data, 1);
- int firstColumn = LittleEndian.getUShort(data, 3);
- return new CellReference(firstRow, firstColumn);
- }
- public boolean isSame(Formula other) {
- return Arrays.equals(_byteEncoding, other._byteEncoding);
- }
-}
+/* ==================================================================== + 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.formula; + +import java.util.Arrays; + +import org.apache.poi.hssf.record.ArrayRecord; +import org.apache.poi.hssf.record.SharedFormulaRecord; +import org.apache.poi.hssf.record.TableRecord; +import org.apache.poi.hssf.record.formula.ExpPtg; +import org.apache.poi.hssf.record.formula.Ptg; +import org.apache.poi.hssf.record.formula.TblPtg; +import org.apache.poi.hssf.util.CellReference; +import org.apache.poi.util.LittleEndian; +import org.apache.poi.util.LittleEndianByteArrayInputStream; +import org.apache.poi.util.LittleEndianInput; +import org.apache.poi.util.LittleEndianOutput; + +/** + * Encapsulates an encoded formula token array. + * + * @author Josh Micich + */ +public class Formula { + + private static final Formula EMPTY = new Formula(new byte[0], 0); + + /** immutable */ + private final byte[] _byteEncoding; + private final int _encodedTokenLen; + + private Formula(byte[] byteEncoding, int encodedTokenLen) { + _byteEncoding = byteEncoding; + _encodedTokenLen = encodedTokenLen; + if (false) { // set to true to eagerly check Ptg decoding + LittleEndianByteArrayInputStream in = new LittleEndianByteArrayInputStream(byteEncoding); + Ptg.readTokens(encodedTokenLen, in); + int nUnusedBytes = _byteEncoding.length - in.getReadIndex(); + if (nUnusedBytes > 0) { + // TODO - this seems to occur when IntersectionPtg is present + // This example file "IntersectionPtg.xls" + // used by test: TestIntersectionPtg.testReading() + // has 10 bytes unused at the end of the formula + // 10 extra bytes are just 0x01 and 0x00 + System.out.println(nUnusedBytes + " unused bytes at end of formula"); + } + } + } + /** + * Convenience method for {@link #read(int, LittleEndianInput, int)} + */ + public static Formula read(int encodedTokenLen, LittleEndianInput in) { + return read(encodedTokenLen, in, encodedTokenLen); + } + /** + * When there are no array constants present, <tt>encodedTokenLen</tt>==<tt>totalEncodedLen</tt> + * @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens + * @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding + * for array constants, but does not include 2 bytes for initial <tt>ushort encodedTokenLen</tt> field. + * @return A new formula object as read from the stream. Possibly empty, never <code>null</code>. + */ + public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) { + byte[] byteEncoding = new byte[totalEncodedLen]; + in.readFully(byteEncoding); + return new Formula(byteEncoding, encodedTokenLen); + } + + public Ptg[] getTokens() { + LittleEndianInput in = new LittleEndianByteArrayInputStream(_byteEncoding); + return Ptg.readTokens(_encodedTokenLen, in); + } + /** + * Writes The formula encoding is includes: + * <ul> + * <li>ushort tokenDataLen</li> + * <li>tokenData</li> + * <li>arrayConstantData (if present)</li> + * </ul> + */ + public void serialize(LittleEndianOutput out) { + out.writeShort(_encodedTokenLen); + out.write(_byteEncoding); + } + + public void serializeTokens(LittleEndianOutput out) { + out.write(_byteEncoding, 0, _encodedTokenLen); + } + public void serializeArrayConstantData(LittleEndianOutput out) { + int len = _byteEncoding.length-_encodedTokenLen; + out.write(_byteEncoding, _encodedTokenLen, len); + } + + + /** + * @return total formula encoding length. The formula encoding includes: + * <ul> + * <li>ushort tokenDataLen</li> + * <li>tokenData</li> + * <li>arrayConstantData (optional)</li> + * </ul> + * Note - this value is different to <tt>tokenDataLength</tt> + */ + public int getEncodedSize() { + return 2 + _byteEncoding.length; + } + /** + * This method is often used when the formula length does not appear immediately before + * the encoded token data. + * + * @return the encoded length of the plain formula tokens. This does <em>not</em> include + * the leading ushort field, nor any trailing array constant data. + */ + public int getEncodedTokenSize() { + return _encodedTokenLen; + } + + /** + * Creates a {@link Formula} object from a supplied {@link Ptg} array. + * Handles <code>null</code>s OK. + * @param ptgs may be <code>null</code> + * @return Never <code>null</code> (Possibly empty if the supplied <tt>ptgs</tt> is <code>null</code>) + */ + public static Formula create(Ptg[] ptgs) { + if (ptgs == null || ptgs.length < 1) { + return EMPTY; + } + int totalSize = Ptg.getEncodedSize(ptgs); + byte[] encodedData = new byte[totalSize]; + Ptg.serializePtgs(ptgs, encodedData, 0); + int encodedTokenLen = Ptg.getEncodedSizeWithoutArrayData(ptgs); + return new Formula(encodedData, encodedTokenLen); + } + /** + * Gets the {@link Ptg} array from the supplied {@link Formula}. + * Handles <code>null</code>s OK. + * + * @param formula may be <code>null</code> + * @return possibly <code>null</code> (if the supplied <tt>formula</tt> is <code>null</code>) + */ + public static Ptg[] getTokens(Formula formula) { + if (formula == null) { + return null; + } + return formula.getTokens(); + } + + public Formula copy() { + // OK to return this because immutable + return this; + } + + /** + * Gets the locator for the corresponding {@link SharedFormulaRecord}, {@link ArrayRecord} or + * {@link TableRecord} if this formula belongs to such a grouping. The {@link CellReference} + * returned by this method will match the top left corner of the range of that grouping. + * The return value is usually not the same as the location of the cell containing this formula. + * + * @return the firstRow & firstColumn of an array formula or shared formula that this formula + * belongs to. <code>null</code> if this formula is not part of an array or shared formula. + */ + public CellReference getExpReference() { + byte[] data = _byteEncoding; + if (data.length != 5) { + // tExp and tTbl are always 5 bytes long, and the only ptg in the formula + return null; + } + switch (data[0]) { + case ExpPtg.sid: + break; + case TblPtg.sid: + break; + default: + return null; + } + int firstRow = LittleEndian.getUShort(data, 1); + int firstColumn = LittleEndian.getUShort(data, 3); + return new CellReference(firstRow, firstColumn); + } + public boolean isSame(Formula other) { + return Arrays.equals(_byteEncoding, other._byteEncoding); + } +} diff --git a/src/java/org/apache/poi/ss/formula/FormulaParsingWorkbook.java b/src/java/org/apache/poi/ss/formula/FormulaParsingWorkbook.java index 2ecd69be9a..83f7c99a96 100644 --- a/src/java/org/apache/poi/ss/formula/FormulaParsingWorkbook.java +++ b/src/java/org/apache/poi/ss/formula/FormulaParsingWorkbook.java @@ -1,55 +1,55 @@ -/* ====================================================================
- 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.formula;
-
-import org.apache.poi.hssf.record.formula.NameXPtg;
-import org.apache.poi.ss.SpreadsheetVersion;
-
-/**
- * Abstracts a workbook for the purpose of formula parsing.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public interface FormulaParsingWorkbook {
- /**
- * named range name matching is case insensitive
- */
- EvaluationName getName(String name, int sheetIndex);
-
- NameXPtg getNameXPtg(String name);
-
- /**
- * gets the externSheet index for a sheet from this workbook
- */
- int getExternalSheetIndex(String sheetName);
- /**
- * gets the externSheet index for a sheet from an external workbook
- * @param workbookName e.g. "Budget.xls"
- * @param sheetName a name of a sheet in that workbook
- */
- int getExternalSheetIndex(String workbookName, String sheetName);
-
- /**
- * Returns an enum holding spreadhseet properties specific to an Excel version (
- * max column and row numbers, max arguments to a function, etc.)
- */
- SpreadsheetVersion getSpreadsheetVersion();
-
-}
+/* ==================================================================== + 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.formula; + +import org.apache.poi.hssf.record.formula.NameXPtg; +import org.apache.poi.ss.SpreadsheetVersion; + +/** + * Abstracts a workbook for the purpose of formula parsing.<br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public interface FormulaParsingWorkbook { + /** + * named range name matching is case insensitive + */ + EvaluationName getName(String name, int sheetIndex); + + NameXPtg getNameXPtg(String name); + + /** + * gets the externSheet index for a sheet from this workbook + */ + int getExternalSheetIndex(String sheetName); + /** + * gets the externSheet index for a sheet from an external workbook + * @param workbookName e.g. "Budget.xls" + * @param sheetName a name of a sheet in that workbook + */ + int getExternalSheetIndex(String workbookName, String sheetName); + + /** + * Returns an enum holding spreadhseet properties specific to an Excel version ( + * max column and row numbers, max arguments to a function, etc.) + */ + SpreadsheetVersion getSpreadsheetVersion(); + +} diff --git a/src/java/org/apache/poi/ss/formula/FormulaRenderer.java b/src/java/org/apache/poi/ss/formula/FormulaRenderer.java index df078809cf..76dce7f55e 100644 --- a/src/java/org/apache/poi/ss/formula/FormulaRenderer.java +++ b/src/java/org/apache/poi/ss/formula/FormulaRenderer.java @@ -1,131 +1,131 @@ -/* ====================================================================
- 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.formula;
-
-import java.util.Stack;
-
-import org.apache.poi.hssf.record.formula.AttrPtg;
-import org.apache.poi.hssf.record.formula.MemAreaPtg;
-import org.apache.poi.hssf.record.formula.MemErrPtg;
-import org.apache.poi.hssf.record.formula.MemFuncPtg;
-import org.apache.poi.hssf.record.formula.OperationPtg;
-import org.apache.poi.hssf.record.formula.ParenthesisPtg;
-import org.apache.poi.hssf.record.formula.Ptg;
-
-/**
- * Common logic for rendering formulas.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public class FormulaRenderer {
-
- /**
- * Static method to convert an array of {@link Ptg}s in RPN order
- * to a human readable string format in infix mode.
- * @param book used for defined names and 3D references
- * @param ptgs must not be <code>null</code>
- * @return a human readable String
- */
- public static String toFormulaString(FormulaRenderingWorkbook book, Ptg[] ptgs) {
- if (ptgs == null || ptgs.length == 0) {
- throw new IllegalArgumentException("ptgs must not be null");
- }
- Stack<String> stack = new Stack<String>();
-
- for (int i=0 ; i < ptgs.length; i++) {
- Ptg ptg = ptgs[i];
- // TODO - what about MemNoMemPtg?
- if(ptg instanceof MemAreaPtg || ptg instanceof MemFuncPtg || ptg instanceof MemErrPtg) {
- // marks the start of a list of area expressions which will be naturally combined
- // by their trailing operators (e.g. UnionPtg)
- // TODO - put comment and throw exception in toFormulaString() of these classes
- continue;
- }
- if (ptg instanceof ParenthesisPtg) {
- String contents = stack.pop();
- stack.push ("(" + contents + ")");
- continue;
- }
- if (ptg instanceof AttrPtg) {
- AttrPtg attrPtg = ((AttrPtg) ptg);
- if (attrPtg.isOptimizedIf() || attrPtg.isOptimizedChoose() || attrPtg.isGoto()) {
- continue;
- }
- if (attrPtg.isSpace()) {
- // POI currently doesn't render spaces in formulas
- continue;
- // but if it ever did, care must be taken:
- // tAttrSpace comes *before* the operand it applies to, which may be consistent
- // with how the formula text appears but is against the RPN ordering assumed here
- }
- if (attrPtg.isSemiVolatile()) {
- // similar to tAttrSpace - RPN is violated
- continue;
- }
- if (attrPtg.isSum()) {
- String[] operands = getOperands(stack, attrPtg.getNumberOfOperands());
- stack.push(attrPtg.toFormulaString(operands));
- continue;
- }
- throw new RuntimeException("Unexpected tAttr: " + attrPtg.toString());
- }
-
- if (ptg instanceof WorkbookDependentFormula) {
- WorkbookDependentFormula optg = (WorkbookDependentFormula) ptg;
- stack.push(optg.toFormulaString(book));
- continue;
- }
- if (! (ptg instanceof OperationPtg)) {
- stack.push(ptg.toFormulaString());
- continue;
- }
-
- OperationPtg o = (OperationPtg) ptg;
- String[] operands = getOperands(stack, o.getNumberOfOperands());
- stack.push(o.toFormulaString(operands));
- }
- if(stack.isEmpty()) {
- // inspection of the code above reveals that every stack.pop() is followed by a
- // stack.push(). So this is either an internal error or impossible.
- throw new IllegalStateException("Stack underflow");
- }
- String result = stack.pop();
- if(!stack.isEmpty()) {
- // Might be caused by some tokens like AttrPtg and Mem*Ptg, which really shouldn't
- // put anything on the stack
- throw new IllegalStateException("too much stuff left on the stack");
- }
- return result;
- }
-
- private static String[] getOperands(Stack<String> stack, int nOperands) {
- String[] operands = new String[nOperands];
-
- for (int j = nOperands-1; j >= 0; j--) { // reverse iteration because args were pushed in-order
- if(stack.isEmpty()) {
- String msg = "Too few arguments supplied to operation. Expected (" + nOperands
- + ") operands but got (" + (nOperands - j - 1) + ")";
- throw new IllegalStateException(msg);
- }
- operands[j] = stack.pop();
- }
- return operands;
- }
-}
+/* ==================================================================== + 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.formula; + +import java.util.Stack; + +import org.apache.poi.hssf.record.formula.AttrPtg; +import org.apache.poi.hssf.record.formula.MemAreaPtg; +import org.apache.poi.hssf.record.formula.MemErrPtg; +import org.apache.poi.hssf.record.formula.MemFuncPtg; +import org.apache.poi.hssf.record.formula.OperationPtg; +import org.apache.poi.hssf.record.formula.ParenthesisPtg; +import org.apache.poi.hssf.record.formula.Ptg; + +/** + * Common logic for rendering formulas.<br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public class FormulaRenderer { + + /** + * Static method to convert an array of {@link Ptg}s in RPN order + * to a human readable string format in infix mode. + * @param book used for defined names and 3D references + * @param ptgs must not be <code>null</code> + * @return a human readable String + */ + public static String toFormulaString(FormulaRenderingWorkbook book, Ptg[] ptgs) { + if (ptgs == null || ptgs.length == 0) { + throw new IllegalArgumentException("ptgs must not be null"); + } + Stack<String> stack = new Stack<String>(); + + for (int i=0 ; i < ptgs.length; i++) { + Ptg ptg = ptgs[i]; + // TODO - what about MemNoMemPtg? + if(ptg instanceof MemAreaPtg || ptg instanceof MemFuncPtg || ptg instanceof MemErrPtg) { + // marks the start of a list of area expressions which will be naturally combined + // by their trailing operators (e.g. UnionPtg) + // TODO - put comment and throw exception in toFormulaString() of these classes + continue; + } + if (ptg instanceof ParenthesisPtg) { + String contents = stack.pop(); + stack.push ("(" + contents + ")"); + continue; + } + if (ptg instanceof AttrPtg) { + AttrPtg attrPtg = ((AttrPtg) ptg); + if (attrPtg.isOptimizedIf() || attrPtg.isOptimizedChoose() || attrPtg.isGoto()) { + continue; + } + if (attrPtg.isSpace()) { + // POI currently doesn't render spaces in formulas + continue; + // but if it ever did, care must be taken: + // tAttrSpace comes *before* the operand it applies to, which may be consistent + // with how the formula text appears but is against the RPN ordering assumed here + } + if (attrPtg.isSemiVolatile()) { + // similar to tAttrSpace - RPN is violated + continue; + } + if (attrPtg.isSum()) { + String[] operands = getOperands(stack, attrPtg.getNumberOfOperands()); + stack.push(attrPtg.toFormulaString(operands)); + continue; + } + throw new RuntimeException("Unexpected tAttr: " + attrPtg.toString()); + } + + if (ptg instanceof WorkbookDependentFormula) { + WorkbookDependentFormula optg = (WorkbookDependentFormula) ptg; + stack.push(optg.toFormulaString(book)); + continue; + } + if (! (ptg instanceof OperationPtg)) { + stack.push(ptg.toFormulaString()); + continue; + } + + OperationPtg o = (OperationPtg) ptg; + String[] operands = getOperands(stack, o.getNumberOfOperands()); + stack.push(o.toFormulaString(operands)); + } + if(stack.isEmpty()) { + // inspection of the code above reveals that every stack.pop() is followed by a + // stack.push(). So this is either an internal error or impossible. + throw new IllegalStateException("Stack underflow"); + } + String result = stack.pop(); + if(!stack.isEmpty()) { + // Might be caused by some tokens like AttrPtg and Mem*Ptg, which really shouldn't + // put anything on the stack + throw new IllegalStateException("too much stuff left on the stack"); + } + return result; + } + + private static String[] getOperands(Stack<String> stack, int nOperands) { + String[] operands = new String[nOperands]; + + for (int j = nOperands-1; j >= 0; j--) { // reverse iteration because args were pushed in-order + if(stack.isEmpty()) { + String msg = "Too few arguments supplied to operation. Expected (" + nOperands + + ") operands but got (" + (nOperands - j - 1) + ")"; + throw new IllegalStateException(msg); + } + operands[j] = stack.pop(); + } + return operands; + } +} diff --git a/src/java/org/apache/poi/ss/formula/FormulaRenderingWorkbook.java b/src/java/org/apache/poi/ss/formula/FormulaRenderingWorkbook.java index c9b95f6b1c..b0dcb38512 100644 --- a/src/java/org/apache/poi/ss/formula/FormulaRenderingWorkbook.java +++ b/src/java/org/apache/poi/ss/formula/FormulaRenderingWorkbook.java @@ -1,40 +1,40 @@ -/* ====================================================================
- 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.formula;
-
-import org.apache.poi.hssf.record.formula.NamePtg;
-import org.apache.poi.hssf.record.formula.NameXPtg;
-import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalSheet;
-
-/**
- * Abstracts a workbook for the purpose of converting formula to text.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public interface FormulaRenderingWorkbook {
-
- /**
- * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook
- */
- ExternalSheet getExternalSheet(int externSheetIndex);
- String getSheetNameByExternSheet(int externSheetIndex);
- String resolveNameXText(NameXPtg nameXPtg);
- String getNameText(NamePtg namePtg);
-}
+/* ==================================================================== + 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.formula; + +import org.apache.poi.hssf.record.formula.NamePtg; +import org.apache.poi.hssf.record.formula.NameXPtg; +import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalSheet; + +/** + * Abstracts a workbook for the purpose of converting formula to text.<br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public interface FormulaRenderingWorkbook { + + /** + * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook + */ + ExternalSheet getExternalSheet(int externSheetIndex); + String getSheetNameByExternSheet(int externSheetIndex); + String resolveNameXText(NameXPtg nameXPtg); + String getNameText(NamePtg namePtg); +} diff --git a/src/java/org/apache/poi/ss/formula/FormulaType.java b/src/java/org/apache/poi/ss/formula/FormulaType.java index 3b47030d47..b770019907 100644 --- a/src/java/org/apache/poi/ss/formula/FormulaType.java +++ b/src/java/org/apache/poi/ss/formula/FormulaType.java @@ -1,40 +1,40 @@ -/* ====================================================================
- 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.formula;
-
-/**
- * Enumeration of various formula types.<br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public final class FormulaType {
- private FormulaType() {
- // no instances of this class
- }
- public static final int CELL = 0;
- public static final int SHARED = 1;
- public static final int ARRAY =2;
- public static final int CONDFORMAT = 3;
- public static final int NAMEDRANGE = 4;
- // this constant is currently very specific. The exact differences from general data
- // validation formulas or conditional format formulas is not known yet
- public static final int DATAVALIDATION_LIST = 5;
-
-}
+/* ==================================================================== + 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.formula; + +/** + * Enumeration of various formula types.<br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public final class FormulaType { + private FormulaType() { + // no instances of this class + } + public static final int CELL = 0; + public static final int SHARED = 1; + public static final int ARRAY =2; + public static final int CONDFORMAT = 3; + public static final int NAMEDRANGE = 4; + // this constant is currently very specific. The exact differences from general data + // validation formulas or conditional format formulas is not known yet + public static final int DATAVALIDATION_LIST = 5; + +} diff --git a/src/java/org/apache/poi/ss/formula/LazyRefEval.java b/src/java/org/apache/poi/ss/formula/LazyRefEval.java index f25e86fc40..69f0834f50 100644 --- a/src/java/org/apache/poi/ss/formula/LazyRefEval.java +++ b/src/java/org/apache/poi/ss/formula/LazyRefEval.java @@ -1,68 +1,68 @@ -/* ====================================================================
- 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.formula;
-
-import org.apache.poi.hssf.record.formula.AreaI;
-import org.apache.poi.hssf.record.formula.Ref3DPtg;
-import org.apache.poi.hssf.record.formula.RefPtg;
-import org.apache.poi.hssf.record.formula.AreaI.OffsetArea;
-import org.apache.poi.hssf.record.formula.eval.AreaEval;
-import org.apache.poi.hssf.record.formula.eval.RefEvalBase;
-import org.apache.poi.hssf.record.formula.eval.ValueEval;
-import org.apache.poi.hssf.util.CellReference;
-
-/**
-*
-* @author Josh Micich
-*/
-final class LazyRefEval extends RefEvalBase {
-
- private final SheetRefEvaluator _evaluator;
-
- public LazyRefEval(RefPtg ptg, SheetRefEvaluator sre) {
- super(ptg.getRow(), ptg.getColumn());
- _evaluator = sre;
- }
- public LazyRefEval(Ref3DPtg ptg, SheetRefEvaluator sre) {
- super(ptg.getRow(), ptg.getColumn());
- _evaluator = sre;
- }
-
- public ValueEval getInnerValueEval() {
- return _evaluator.getEvalForCell(getRow(), getColumn());
- }
-
- public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) {
-
- AreaI area = new OffsetArea(getRow(), getColumn(),
- relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
-
- return new LazyAreaEval(area, _evaluator);
- }
-
- public String toString() {
- CellReference cr = new CellReference(getRow(), getColumn());
- StringBuffer sb = new StringBuffer();
- sb.append(getClass().getName()).append("[");
- sb.append(_evaluator.getSheetName());
- sb.append('!');
- sb.append(cr.formatAsString());
- sb.append("]");
- return sb.toString();
- }
-}
+/* ==================================================================== + 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.formula; + +import org.apache.poi.hssf.record.formula.AreaI; +import org.apache.poi.hssf.record.formula.Ref3DPtg; +import org.apache.poi.hssf.record.formula.RefPtg; +import org.apache.poi.hssf.record.formula.AreaI.OffsetArea; +import org.apache.poi.hssf.record.formula.eval.AreaEval; +import org.apache.poi.hssf.record.formula.eval.RefEvalBase; +import org.apache.poi.hssf.record.formula.eval.ValueEval; +import org.apache.poi.hssf.util.CellReference; + +/** +* +* @author Josh Micich +*/ +final class LazyRefEval extends RefEvalBase { + + private final SheetRefEvaluator _evaluator; + + public LazyRefEval(RefPtg ptg, SheetRefEvaluator sre) { + super(ptg.getRow(), ptg.getColumn()); + _evaluator = sre; + } + public LazyRefEval(Ref3DPtg ptg, SheetRefEvaluator sre) { + super(ptg.getRow(), ptg.getColumn()); + _evaluator = sre; + } + + public ValueEval getInnerValueEval() { + return _evaluator.getEvalForCell(getRow(), getColumn()); + } + + public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { + + AreaI area = new OffsetArea(getRow(), getColumn(), + relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); + + return new LazyAreaEval(area, _evaluator); + } + + public String toString() { + CellReference cr = new CellReference(getRow(), getColumn()); + StringBuffer sb = new StringBuffer(); + sb.append(getClass().getName()).append("["); + sb.append(_evaluator.getSheetName()); + sb.append('!'); + sb.append(cr.formatAsString()); + sb.append("]"); + return sb.toString(); + } +} diff --git a/src/java/org/apache/poi/ss/formula/SheetRefEvaluator.java b/src/java/org/apache/poi/ss/formula/SheetRefEvaluator.java index bf636a4da3..b2a6ed123d 100644 --- a/src/java/org/apache/poi/ss/formula/SheetRefEvaluator.java +++ b/src/java/org/apache/poi/ss/formula/SheetRefEvaluator.java @@ -1,48 +1,48 @@ -/* ====================================================================
- 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.formula;
-
-import org.apache.poi.hssf.record.formula.eval.ValueEval;
-/**
- *
- *
- * @author Josh Micich
- */
-final class SheetRefEvaluator {
-
- private final WorkbookEvaluator _bookEvaluator;
- private final EvaluationTracker _tracker;
- private final EvaluationSheet _sheet;
- private final int _sheetIndex;
-
- public SheetRefEvaluator(WorkbookEvaluator bookEvaluator, EvaluationTracker tracker,
- EvaluationWorkbook _workbook, int sheetIndex) {
- _bookEvaluator = bookEvaluator;
- _tracker = tracker;
- _sheet = _workbook.getSheet(sheetIndex);
- _sheetIndex = sheetIndex;
- }
-
- public String getSheetName() {
- return _bookEvaluator.getSheetName(_sheetIndex);
- }
-
- public ValueEval getEvalForCell(int rowIndex, int columnIndex) {
- return _bookEvaluator.evaluateReference(_sheet, _sheetIndex, rowIndex, columnIndex, _tracker);
- }
-}
+/* ==================================================================== + 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.formula; + +import org.apache.poi.hssf.record.formula.eval.ValueEval; +/** + * + * + * @author Josh Micich + */ +final class SheetRefEvaluator { + + private final WorkbookEvaluator _bookEvaluator; + private final EvaluationTracker _tracker; + private final EvaluationSheet _sheet; + private final int _sheetIndex; + + public SheetRefEvaluator(WorkbookEvaluator bookEvaluator, EvaluationTracker tracker, + EvaluationWorkbook _workbook, int sheetIndex) { + _bookEvaluator = bookEvaluator; + _tracker = tracker; + _sheet = _workbook.getSheet(sheetIndex); + _sheetIndex = sheetIndex; + } + + public String getSheetName() { + return _bookEvaluator.getSheetName(_sheetIndex); + } + + public ValueEval getEvalForCell(int rowIndex, int columnIndex) { + return _bookEvaluator.evaluateReference(_sheet, _sheetIndex, rowIndex, columnIndex, _tracker); + } +} diff --git a/src/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java b/src/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java index 3dc2c525d5..4beaaa3b08 100644 --- a/src/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java +++ b/src/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java @@ -1,30 +1,30 @@ -/* ====================================================================
- 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.formula;
-
-/**
- * Should be implemented by any {@link org.apache.poi.hssf.record.formula.Ptg} subclass that needs a workbook to render its formula.
- * <br/>
- *
- * For POI internal use only
- *
- * @author Josh Micich
- */
-public interface WorkbookDependentFormula {
- String toFormulaString(FormulaRenderingWorkbook book);
-}
+/* ==================================================================== + 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.formula; + +/** + * Should be implemented by any {@link org.apache.poi.hssf.record.formula.Ptg} subclass that needs a workbook to render its formula. + * <br/> + * + * For POI internal use only + * + * @author Josh Micich + */ +public interface WorkbookDependentFormula { + String toFormulaString(FormulaRenderingWorkbook book); +} diff --git a/src/java/org/apache/poi/ss/formula/eval/NotImplementedException.java b/src/java/org/apache/poi/ss/formula/eval/NotImplementedException.java index 84480758ec..cad7f88582 100644 --- a/src/java/org/apache/poi/ss/formula/eval/NotImplementedException.java +++ b/src/java/org/apache/poi/ss/formula/eval/NotImplementedException.java @@ -1,36 +1,36 @@ -/* ====================================================================
- 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.formula.eval;
-
-import org.apache.poi.ss.usermodel.FormulaEvaluator;
-
-/**
- * An exception thrown by implementors of {@link FormulaEvaluator} when attempting to evaluate
- * a formula which requires features that POI does not (yet) support.
- *
- * @author Josh Micich
- */
-public final class NotImplementedException extends RuntimeException {
-
- public NotImplementedException(String message) {
- super(message);
- }
- public NotImplementedException(String message, NotImplementedException cause) {
- super(message, cause);
- }
-}
+/* ==================================================================== + 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.formula.eval; + +import org.apache.poi.ss.usermodel.FormulaEvaluator; + +/** + * An exception thrown by implementors of {@link FormulaEvaluator} when attempting to evaluate + * a formula which requires features that POI does not (yet) support. + * + * @author Josh Micich + */ +public final class NotImplementedException extends RuntimeException { + + public NotImplementedException(String message) { + super(message); + } + public NotImplementedException(String message, NotImplementedException cause) { + super(message, cause); + } +} diff --git a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java index 3563904b1a..73c6a7ddc6 100644 --- a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java +++ b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java @@ -1,132 +1,132 @@ -/* ====================================================================
- 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.formula.eval.forked;
-
-import org.apache.poi.hssf.record.formula.eval.BlankEval;
-import org.apache.poi.hssf.record.formula.eval.BoolEval;
-import org.apache.poi.hssf.record.formula.eval.ErrorEval;
-import org.apache.poi.hssf.record.formula.eval.NumberEval;
-import org.apache.poi.hssf.record.formula.eval.StringEval;
-import org.apache.poi.hssf.record.formula.eval.ValueEval;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.ss.formula.EvaluationCell;
-import org.apache.poi.ss.formula.EvaluationSheet;
-import org.apache.poi.ss.usermodel.Cell;
-
-/**
- * Represents a cell being used for forked evaluation that has had a value set different from the
- * corresponding cell in the shared master workbook.
- *
- * @author Josh Micich
- */
-final class ForkedEvaluationCell implements EvaluationCell {
-
- private final EvaluationSheet _sheet;
- /** corresponding cell from master workbook */
- private final EvaluationCell _masterCell;
- private boolean _booleanValue;
- private int _cellType;
- private int _errorValue;
- private double _numberValue;
- private String _stringValue;
-
- public ForkedEvaluationCell(ForkedEvaluationSheet sheet, EvaluationCell masterCell) {
- _sheet = sheet;
- _masterCell = masterCell;
- // start with value blank, but expect construction to be immediately
- setValue(BlankEval.INSTANCE); // followed by a proper call to setValue()
- }
-
- public Object getIdentityKey() {
- return _masterCell.getIdentityKey();
- }
-
- public void setValue(ValueEval value) {
- Class<? extends ValueEval> cls = value.getClass();
-
- if (cls == NumberEval.class) {
- _cellType = HSSFCell.CELL_TYPE_NUMERIC;
- _numberValue = ((NumberEval)value).getNumberValue();
- return;
- }
- if (cls == StringEval.class) {
- _cellType = HSSFCell.CELL_TYPE_STRING;
- _stringValue = ((StringEval)value).getStringValue();
- return;
- }
- if (cls == BoolEval.class) {
- _cellType = HSSFCell.CELL_TYPE_BOOLEAN;
- _booleanValue = ((BoolEval)value).getBooleanValue();
- return;
- }
- if (cls == ErrorEval.class) {
- _cellType = HSSFCell.CELL_TYPE_ERROR;
- _errorValue = ((ErrorEval)value).getErrorCode();
- return;
- }
- if (cls == BlankEval.class) {
- _cellType = HSSFCell.CELL_TYPE_BLANK;
- return;
- }
- throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")");
- }
- public void copyValue(Cell destCell) {
- switch (_cellType) {
- case Cell.CELL_TYPE_BLANK: destCell.setCellType(Cell.CELL_TYPE_BLANK); return;
- case Cell.CELL_TYPE_NUMERIC: destCell.setCellValue(_numberValue); return;
- case Cell.CELL_TYPE_BOOLEAN: destCell.setCellValue(_booleanValue); return;
- case Cell.CELL_TYPE_STRING: destCell.setCellValue(_stringValue); return;
- case Cell.CELL_TYPE_ERROR: destCell.setCellErrorValue((byte)_errorValue); return;
- }
- throw new IllegalStateException("Unexpected data type (" + _cellType + ")");
- }
-
- private void checkCellType(int expectedCellType) {
- if (_cellType != expectedCellType) {
- throw new RuntimeException("Wrong data type (" + _cellType + ")");
- }
- }
- public int getCellType() {
- return _cellType;
- }
- public boolean getBooleanCellValue() {
- checkCellType(HSSFCell.CELL_TYPE_BOOLEAN);
- return _booleanValue;
- }
- public int getErrorCellValue() {
- checkCellType(HSSFCell.CELL_TYPE_ERROR);
- return _errorValue;
- }
- public double getNumericCellValue() {
- checkCellType(HSSFCell.CELL_TYPE_NUMERIC);
- return _numberValue;
- }
- public String getStringCellValue() {
- checkCellType(HSSFCell.CELL_TYPE_STRING);
- return _stringValue;
- }
- public EvaluationSheet getSheet() {
- return _sheet;
- }
- public int getRowIndex() {
- return _masterCell.getRowIndex();
- }
- public int getColumnIndex() {
- return _masterCell.getColumnIndex();
- }
-}
+/* ==================================================================== + 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.formula.eval.forked; + +import org.apache.poi.hssf.record.formula.eval.BlankEval; +import org.apache.poi.hssf.record.formula.eval.BoolEval; +import org.apache.poi.hssf.record.formula.eval.ErrorEval; +import org.apache.poi.hssf.record.formula.eval.NumberEval; +import org.apache.poi.hssf.record.formula.eval.StringEval; +import org.apache.poi.hssf.record.formula.eval.ValueEval; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.ss.formula.EvaluationCell; +import org.apache.poi.ss.formula.EvaluationSheet; +import org.apache.poi.ss.usermodel.Cell; + +/** + * Represents a cell being used for forked evaluation that has had a value set different from the + * corresponding cell in the shared master workbook. + * + * @author Josh Micich + */ +final class ForkedEvaluationCell implements EvaluationCell { + + private final EvaluationSheet _sheet; + /** corresponding cell from master workbook */ + private final EvaluationCell _masterCell; + private boolean _booleanValue; + private int _cellType; + private int _errorValue; + private double _numberValue; + private String _stringValue; + + public ForkedEvaluationCell(ForkedEvaluationSheet sheet, EvaluationCell masterCell) { + _sheet = sheet; + _masterCell = masterCell; + // start with value blank, but expect construction to be immediately + setValue(BlankEval.INSTANCE); // followed by a proper call to setValue() + } + + public Object getIdentityKey() { + return _masterCell.getIdentityKey(); + } + + public void setValue(ValueEval value) { + Class<? extends ValueEval> cls = value.getClass(); + + if (cls == NumberEval.class) { + _cellType = HSSFCell.CELL_TYPE_NUMERIC; + _numberValue = ((NumberEval)value).getNumberValue(); + return; + } + if (cls == StringEval.class) { + _cellType = HSSFCell.CELL_TYPE_STRING; + _stringValue = ((StringEval)value).getStringValue(); + return; + } + if (cls == BoolEval.class) { + _cellType = HSSFCell.CELL_TYPE_BOOLEAN; + _booleanValue = ((BoolEval)value).getBooleanValue(); + return; + } + if (cls == ErrorEval.class) { + _cellType = HSSFCell.CELL_TYPE_ERROR; + _errorValue = ((ErrorEval)value).getErrorCode(); + return; + } + if (cls == BlankEval.class) { + _cellType = HSSFCell.CELL_TYPE_BLANK; + return; + } + throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")"); + } + public void copyValue(Cell destCell) { + switch (_cellType) { + case Cell.CELL_TYPE_BLANK: destCell.setCellType(Cell.CELL_TYPE_BLANK); return; + case Cell.CELL_TYPE_NUMERIC: destCell.setCellValue(_numberValue); return; + case Cell.CELL_TYPE_BOOLEAN: destCell.setCellValue(_booleanValue); return; + case Cell.CELL_TYPE_STRING: destCell.setCellValue(_stringValue); return; + case Cell.CELL_TYPE_ERROR: destCell.setCellErrorValue((byte)_errorValue); return; + } + throw new IllegalStateException("Unexpected data type (" + _cellType + ")"); + } + + private void checkCellType(int expectedCellType) { + if (_cellType != expectedCellType) { + throw new RuntimeException("Wrong data type (" + _cellType + ")"); + } + } + public int getCellType() { + return _cellType; + } + public boolean getBooleanCellValue() { + checkCellType(HSSFCell.CELL_TYPE_BOOLEAN); + return _booleanValue; + } + public int getErrorCellValue() { + checkCellType(HSSFCell.CELL_TYPE_ERROR); + return _errorValue; + } + public double getNumericCellValue() { + checkCellType(HSSFCell.CELL_TYPE_NUMERIC); + return _numberValue; + } + public String getStringCellValue() { + checkCellType(HSSFCell.CELL_TYPE_STRING); + return _stringValue; + } + public EvaluationSheet getSheet() { + return _sheet; + } + public int getRowIndex() { + return _masterCell.getRowIndex(); + } + public int getColumnIndex() { + return _masterCell.getColumnIndex(); + } +} diff --git a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationSheet.java b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationSheet.java index 837ba932e4..c36232a1d8 100644 --- a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationSheet.java +++ b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationSheet.java @@ -1,129 +1,129 @@ -/* ====================================================================
- 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.formula.eval.forked;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.poi.ss.formula.EvaluationCell;
-import org.apache.poi.ss.formula.EvaluationSheet;
-import org.apache.poi.ss.formula.EvaluationWorkbook;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-
-/**
- * Represents a sheet being used for forked evaluation. Initially, objects of this class contain
- * only the cells from the master workbook. By calling {@link #getOrCreateUpdatableCell(int, int)},
- * the master cell object is logically replaced with a {@link ForkedEvaluationCell} instance, which
- * will be used in all subsequent evaluations.
- *
- * @author Josh Micich
- */
-final class ForkedEvaluationSheet implements EvaluationSheet {
-
- private final EvaluationSheet _masterSheet;
- /**
- * Only cells which have been split are put in this map. (This has been done to conserve memory).
- */
- private final Map<RowColKey, ForkedEvaluationCell> _sharedCellsByRowCol;
-
- public ForkedEvaluationSheet(EvaluationSheet masterSheet) {
- _masterSheet = masterSheet;
- _sharedCellsByRowCol = new HashMap<RowColKey, ForkedEvaluationCell>();
- }
-
- public EvaluationCell getCell(int rowIndex, int columnIndex) {
- RowColKey key = new RowColKey(rowIndex, columnIndex);
-
- ForkedEvaluationCell result = _sharedCellsByRowCol.get(key);
- if (result == null) {
- return _masterSheet.getCell(rowIndex, columnIndex);
- }
- return result;
- }
-
- public ForkedEvaluationCell getOrCreateUpdatableCell(int rowIndex, int columnIndex) {
- RowColKey key = new RowColKey(rowIndex, columnIndex);
-
- ForkedEvaluationCell result = _sharedCellsByRowCol.get(key);
- if (result == null) {
- EvaluationCell mcell = _masterSheet.getCell(rowIndex, columnIndex);
- result = new ForkedEvaluationCell(this, mcell);
- _sharedCellsByRowCol.put(key, result);
- }
- return result;
- }
-
- public void copyUpdatedCells(Sheet sheet) {
- RowColKey[] keys = new RowColKey[_sharedCellsByRowCol.size()];
- _sharedCellsByRowCol.keySet().toArray(keys);
- Arrays.sort(keys);
- for (int i = 0; i < keys.length; i++) {
- RowColKey key = keys[i];
- Row row = sheet.getRow(key.getRowIndex());
- if (row == null) {
- row = sheet.createRow(key.getRowIndex());
- }
- Cell destCell = row.getCell(key.getColumnIndex());
- if (destCell == null) {
- destCell = row.createCell(key.getColumnIndex());
- }
-
- ForkedEvaluationCell srcCell = _sharedCellsByRowCol.get(key);
- srcCell.copyValue(destCell);
- }
- }
-
- public int getSheetIndex(EvaluationWorkbook mewb) {
- return mewb.getSheetIndex(_masterSheet);
- }
-
- private static final class RowColKey implements Comparable<RowColKey>{
- private final int _rowIndex;
- private final int _columnIndex;
-
- public RowColKey(int rowIndex, int columnIndex) {
- _rowIndex = rowIndex;
- _columnIndex = columnIndex;
- }
- @Override
- public boolean equals(Object obj) {
- RowColKey other = (RowColKey) obj;
- return _rowIndex == other._rowIndex && _columnIndex == other._columnIndex;
- }
- @Override
- public int hashCode() {
- return _rowIndex ^ _columnIndex;
- }
- public int compareTo(RowColKey o) {
- int cmp = _rowIndex - o._rowIndex;
- if (cmp != 0) {
- return cmp;
- }
- return _columnIndex - o._columnIndex;
- }
- public int getRowIndex() {
- return _rowIndex;
- }
- public int getColumnIndex() {
- return _columnIndex;
- }
- }
-}
+/* ==================================================================== + 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.formula.eval.forked; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.apache.poi.ss.formula.EvaluationCell; +import org.apache.poi.ss.formula.EvaluationSheet; +import org.apache.poi.ss.formula.EvaluationWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; + +/** + * Represents a sheet being used for forked evaluation. Initially, objects of this class contain + * only the cells from the master workbook. By calling {@link #getOrCreateUpdatableCell(int, int)}, + * the master cell object is logically replaced with a {@link ForkedEvaluationCell} instance, which + * will be used in all subsequent evaluations. + * + * @author Josh Micich + */ +final class ForkedEvaluationSheet implements EvaluationSheet { + + private final EvaluationSheet _masterSheet; + /** + * Only cells which have been split are put in this map. (This has been done to conserve memory). + */ + private final Map<RowColKey, ForkedEvaluationCell> _sharedCellsByRowCol; + + public ForkedEvaluationSheet(EvaluationSheet masterSheet) { + _masterSheet = masterSheet; + _sharedCellsByRowCol = new HashMap<RowColKey, ForkedEvaluationCell>(); + } + + public EvaluationCell getCell(int rowIndex, int columnIndex) { + RowColKey key = new RowColKey(rowIndex, columnIndex); + + ForkedEvaluationCell result = _sharedCellsByRowCol.get(key); + if (result == null) { + return _masterSheet.getCell(rowIndex, columnIndex); + } + return result; + } + + public ForkedEvaluationCell getOrCreateUpdatableCell(int rowIndex, int columnIndex) { + RowColKey key = new RowColKey(rowIndex, columnIndex); + + ForkedEvaluationCell result = _sharedCellsByRowCol.get(key); + if (result == null) { + EvaluationCell mcell = _masterSheet.getCell(rowIndex, columnIndex); + result = new ForkedEvaluationCell(this, mcell); + _sharedCellsByRowCol.put(key, result); + } + return result; + } + + public void copyUpdatedCells(Sheet sheet) { + RowColKey[] keys = new RowColKey[_sharedCellsByRowCol.size()]; + _sharedCellsByRowCol.keySet().toArray(keys); + Arrays.sort(keys); + for (int i = 0; i < keys.length; i++) { + RowColKey key = keys[i]; + Row row = sheet.getRow(key.getRowIndex()); + if (row == null) { + row = sheet.createRow(key.getRowIndex()); + } + Cell destCell = row.getCell(key.getColumnIndex()); + if (destCell == null) { + destCell = row.createCell(key.getColumnIndex()); + } + + ForkedEvaluationCell srcCell = _sharedCellsByRowCol.get(key); + srcCell.copyValue(destCell); + } + } + + public int getSheetIndex(EvaluationWorkbook mewb) { + return mewb.getSheetIndex(_masterSheet); + } + + private static final class RowColKey implements Comparable<RowColKey>{ + private final int _rowIndex; + private final int _columnIndex; + + public RowColKey(int rowIndex, int columnIndex) { + _rowIndex = rowIndex; + _columnIndex = columnIndex; + } + @Override + public boolean equals(Object obj) { + RowColKey other = (RowColKey) obj; + return _rowIndex == other._rowIndex && _columnIndex == other._columnIndex; + } + @Override + public int hashCode() { + return _rowIndex ^ _columnIndex; + } + public int compareTo(RowColKey o) { + int cmp = _rowIndex - o._rowIndex; + if (cmp != 0) { + return cmp; + } + return _columnIndex - o._columnIndex; + } + public int getRowIndex() { + return _rowIndex; + } + public int getColumnIndex() { + return _columnIndex; + } + } +} diff --git a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationWorkbook.java b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationWorkbook.java index d7e158f6ff..08c7841197 100644 --- a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationWorkbook.java +++ b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationWorkbook.java @@ -1,144 +1,144 @@ -/* ====================================================================
- 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.formula.eval.forked;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.poi.hssf.record.formula.NamePtg;
-import org.apache.poi.hssf.record.formula.NameXPtg;
-import org.apache.poi.hssf.record.formula.Ptg;
-import org.apache.poi.ss.formula.EvaluationCell;
-import org.apache.poi.ss.formula.EvaluationName;
-import org.apache.poi.ss.formula.EvaluationSheet;
-import org.apache.poi.ss.formula.EvaluationWorkbook;
-import org.apache.poi.ss.usermodel.Workbook;
-
-/**
- * Represents a workbook being used for forked evaluation. Most operations are delegated to the
- * shared master workbook, except those that potentially involve cell values that may have been
- * updated after a call to {@link #getOrCreateUpdatableCell(String, int, int)}.
- *
- * @author Josh Micich
- */
-final class ForkedEvaluationWorkbook implements EvaluationWorkbook {
-
- private final EvaluationWorkbook _masterBook;
- private final Map<String, ForkedEvaluationSheet> _sharedSheetsByName;
-
- public ForkedEvaluationWorkbook(EvaluationWorkbook master) {
- _masterBook = master;
- _sharedSheetsByName = new HashMap<String, ForkedEvaluationSheet>();
- }
-
- public ForkedEvaluationCell getOrCreateUpdatableCell(String sheetName, int rowIndex,
- int columnIndex) {
- ForkedEvaluationSheet sheet = getSharedSheet(sheetName);
- return sheet.getOrCreateUpdatableCell(rowIndex, columnIndex);
- }
-
- public EvaluationCell getEvaluationCell(String sheetName, int rowIndex, int columnIndex) {
- ForkedEvaluationSheet sheet = getSharedSheet(sheetName);
- return sheet.getCell(rowIndex, columnIndex);
- }
-
- private ForkedEvaluationSheet getSharedSheet(String sheetName) {
- ForkedEvaluationSheet result = _sharedSheetsByName.get(sheetName);
- if (result == null) {
- result = new ForkedEvaluationSheet(_masterBook.getSheet(_masterBook
- .getSheetIndex(sheetName)));
- _sharedSheetsByName.put(sheetName, result);
- }
- return result;
- }
-
- public void copyUpdatedCells(Workbook workbook) {
- String[] sheetNames = new String[_sharedSheetsByName.size()];
- _sharedSheetsByName.keySet().toArray(sheetNames);
- OrderedSheet[] oss = new OrderedSheet[sheetNames.length];
- for (int i = 0; i < sheetNames.length; i++) {
- String sheetName = sheetNames[i];
- oss[i] = new OrderedSheet(sheetName, _masterBook.getSheetIndex(sheetName));
- }
- for (int i = 0; i < oss.length; i++) {
- String sheetName = oss[i].getSheetName();
- ForkedEvaluationSheet sheet = _sharedSheetsByName.get(sheetName);
- sheet.copyUpdatedCells(workbook.getSheet(sheetName));
- }
- }
-
- public int convertFromExternSheetIndex(int externSheetIndex) {
- return _masterBook.convertFromExternSheetIndex(externSheetIndex);
- }
-
- public ExternalSheet getExternalSheet(int externSheetIndex) {
- return _masterBook.getExternalSheet(externSheetIndex);
- }
-
- public Ptg[] getFormulaTokens(EvaluationCell cell) {
- if (cell instanceof ForkedEvaluationCell) {
- // doesn't happen yet because formulas cannot be modified from the master workbook
- throw new RuntimeException("Updated formulas not supported yet");
- }
- return _masterBook.getFormulaTokens(cell);
- }
-
- public EvaluationName getName(NamePtg namePtg) {
- return _masterBook.getName(namePtg);
- }
-
- public EvaluationSheet getSheet(int sheetIndex) {
- return getSharedSheet(getSheetName(sheetIndex));
- }
-
- public int getSheetIndex(EvaluationSheet sheet) {
- if (sheet instanceof ForkedEvaluationSheet) {
- ForkedEvaluationSheet mes = (ForkedEvaluationSheet) sheet;
- return mes.getSheetIndex(_masterBook);
- }
- return _masterBook.getSheetIndex(sheet);
- }
-
- public int getSheetIndex(String sheetName) {
- return _masterBook.getSheetIndex(sheetName);
- }
-
- public String getSheetName(int sheetIndex) {
- return _masterBook.getSheetName(sheetIndex);
- }
-
- public String resolveNameXText(NameXPtg ptg) {
- return _masterBook.resolveNameXText(ptg);
- }
-
- private static final class OrderedSheet implements Comparable<OrderedSheet> {
- private final String _sheetName;
- private final int _index;
-
- public OrderedSheet(String sheetName, int index) {
- _sheetName = sheetName;
- _index = index;
- }
- public String getSheetName() {
- return _sheetName;
- }
- public int compareTo(OrderedSheet o) {
- return _index - o._index;
- }
- }
-}
+/* ==================================================================== + 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.formula.eval.forked; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.poi.hssf.record.formula.NamePtg; +import org.apache.poi.hssf.record.formula.NameXPtg; +import org.apache.poi.hssf.record.formula.Ptg; +import org.apache.poi.ss.formula.EvaluationCell; +import org.apache.poi.ss.formula.EvaluationName; +import org.apache.poi.ss.formula.EvaluationSheet; +import org.apache.poi.ss.formula.EvaluationWorkbook; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * Represents a workbook being used for forked evaluation. Most operations are delegated to the + * shared master workbook, except those that potentially involve cell values that may have been + * updated after a call to {@link #getOrCreateUpdatableCell(String, int, int)}. + * + * @author Josh Micich + */ +final class ForkedEvaluationWorkbook implements EvaluationWorkbook { + + private final EvaluationWorkbook _masterBook; + private final Map<String, ForkedEvaluationSheet> _sharedSheetsByName; + + public ForkedEvaluationWorkbook(EvaluationWorkbook master) { + _masterBook = master; + _sharedSheetsByName = new HashMap<String, ForkedEvaluationSheet>(); + } + + public ForkedEvaluationCell getOrCreateUpdatableCell(String sheetName, int rowIndex, + int columnIndex) { + ForkedEvaluationSheet sheet = getSharedSheet(sheetName); + return sheet.getOrCreateUpdatableCell(rowIndex, columnIndex); + } + + public EvaluationCell getEvaluationCell(String sheetName, int rowIndex, int columnIndex) { + ForkedEvaluationSheet sheet = getSharedSheet(sheetName); + return sheet.getCell(rowIndex, columnIndex); + } + + private ForkedEvaluationSheet getSharedSheet(String sheetName) { + ForkedEvaluationSheet result = _sharedSheetsByName.get(sheetName); + if (result == null) { + result = new ForkedEvaluationSheet(_masterBook.getSheet(_masterBook + .getSheetIndex(sheetName))); + _sharedSheetsByName.put(sheetName, result); + } + return result; + } + + public void copyUpdatedCells(Workbook workbook) { + String[] sheetNames = new String[_sharedSheetsByName.size()]; + _sharedSheetsByName.keySet().toArray(sheetNames); + OrderedSheet[] oss = new OrderedSheet[sheetNames.length]; + for (int i = 0; i < sheetNames.length; i++) { + String sheetName = sheetNames[i]; + oss[i] = new OrderedSheet(sheetName, _masterBook.getSheetIndex(sheetName)); + } + for (int i = 0; i < oss.length; i++) { + String sheetName = oss[i].getSheetName(); + ForkedEvaluationSheet sheet = _sharedSheetsByName.get(sheetName); + sheet.copyUpdatedCells(workbook.getSheet(sheetName)); + } + } + + public int convertFromExternSheetIndex(int externSheetIndex) { + return _masterBook.convertFromExternSheetIndex(externSheetIndex); + } + + public ExternalSheet getExternalSheet(int externSheetIndex) { + return _masterBook.getExternalSheet(externSheetIndex); + } + + public Ptg[] getFormulaTokens(EvaluationCell cell) { + if (cell instanceof ForkedEvaluationCell) { + // doesn't happen yet because formulas cannot be modified from the master workbook + throw new RuntimeException("Updated formulas not supported yet"); + } + return _masterBook.getFormulaTokens(cell); + } + + public EvaluationName getName(NamePtg namePtg) { + return _masterBook.getName(namePtg); + } + + public EvaluationSheet getSheet(int sheetIndex) { + return getSharedSheet(getSheetName(sheetIndex)); + } + + public int getSheetIndex(EvaluationSheet sheet) { + if (sheet instanceof ForkedEvaluationSheet) { + ForkedEvaluationSheet mes = (ForkedEvaluationSheet) sheet; + return mes.getSheetIndex(_masterBook); + } + return _masterBook.getSheetIndex(sheet); + } + + public int getSheetIndex(String sheetName) { + return _masterBook.getSheetIndex(sheetName); + } + + public String getSheetName(int sheetIndex) { + return _masterBook.getSheetName(sheetIndex); + } + + public String resolveNameXText(NameXPtg ptg) { + return _masterBook.resolveNameXText(ptg); + } + + private static final class OrderedSheet implements Comparable<OrderedSheet> { + private final String _sheetName; + private final int _index; + + public OrderedSheet(String sheetName, int index) { + _sheetName = sheetName; + _index = index; + } + public String getSheetName() { + return _sheetName; + } + public int compareTo(OrderedSheet o) { + return _index - o._index; + } + } +} diff --git a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java index 6a1e1b1505..e89d2a6104 100644 --- a/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java +++ b/src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java @@ -1,133 +1,133 @@ -/* ====================================================================
- 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.formula.eval.forked;
-
-import org.apache.poi.hssf.record.formula.eval.BoolEval;
-import org.apache.poi.hssf.record.formula.eval.ErrorEval;
-import org.apache.poi.hssf.record.formula.eval.NumberEval;
-import org.apache.poi.hssf.record.formula.eval.StringEval;
-import org.apache.poi.hssf.record.formula.eval.ValueEval;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;
-import org.apache.poi.ss.formula.EvaluationCell;
-import org.apache.poi.ss.formula.EvaluationWorkbook;
-import org.apache.poi.ss.formula.IStabilityClassifier;
-import org.apache.poi.ss.formula.WorkbookEvaluator;
-import org.apache.poi.ss.usermodel.Workbook;
-
-/**
- * An alternative workbook evaluator that saves memory in situations where a single workbook is
- * concurrently and independently evaluated many times. With standard formula evaluation, around
- * 90% of memory consumption is due to loading of the {@link HSSFWorkbook} or {@link org.apache.poi.xssf.usermodel.XSSFWorkbook}.
- * This class enables a 'master workbook' to be loaded just once and shared between many evaluation
- * clients. Each evaluation client creates its own {@link ForkedEvaluator} and can set cell values
- * that will be used for local evaluations (and don't disturb evaluations on other evaluators).
- *
- * @author Josh Micich
- */
-public final class ForkedEvaluator {
-
- private WorkbookEvaluator _evaluator;
- private ForkedEvaluationWorkbook _sewb;
-
- private ForkedEvaluator(EvaluationWorkbook masterWorkbook, IStabilityClassifier stabilityClassifier) {
- _sewb = new ForkedEvaluationWorkbook(masterWorkbook);
- _evaluator = new WorkbookEvaluator(_sewb, stabilityClassifier);
- }
- private static EvaluationWorkbook createEvaluationWorkbook(Workbook wb) {
- if (wb instanceof HSSFWorkbook) {
- return HSSFEvaluationWorkbook.create((HSSFWorkbook) wb);
- }
-// TODO rearrange POI build to allow this
-// if (wb instanceof XSSFWorkbook) {
-// return XSSFEvaluationWorkbook.create((XSSFWorkbook) wb);
-// }
- throw new IllegalArgumentException("Unexpected workbook type (" + wb.getClass().getName() + ")");
- }
- public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier) {
- return new ForkedEvaluator(createEvaluationWorkbook(wb), stabilityClassifier);
- }
-
- /**
- * Sets the specified cell to the supplied <tt>value</tt>
- * @param sheetName the name of the sheet containing the cell
- * @param rowIndex zero based
- * @param columnIndex zero based
- */
- public void updateCell(String sheetName, int rowIndex, int columnIndex, ValueEval value) {
-
- ForkedEvaluationCell cell = _sewb.getOrCreateUpdatableCell(sheetName, rowIndex, columnIndex);
- cell.setValue(value);
- _evaluator.notifyUpdateCell(cell);
- }
- /**
- * Copies the values of all updated cells (modified by calls to {@link
- * #updateCell(String, int, int, ValueEval)}) to the supplied <tt>workbook</tt>.<br/>
- * Typically, the supplied <tt>workbook</tt> is a writable copy of the 'master workbook',
- * but at the very least it must contain sheets with the same names.
- */
- public void copyUpdatedCells(Workbook workbook) {
- _sewb.copyUpdatedCells(workbook);
- }
-
- /**
- * 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 may be <code>null</code> signifying that the cell is not present (or blank)
- * @return <code>null</code> if the supplied cell is <code>null</code> or blank
- */
- public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) {
- EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex);
-
- switch (cell.getCellType()) {
- case HSSFCell.CELL_TYPE_BOOLEAN:
- return BoolEval.valueOf(cell.getBooleanCellValue());
- case HSSFCell.CELL_TYPE_ERROR:
- return ErrorEval.valueOf(cell.getErrorCellValue());
- case HSSFCell.CELL_TYPE_FORMULA:
- return _evaluator.evaluate(cell);
- case HSSFCell.CELL_TYPE_NUMERIC:
- return new NumberEval(cell.getNumericCellValue());
- case HSSFCell.CELL_TYPE_STRING:
- return new StringEval(cell.getStringCellValue());
- case HSSFCell.CELL_TYPE_BLANK:
- return null;
- }
- throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")");
- }
- /**
- * Coordinates several formula evaluators together so that formulas that involve external
- * references can be evaluated.
- * @param workbookNames the simple file names used to identify the workbooks in formulas
- * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")
- * @param evaluators all evaluators for the full set of workbooks required by the formulas.
- */
- public static void setupEnvironment(String[] workbookNames, ForkedEvaluator[] evaluators) {
- WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];
- for (int i = 0; i < wbEvals.length; i++) {
- wbEvals[i] = evaluators[i]._evaluator;
- }
- CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
- }
-}
+/* ==================================================================== + 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.formula.eval.forked; + +import org.apache.poi.hssf.record.formula.eval.BoolEval; +import org.apache.poi.hssf.record.formula.eval.ErrorEval; +import org.apache.poi.hssf.record.formula.eval.NumberEval; +import org.apache.poi.hssf.record.formula.eval.StringEval; +import org.apache.poi.hssf.record.formula.eval.ValueEval; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment; +import org.apache.poi.ss.formula.EvaluationCell; +import org.apache.poi.ss.formula.EvaluationWorkbook; +import org.apache.poi.ss.formula.IStabilityClassifier; +import org.apache.poi.ss.formula.WorkbookEvaluator; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * An alternative workbook evaluator that saves memory in situations where a single workbook is + * concurrently and independently evaluated many times. With standard formula evaluation, around + * 90% of memory consumption is due to loading of the {@link HSSFWorkbook} or {@link org.apache.poi.xssf.usermodel.XSSFWorkbook}. + * This class enables a 'master workbook' to be loaded just once and shared between many evaluation + * clients. Each evaluation client creates its own {@link ForkedEvaluator} and can set cell values + * that will be used for local evaluations (and don't disturb evaluations on other evaluators). + * + * @author Josh Micich + */ +public final class ForkedEvaluator { + + private WorkbookEvaluator _evaluator; + private ForkedEvaluationWorkbook _sewb; + + private ForkedEvaluator(EvaluationWorkbook masterWorkbook, IStabilityClassifier stabilityClassifier) { + _sewb = new ForkedEvaluationWorkbook(masterWorkbook); + _evaluator = new WorkbookEvaluator(_sewb, stabilityClassifier); + } + private static EvaluationWorkbook createEvaluationWorkbook(Workbook wb) { + if (wb instanceof HSSFWorkbook) { + return HSSFEvaluationWorkbook.create((HSSFWorkbook) wb); + } +// TODO rearrange POI build to allow this +// if (wb instanceof XSSFWorkbook) { +// return XSSFEvaluationWorkbook.create((XSSFWorkbook) wb); +// } + throw new IllegalArgumentException("Unexpected workbook type (" + wb.getClass().getName() + ")"); + } + public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier) { + return new ForkedEvaluator(createEvaluationWorkbook(wb), stabilityClassifier); + } + + /** + * Sets the specified cell to the supplied <tt>value</tt> + * @param sheetName the name of the sheet containing the cell + * @param rowIndex zero based + * @param columnIndex zero based + */ + public void updateCell(String sheetName, int rowIndex, int columnIndex, ValueEval value) { + + ForkedEvaluationCell cell = _sewb.getOrCreateUpdatableCell(sheetName, rowIndex, columnIndex); + cell.setValue(value); + _evaluator.notifyUpdateCell(cell); + } + /** + * Copies the values of all updated cells (modified by calls to {@link + * #updateCell(String, int, int, ValueEval)}) to the supplied <tt>workbook</tt>.<br/> + * Typically, the supplied <tt>workbook</tt> is a writable copy of the 'master workbook', + * but at the very least it must contain sheets with the same names. + */ + public void copyUpdatedCells(Workbook workbook) { + _sewb.copyUpdatedCells(workbook); + } + + /** + * 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 may be <code>null</code> signifying that the cell is not present (or blank) + * @return <code>null</code> if the supplied cell is <code>null</code> or blank + */ + public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) { + EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex); + + switch (cell.getCellType()) { + case HSSFCell.CELL_TYPE_BOOLEAN: + return BoolEval.valueOf(cell.getBooleanCellValue()); + case HSSFCell.CELL_TYPE_ERROR: + return ErrorEval.valueOf(cell.getErrorCellValue()); + case HSSFCell.CELL_TYPE_FORMULA: + return _evaluator.evaluate(cell); + case HSSFCell.CELL_TYPE_NUMERIC: + return new NumberEval(cell.getNumericCellValue()); + case HSSFCell.CELL_TYPE_STRING: + return new StringEval(cell.getStringCellValue()); + case HSSFCell.CELL_TYPE_BLANK: + return null; + } + throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")"); + } + /** + * Coordinates several formula evaluators together so that formulas that involve external + * references can be evaluated. + * @param workbookNames the simple file names used to identify the workbooks in formulas + * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1") + * @param evaluators all evaluators for the full set of workbooks required by the formulas. + */ + public static void setupEnvironment(String[] workbookNames, ForkedEvaluator[] evaluators) { + WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length]; + for (int i = 0; i < wbEvals.length; i++) { + wbEvals[i] = evaluators[i]._evaluator; + } + CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals); + } +} diff --git a/src/java/org/apache/poi/ss/usermodel/CellValue.java b/src/java/org/apache/poi/ss/usermodel/CellValue.java index 705f557101..664f100562 100644 --- a/src/java/org/apache/poi/ss/usermodel/CellValue.java +++ b/src/java/org/apache/poi/ss/usermodel/CellValue.java @@ -1,114 +1,114 @@ -/* ====================================================================
- 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.formula.eval.ErrorEval;
-import org.apache.poi.ss.usermodel.Cell;
-
-/**
- * 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.
- * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
- */
-public final class CellValue {
- public static final CellValue TRUE = new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, true, null, 0);
- public static final CellValue FALSE= new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, false, null, 0);
-
- private final int _cellType;
- private final double _numberValue;
- private final boolean _booleanValue;
- private final String _textValue;
- private final int _errorCode;
-
- private CellValue(int cellType, double numberValue, boolean booleanValue,
- String textValue, int errorCode) {
- _cellType = cellType;
- _numberValue = numberValue;
- _booleanValue = booleanValue;
- _textValue = textValue;
- _errorCode = errorCode;
- }
-
-
- public CellValue(double numberValue) {
- this(Cell.CELL_TYPE_NUMERIC, numberValue, false, null, 0);
- }
- public static CellValue valueOf(boolean booleanValue) {
- return booleanValue ? TRUE : FALSE;
- }
- public CellValue(String stringValue) {
- this(Cell.CELL_TYPE_STRING, 0.0, false, stringValue, 0);
- }
- public static CellValue getError(int errorCode) {
- return new CellValue(Cell.CELL_TYPE_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 Returns the cellType.
- */
- public int getCellType() {
- return _cellType;
- }
- /**
- * @return Returns the errorValue.
- */
- public byte getErrorValue() {
- return (byte) _errorCode;
- }
- public String toString() {
- StringBuffer sb = new StringBuffer(64);
- sb.append(getClass().getName()).append(" [");
- sb.append(formatAsString());
- sb.append("]");
- return sb.toString();
- }
-
- public String formatAsString() {
- switch (_cellType) {
- case Cell.CELL_TYPE_NUMERIC:
- return String.valueOf(_numberValue);
- case Cell.CELL_TYPE_STRING:
- return '"' + _textValue + '"';
- case Cell.CELL_TYPE_BOOLEAN:
- return _booleanValue ? "TRUE" : "FALSE";
- case Cell.CELL_TYPE_ERROR:
- return ErrorEval.getText(_errorCode);
- }
- return "<error unexpected cell type " + _cellType + ">";
- }
-}
+/* ==================================================================== + 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.formula.eval.ErrorEval; +import org.apache.poi.ss.usermodel.Cell; + +/** + * 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. + * @author Amol S. Deshmukh < amolweb at ya hoo dot com > + */ +public final class CellValue { + public static final CellValue TRUE = new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, true, null, 0); + public static final CellValue FALSE= new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, false, null, 0); + + private final int _cellType; + private final double _numberValue; + private final boolean _booleanValue; + private final String _textValue; + private final int _errorCode; + + private CellValue(int cellType, double numberValue, boolean booleanValue, + String textValue, int errorCode) { + _cellType = cellType; + _numberValue = numberValue; + _booleanValue = booleanValue; + _textValue = textValue; + _errorCode = errorCode; + } + + + public CellValue(double numberValue) { + this(Cell.CELL_TYPE_NUMERIC, numberValue, false, null, 0); + } + public static CellValue valueOf(boolean booleanValue) { + return booleanValue ? TRUE : FALSE; + } + public CellValue(String stringValue) { + this(Cell.CELL_TYPE_STRING, 0.0, false, stringValue, 0); + } + public static CellValue getError(int errorCode) { + return new CellValue(Cell.CELL_TYPE_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 Returns the cellType. + */ + public int getCellType() { + return _cellType; + } + /** + * @return Returns the errorValue. + */ + public byte getErrorValue() { + return (byte) _errorCode; + } + public String toString() { + StringBuffer sb = new StringBuffer(64); + sb.append(getClass().getName()).append(" ["); + sb.append(formatAsString()); + sb.append("]"); + return sb.toString(); + } + + public String formatAsString() { + switch (_cellType) { + case Cell.CELL_TYPE_NUMERIC: + return String.valueOf(_numberValue); + case Cell.CELL_TYPE_STRING: + return '"' + _textValue + '"'; + case Cell.CELL_TYPE_BOOLEAN: + return _booleanValue ? "TRUE" : "FALSE"; + case Cell.CELL_TYPE_ERROR: + return ErrorEval.getText(_errorCode); + } + return "<error unexpected cell type " + _cellType + ">"; + } +} diff --git a/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java b/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java index 6a51a7288c..a4e66635ca 100755 --- a/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java +++ b/src/java/org/apache/poi/ss/usermodel/ClientAnchor.java @@ -1,202 +1,202 @@ -/* ====================================================================
- 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 client anchor is attached to an excel worksheet. It anchors against a
- * top-left and bottom-right cell.
- *
- * @author Yegor Kozlov
- */
-public interface ClientAnchor {
- /**
- * Move and Resize With Anchor Cells
- * <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>
- */
- public static final int MOVE_AND_RESIZE = 0;
-
- /**
- * Move With Cells but Do Not Resize
- * <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>
- */
- public static final int MOVE_DONT_RESIZE = 2;
-
- /**
- * Do Not Move or Resize With Underlying Rows/Columns
- * <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>
- */
- public static final int DONT_MOVE_AND_RESIZE = 3;
-
- /**
- * Returns the column (0 based) of the first cell.
- *
- * @return 0-based column of the first cell.
- */
- 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.
- *
- * @return 0-based column of the second cell.
- */
- 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.
- *
- * @return 0-based row of the first cell.
- */
- 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.
- *
- * @return 0-based row of the second cell.
- */
- 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
- *
- * @return the x coordinate within the first cell
- */
- public int getDx1();
-
- /**
- * Sets the x coordinate within the first cell
- *
- * @param dx1 the x coordinate within the first cell
- */
- public void setDx1(int dx1);
-
- /**
- * Returns the y coordinate within the first cell
- *
- * @return the y coordinate within the first cell
- */
- public int getDy1();
-
- /**
- * Sets the y coordinate within the first cell
- *
- * @param dy1 the y coordinate within the first cell
- */
- public void setDy1(int dy1);
-
- /**
- * Sets the y coordinate within the second cell
- *
- * @return the y coordinate within the second cell
- */
- public int getDy2();
-
- /**
- * Sets the y coordinate within the second cell
- *
- * @param dy2 the y coordinate within the second cell
- */
- public void setDy2(int dy2);
-
- /**
- * Returns the x coordinate within the second cell
- *
- * @return the x coordinate within the second cell
- */
- public int getDx2();
-
- /**
- * Sets the x coordinate within the second cell
- *
- * @param dx2 the x coordinate within the second cell
- */
- public void setDx2(int dx2);
-
-
- /**
- * Sets the anchor type
- * <p>
- * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
- * </p>
- * @param anchorType the anchor type
- * @see #MOVE_AND_RESIZE
- * @see #MOVE_DONT_RESIZE
- * @see #DONT_MOVE_AND_RESIZE
- */
- public void setAnchorType( int anchorType );
-
- /**
- * Gets the anchor type
- * <p>
- * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
- * </p>
- * @return the anchor type
- * @see #MOVE_AND_RESIZE
- * @see #MOVE_DONT_RESIZE
- * @see #DONT_MOVE_AND_RESIZE
- */
- public int getAnchorType();
-
-}
+/* ==================================================================== + 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 client anchor is attached to an excel worksheet. It anchors against a + * top-left and bottom-right cell. + * + * @author Yegor Kozlov + */ +public interface ClientAnchor { + /** + * Move and Resize With Anchor Cells + * <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> + */ + public static final int MOVE_AND_RESIZE = 0; + + /** + * Move With Cells but Do Not Resize + * <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> + */ + public static final int MOVE_DONT_RESIZE = 2; + + /** + * Do Not Move or Resize With Underlying Rows/Columns + * <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> + */ + public static final int DONT_MOVE_AND_RESIZE = 3; + + /** + * Returns the column (0 based) of the first cell. + * + * @return 0-based column of the first cell. + */ + 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. + * + * @return 0-based column of the second cell. + */ + 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. + * + * @return 0-based row of the first cell. + */ + 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. + * + * @return 0-based row of the second cell. + */ + 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 + * + * @return the x coordinate within the first cell + */ + public int getDx1(); + + /** + * Sets the x coordinate within the first cell + * + * @param dx1 the x coordinate within the first cell + */ + public void setDx1(int dx1); + + /** + * Returns the y coordinate within the first cell + * + * @return the y coordinate within the first cell + */ + public int getDy1(); + + /** + * Sets the y coordinate within the first cell + * + * @param dy1 the y coordinate within the first cell + */ + public void setDy1(int dy1); + + /** + * Sets the y coordinate within the second cell + * + * @return the y coordinate within the second cell + */ + public int getDy2(); + + /** + * Sets the y coordinate within the second cell + * + * @param dy2 the y coordinate within the second cell + */ + public void setDy2(int dy2); + + /** + * Returns the x coordinate within the second cell + * + * @return the x coordinate within the second cell + */ + public int getDx2(); + + /** + * Sets the x coordinate within the second cell + * + * @param dx2 the x coordinate within the second cell + */ + public void setDx2(int dx2); + + + /** + * Sets the anchor type + * <p> + * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells. + * </p> + * @param anchorType the anchor type + * @see #MOVE_AND_RESIZE + * @see #MOVE_DONT_RESIZE + * @see #DONT_MOVE_AND_RESIZE + */ + public void setAnchorType( int anchorType ); + + /** + * Gets the anchor type + * <p> + * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells. + * </p> + * @return the anchor type + * @see #MOVE_AND_RESIZE + * @see #MOVE_DONT_RESIZE + * @see #DONT_MOVE_AND_RESIZE + */ + public int getAnchorType(); + +} diff --git a/src/java/org/apache/poi/ss/usermodel/DataFormatter.java b/src/java/org/apache/poi/ss/usermodel/DataFormatter.java index 50e3690f7c..f402a0cfab 100755 --- a/src/java/org/apache/poi/ss/usermodel/DataFormatter.java +++ b/src/java/org/apache/poi/ss/usermodel/DataFormatter.java @@ -1,665 +1,665 @@ -/* ====================================================================
- 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 java.util.regex.Matcher;
-import java.util.*;
-import java.text.*;
-
-/**
- * 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.
- *
- * @author James May (james dot may at fmr dot com)
- *
- */
-public class DataFormatter {
-
- /** 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("((A|P)[M/P]*)", Pattern.CASE_INSENSITIVE);
-
- /** A regex to find patterns like [$$-1009] and [$?-452]. */
- private static final Pattern specialPatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+\\])");
-
- /** <em>General</em> format for whole numbers. */
- private static final Format generalWholeNumFormat = new DecimalFormat("#");
-
- /** <em>General</em> format for decimal numbers. */
- private static final Format generalDecimalNumFormat = new DecimalFormat("#.##########");
-
- /** 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 formats;
-
- /**
- * Constructor
- */
- public DataFormatter() {
- formats = new HashMap();
-
- // init built-in formats
-
- 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);
- }
-
- /**
- * Return a Format for the given cell if one exists, otherwise try to
- * create one. This method will return <code>null</code> if the 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) {
- if ( cell.getCellStyle() == null) {
- return null;
- }
-
- int formatIndex = cell.getCellStyle().getDataFormat();
- String formatStr = cell.getCellStyle().getDataFormatString();
- if(formatStr == null || formatStr.trim().length() == 0) {
- return null;
- }
- return getFormat(cell.getNumericCellValue(), formatIndex, formatStr);
- }
-
- private Format getFormat(double cellValue, int formatIndex, String formatStr) {
- Format format = (Format)formats.get(formatStr);
- if (format != null) {
- return format;
- }
- if (formatStr.equals("General") || formatStr.equals("@")) {
- if (DataFormatter.isWholeNumber(cellValue)) {
- return generalWholeNumFormat;
- }
- return generalDecimalNumFormat;
- }
- 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) {
- // remove color formatting if present
- String formatStr = sFormat.replaceAll("\\[[a-zA-Z]*\\]", "");
-
- // try to extract special characters like currency
- Matcher m = specialPatternGroup.matcher(formatStr);
- while(m.find()) {
- String match = m.group();
- String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-'));
- if (symbol.indexOf('$') > -1) {
- StringBuffer sb = new StringBuffer();
- sb.append(symbol.substring(0, symbol.indexOf('$')));
- sb.append('\\');
- sb.append(symbol.substring(symbol.indexOf('$'), symbol.length()));
- symbol = sb.toString();
- }
- formatStr = m.replaceAll(symbol);
- m = specialPatternGroup.matcher(formatStr);
- }
-
- if(formatStr == null || formatStr.trim().length() == 0) {
- return getDefaultFormat(cellValue);
- }
-
-
- if(DateUtil.isADateFormat(formatIndex,formatStr) &&
- DateUtil.isValidExcelDate(cellValue)) {
- return createDateFormat(formatStr, cellValue);
- }
- if (numPattern.matcher(formatStr).find()) {
- return createNumberFormat(formatStr, cellValue);
- }
- // TODO - when does this occur?
- return null;
- }
-
- private Format createDateFormat(String pFormatStr, double cellValue) {
- String formatStr = pFormatStr;
- formatStr = formatStr.replaceAll("\\\\-","-");
- formatStr = formatStr.replaceAll("\\\\,",",");
- formatStr = formatStr.replaceAll("\\\\ "," ");
- formatStr = formatStr.replaceAll(";@", "");
- boolean hasAmPm = false;
- Matcher amPmMatcher = amPmPattern.matcher(formatStr);
- while (amPmMatcher.find()) {
- formatStr = amPmMatcher.replaceAll("@");
- hasAmPm = true;
- amPmMatcher = amPmPattern.matcher(formatStr);
- }
- formatStr = formatStr.replaceAll("@", "a");
-
-
- Matcher dateMatcher = daysAsText.matcher(formatStr);
- if (dateMatcher.find()) {
- String match = dateMatcher.group(0);
- formatStr = dateMatcher.replaceAll(match.toUpperCase().replaceAll("D", "E"));
- }
-
- // Convert excel date format to SimpleDateFormat.
- // Excel uses lower 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."
- */
-
- StringBuffer sb = new StringBuffer();
- char[] chars = formatStr.toCharArray();
- boolean mIsMonth = true;
- List ms = new ArrayList();
- for(int j=0; j<chars.length; j++) {
- char c = chars[j];
- if (c == 'h' || c == 'H') {
- mIsMonth = false;
- if (hasAmPm) {
- sb.append('h');
- } else {
- sb.append('H');
- }
- }
- else if (c == 'm') {
- if(mIsMonth) {
- sb.append('M');
- ms.add(
- new Integer(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 i = 0; i < ms.size(); i++) {
- int index = ((Integer)ms.get(i)).intValue();
- 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 {
- sb.append(c);
- }
- }
- formatStr = sb.toString();
-
- try {
- return new SimpleDateFormat(formatStr);
- } catch(IllegalArgumentException iae) {
-
- // the pattern could not be parsed correctly,
- // so fall back to the default number format
- return getDefaultFormat(cellValue);
- }
-
- }
-
- private Format createNumberFormat(String formatStr, double cellValue) {
- StringBuffer sb = new StringBuffer(formatStr);
- for (int i = 0; i < sb.length(); i++) {
- char c = sb.charAt(i);
- //handle (#,##0_);
- if (c == '(') {
- int idx = sb.indexOf(")", i);
- if (idx > -1 && sb.charAt(idx -1) == '_') {
- sb.deleteCharAt(idx);
- sb.deleteCharAt(idx - 1);
- sb.deleteCharAt(i);
- i--;
- }
- } else if (c == ')' && i > 0 && sb.charAt(i - 1) == '_') {
- sb.deleteCharAt(i);
- sb.deleteCharAt(i - 1);
- i--;
- // remove quotes and back slashes
- } else if (c == '\\' || c == '"') {
- sb.deleteCharAt(i);
- i--;
-
- // for scientific/engineering notation
- } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') {
- sb.deleteCharAt(i);
- i--;
- }
- }
-
- try {
- return new DecimalFormat(sb.toString());
- } catch(IllegalArgumentException iae) {
-
- // the pattern could not be parsed correctly,
- // so fall back to the default number format
- return getDefaultFormat(cellValue);
- }
- }
-
- /**
- * Return true if the double value represents a whole number
- * @param d the double value to check
- * @return <code>true</code> if d is a whole number
- */
- private static boolean isWholeNumber(double d) {
- return d == Math.floor(d);
- }
-
- /**
- * 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) {
- // for numeric cells try user supplied default
- if (defaultNumFormat != null) {
- return defaultNumFormat;
-
- // otherwise use general format
- }
- if (isWholeNumber(cellValue)){
- return generalWholeNumFormat;
- }
- return generalDecimalNumFormat;
- }
-
- /**
- * 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.
- *
- * @param cell The cell
- * @return a formatted date string
- */
- private String getFormattedDateString(Cell cell) {
- Format dateFormat = getFormat(cell);
- Date d = cell.getDateCellValue();
- if (dateFormat != null) {
- return dateFormat.format(d);
- }
- return d.toString();
- }
-
- /**
- * 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".
- *
- * @param cell The cell
- * @return a formatted number string
- */
- private String getFormattedNumberString(Cell cell) {
-
- Format numberFormat = getFormat(cell);
- double d = cell.getNumericCellValue();
- if (numberFormat == null) {
- return String.valueOf(d);
- }
- return numberFormat.format(new Double(d));
- }
-
- /**
- * 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) {
- // Is it a date?
- if(DateUtil.isADateFormat(formatIndex,formatString) &&
- DateUtil.isValidExcelDate(value)) {
-
- Format dateFormat = getFormat(value, formatIndex, formatString);
- Date d = DateUtil.getJavaDate(value);
- if (dateFormat == null) {
- return d.toString();
- }
- return dateFormat.format(d);
- }
- // else Number
- Format numberFormat = getFormat(value, formatIndex, formatString);
- if (numberFormat == null) {
- return String.valueOf(value);
- }
- return numberFormat.format(new Double(value));
- }
-
- /**
- * <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 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) {
-
- if (cell == null) {
- return "";
- }
-
- int cellType = cell.getCellType();
- if (cellType == Cell.CELL_TYPE_FORMULA) {
- if (evaluator == null) {
- return cell.getCellFormula();
- }
- cellType = evaluator.evaluateFormulaCell(cell);
- }
- switch (cellType) {
- case Cell.CELL_TYPE_NUMERIC :
-
- if (DateUtil.isCellDateFormatted(cell)) {
- return getFormattedDateString(cell);
- }
- return getFormattedNumberString(cell);
-
- case Cell.CELL_TYPE_STRING :
- return cell.getRichStringCellValue().getString();
-
- case Cell.CELL_TYPE_BOOLEAN :
- return String.valueOf(cell.getBooleanCellValue());
- case Cell.CELL_TYPE_BLANK :
- return "";
- }
- 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 java.text.Format#format
- */
- public void setDefaultNumberFormat(Format format) {
- Iterator itr = formats.entrySet().iterator();
- while(itr.hasNext()) {
- Map.Entry entry = (Map.Entry)itr.next();
- if (entry.getValue() == generalDecimalNumFormat
- || entry.getValue() == generalWholeNumFormat) {
- 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>
- */
- /* package */ static DecimalFormat createIntegerOnlyFormat(String fmt) {
- DecimalFormat result = new DecimalFormat(fmt);
- result.setParseIntegerOnly(true);
- return result;
- }
- /**
- * Format class for Excel's SSN format. This class mimics Excel's built-in
- * SSN formatting.
- *
- * @author James May
- */
- 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);
- StringBuffer sb = new StringBuffer();
- sb.append(result.substring(0, 3)).append('-');
- sb.append(result.substring(3, 5)).append('-');
- sb.append(result.substring(5, 9));
- 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) {
- 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
- */
- 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);
- StringBuffer sb = new StringBuffer();
- sb.append(result.substring(0, 5)).append('-');
- sb.append(result.substring(5, 9));
- 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) {
- 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
- */
- 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);
- StringBuffer sb = new StringBuffer();
- 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 != null && seg1.trim().length() > 0) {
- sb.append('(').append(seg1).append(") ");
- }
- if(seg2 != null && seg2.trim().length() > 0) {
- sb.append(seg2).append('-');
- }
- sb.append(seg3);
- 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) {
- return df.parseObject(source, pos);
- }
- }
-}
+/* ==================================================================== + 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 java.util.regex.Matcher; +import java.util.*; +import java.text.*; + +/** + * 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. + * + * @author James May (james dot may at fmr dot com) + * + */ +public class DataFormatter { + + /** 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("((A|P)[M/P]*)", Pattern.CASE_INSENSITIVE); + + /** A regex to find patterns like [$$-1009] and [$?-452]. */ + private static final Pattern specialPatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+\\])"); + + /** <em>General</em> format for whole numbers. */ + private static final Format generalWholeNumFormat = new DecimalFormat("#"); + + /** <em>General</em> format for decimal numbers. */ + private static final Format generalDecimalNumFormat = new DecimalFormat("#.##########"); + + /** 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 formats; + + /** + * Constructor + */ + public DataFormatter() { + formats = new HashMap(); + + // init built-in formats + + 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); + } + + /** + * Return a Format for the given cell if one exists, otherwise try to + * create one. This method will return <code>null</code> if the 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) { + if ( cell.getCellStyle() == null) { + return null; + } + + int formatIndex = cell.getCellStyle().getDataFormat(); + String formatStr = cell.getCellStyle().getDataFormatString(); + if(formatStr == null || formatStr.trim().length() == 0) { + return null; + } + return getFormat(cell.getNumericCellValue(), formatIndex, formatStr); + } + + private Format getFormat(double cellValue, int formatIndex, String formatStr) { + Format format = (Format)formats.get(formatStr); + if (format != null) { + return format; + } + if (formatStr.equals("General") || formatStr.equals("@")) { + if (DataFormatter.isWholeNumber(cellValue)) { + return generalWholeNumFormat; + } + return generalDecimalNumFormat; + } + 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) { + // remove color formatting if present + String formatStr = sFormat.replaceAll("\\[[a-zA-Z]*\\]", ""); + + // try to extract special characters like currency + Matcher m = specialPatternGroup.matcher(formatStr); + while(m.find()) { + String match = m.group(); + String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-')); + if (symbol.indexOf('$') > -1) { + StringBuffer sb = new StringBuffer(); + sb.append(symbol.substring(0, symbol.indexOf('$'))); + sb.append('\\'); + sb.append(symbol.substring(symbol.indexOf('$'), symbol.length())); + symbol = sb.toString(); + } + formatStr = m.replaceAll(symbol); + m = specialPatternGroup.matcher(formatStr); + } + + if(formatStr == null || formatStr.trim().length() == 0) { + return getDefaultFormat(cellValue); + } + + + if(DateUtil.isADateFormat(formatIndex,formatStr) && + DateUtil.isValidExcelDate(cellValue)) { + return createDateFormat(formatStr, cellValue); + } + if (numPattern.matcher(formatStr).find()) { + return createNumberFormat(formatStr, cellValue); + } + // TODO - when does this occur? + return null; + } + + private Format createDateFormat(String pFormatStr, double cellValue) { + String formatStr = pFormatStr; + formatStr = formatStr.replaceAll("\\\\-","-"); + formatStr = formatStr.replaceAll("\\\\,",","); + formatStr = formatStr.replaceAll("\\\\ "," "); + formatStr = formatStr.replaceAll(";@", ""); + boolean hasAmPm = false; + Matcher amPmMatcher = amPmPattern.matcher(formatStr); + while (amPmMatcher.find()) { + formatStr = amPmMatcher.replaceAll("@"); + hasAmPm = true; + amPmMatcher = amPmPattern.matcher(formatStr); + } + formatStr = formatStr.replaceAll("@", "a"); + + + Matcher dateMatcher = daysAsText.matcher(formatStr); + if (dateMatcher.find()) { + String match = dateMatcher.group(0); + formatStr = dateMatcher.replaceAll(match.toUpperCase().replaceAll("D", "E")); + } + + // Convert excel date format to SimpleDateFormat. + // Excel uses lower 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." + */ + + StringBuffer sb = new StringBuffer(); + char[] chars = formatStr.toCharArray(); + boolean mIsMonth = true; + List ms = new ArrayList(); + for(int j=0; j<chars.length; j++) { + char c = chars[j]; + if (c == 'h' || c == 'H') { + mIsMonth = false; + if (hasAmPm) { + sb.append('h'); + } else { + sb.append('H'); + } + } + else if (c == 'm') { + if(mIsMonth) { + sb.append('M'); + ms.add( + new Integer(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 i = 0; i < ms.size(); i++) { + int index = ((Integer)ms.get(i)).intValue(); + 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 { + sb.append(c); + } + } + formatStr = sb.toString(); + + try { + return new SimpleDateFormat(formatStr); + } catch(IllegalArgumentException iae) { + + // the pattern could not be parsed correctly, + // so fall back to the default number format + return getDefaultFormat(cellValue); + } + + } + + private Format createNumberFormat(String formatStr, double cellValue) { + StringBuffer sb = new StringBuffer(formatStr); + for (int i = 0; i < sb.length(); i++) { + char c = sb.charAt(i); + //handle (#,##0_); + if (c == '(') { + int idx = sb.indexOf(")", i); + if (idx > -1 && sb.charAt(idx -1) == '_') { + sb.deleteCharAt(idx); + sb.deleteCharAt(idx - 1); + sb.deleteCharAt(i); + i--; + } + } else if (c == ')' && i > 0 && sb.charAt(i - 1) == '_') { + sb.deleteCharAt(i); + sb.deleteCharAt(i - 1); + i--; + // remove quotes and back slashes + } else if (c == '\\' || c == '"') { + sb.deleteCharAt(i); + i--; + + // for scientific/engineering notation + } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') { + sb.deleteCharAt(i); + i--; + } + } + + try { + return new DecimalFormat(sb.toString()); + } catch(IllegalArgumentException iae) { + + // the pattern could not be parsed correctly, + // so fall back to the default number format + return getDefaultFormat(cellValue); + } + } + + /** + * Return true if the double value represents a whole number + * @param d the double value to check + * @return <code>true</code> if d is a whole number + */ + private static boolean isWholeNumber(double d) { + return d == Math.floor(d); + } + + /** + * 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) { + // for numeric cells try user supplied default + if (defaultNumFormat != null) { + return defaultNumFormat; + + // otherwise use general format + } + if (isWholeNumber(cellValue)){ + return generalWholeNumFormat; + } + return generalDecimalNumFormat; + } + + /** + * 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. + * + * @param cell The cell + * @return a formatted date string + */ + private String getFormattedDateString(Cell cell) { + Format dateFormat = getFormat(cell); + Date d = cell.getDateCellValue(); + if (dateFormat != null) { + return dateFormat.format(d); + } + return d.toString(); + } + + /** + * 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". + * + * @param cell The cell + * @return a formatted number string + */ + private String getFormattedNumberString(Cell cell) { + + Format numberFormat = getFormat(cell); + double d = cell.getNumericCellValue(); + if (numberFormat == null) { + return String.valueOf(d); + } + return numberFormat.format(new Double(d)); + } + + /** + * 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) { + // Is it a date? + if(DateUtil.isADateFormat(formatIndex,formatString) && + DateUtil.isValidExcelDate(value)) { + + Format dateFormat = getFormat(value, formatIndex, formatString); + Date d = DateUtil.getJavaDate(value); + if (dateFormat == null) { + return d.toString(); + } + return dateFormat.format(d); + } + // else Number + Format numberFormat = getFormat(value, formatIndex, formatString); + if (numberFormat == null) { + return String.valueOf(value); + } + return numberFormat.format(new Double(value)); + } + + /** + * <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 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) { + + if (cell == null) { + return ""; + } + + int cellType = cell.getCellType(); + if (cellType == Cell.CELL_TYPE_FORMULA) { + if (evaluator == null) { + return cell.getCellFormula(); + } + cellType = evaluator.evaluateFormulaCell(cell); + } + switch (cellType) { + case Cell.CELL_TYPE_NUMERIC : + + if (DateUtil.isCellDateFormatted(cell)) { + return getFormattedDateString(cell); + } + return getFormattedNumberString(cell); + + case Cell.CELL_TYPE_STRING : + return cell.getRichStringCellValue().getString(); + + case Cell.CELL_TYPE_BOOLEAN : + return String.valueOf(cell.getBooleanCellValue()); + case Cell.CELL_TYPE_BLANK : + return ""; + } + 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 java.text.Format#format + */ + public void setDefaultNumberFormat(Format format) { + Iterator itr = formats.entrySet().iterator(); + while(itr.hasNext()) { + Map.Entry entry = (Map.Entry)itr.next(); + if (entry.getValue() == generalDecimalNumFormat + || entry.getValue() == generalWholeNumFormat) { + 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> + */ + /* package */ static DecimalFormat createIntegerOnlyFormat(String fmt) { + DecimalFormat result = new DecimalFormat(fmt); + result.setParseIntegerOnly(true); + return result; + } + /** + * Format class for Excel's SSN format. This class mimics Excel's built-in + * SSN formatting. + * + * @author James May + */ + 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); + StringBuffer sb = new StringBuffer(); + sb.append(result.substring(0, 3)).append('-'); + sb.append(result.substring(3, 5)).append('-'); + sb.append(result.substring(5, 9)); + 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) { + 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 + */ + 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); + StringBuffer sb = new StringBuffer(); + sb.append(result.substring(0, 5)).append('-'); + sb.append(result.substring(5, 9)); + 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) { + 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 + */ + 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); + StringBuffer sb = new StringBuffer(); + 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 != null && seg1.trim().length() > 0) { + sb.append('(').append(seg1).append(") "); + } + if(seg2 != null && seg2.trim().length() > 0) { + sb.append(seg2).append('-'); + } + sb.append(seg3); + 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) { + return df.parseObject(source, pos); + } + } +} diff --git a/src/java/org/apache/poi/ss/usermodel/Drawing.java b/src/java/org/apache/poi/ss/usermodel/Drawing.java index c7b8dc0e84..b27c3098c0 100755 --- a/src/java/org/apache/poi/ss/usermodel/Drawing.java +++ b/src/java/org/apache/poi/ss/usermodel/Drawing.java @@ -1,24 +1,24 @@ -/* ====================================================================
- 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 Drawing {
- Picture createPicture(ClientAnchor anchor, int pictureIndex);
-}
+/* ==================================================================== + 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 Drawing { + Picture createPicture(ClientAnchor anchor, int pictureIndex); +} diff --git a/src/java/org/apache/poi/ss/usermodel/FormulaError.java b/src/java/org/apache/poi/ss/usermodel/FormulaError.java index 4f631c6ee4..c3c43301e5 100755 --- a/src/java/org/apache/poi/ss/usermodel/FormulaError.java +++ b/src/java/org/apache/poi/ss/usermodel/FormulaError.java @@ -1,140 +1,140 @@ -/* ====================================================================
- 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 java.util.HashMap;
-
-/**
- * Enumerates error values in SpreadsheetML formula calculations.
- *
- * @author Yegor Kozlov
- */
-public enum FormulaError {
- /**
- * 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(0x1D, "#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");
-
- private byte type;
- private String repr;
-
- private FormulaError(int type, String repr) {
- this.type = (byte) type;
- this.repr = repr;
- }
-
- /**
- * @return numeric code of the error
- */
- public byte getCode() {
- return type;
- }
-
- /**
- * @return string representation of the error
- */
- public String getString() {
- return repr;
- }
-
- private static Map<String, FormulaError> smap = new HashMap<String, FormulaError>();
- private static Map<Byte, FormulaError> imap = new HashMap<Byte, FormulaError>();
- static{
- for (FormulaError error : values()) {
- imap.put(error.getCode(), error);
- smap.put(error.getString(), error);
- }
- }
-
- public static FormulaError forInt(byte type){
- FormulaError err = imap.get(type);
- if(err == null) throw new IllegalArgumentException("Unknown error type: " + type);
- return err;
- }
-
- public static FormulaError forString(String code){
- FormulaError err = smap.get(code);
- if(err == null) throw new IllegalArgumentException("Unknown error code: " + code);
- return err;
- }
-}
+/* ==================================================================== + 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 java.util.HashMap; + +/** + * Enumerates error values in SpreadsheetML formula calculations. + * + * @author Yegor Kozlov + */ +public enum FormulaError { + /** + * 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(0x1D, "#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"); + + private byte type; + private String repr; + + private FormulaError(int type, String repr) { + this.type = (byte) type; + this.repr = repr; + } + + /** + * @return numeric code of the error + */ + public byte getCode() { + return type; + } + + /** + * @return string representation of the error + */ + public String getString() { + return repr; + } + + private static Map<String, FormulaError> smap = new HashMap<String, FormulaError>(); + private static Map<Byte, FormulaError> imap = new HashMap<Byte, FormulaError>(); + static{ + for (FormulaError error : values()) { + imap.put(error.getCode(), error); + smap.put(error.getString(), error); + } + } + + public static FormulaError forInt(byte type){ + FormulaError err = imap.get(type); + if(err == null) throw new IllegalArgumentException("Unknown error type: " + type); + return err; + } + + public static FormulaError forString(String code){ + 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/HorizontalAlignment.java b/src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java index bcc05d8fbf..9be6017ab0 100755 --- a/src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java +++ b/src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java @@ -1,95 +1,95 @@ -/* ====================================================================
- 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
-}
+/* ==================================================================== + 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 +} diff --git a/src/java/org/apache/poi/ss/usermodel/Picture.java b/src/java/org/apache/poi/ss/usermodel/Picture.java index dd6a8e7d31..e816c9ac15 100755 --- a/src/java/org/apache/poi/ss/usermodel/Picture.java +++ b/src/java/org/apache/poi/ss/usermodel/Picture.java @@ -1,42 +1,42 @@ -/* ====================================================================
- 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;
-
-/**
- * Repersents a picture in a SpreadsheetML document
- *
- * @author Yegor Kozlov
- */
-public interface Picture {
-
- /**
- * Reset the image to the original size.
- */
- void resize();
-
- /**
- * Reset the image to the original size.
- *
- * @param scale the amount by which image dimensions are multiplied relative to the original size.
- * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original,
- * <code>resize(2.0)</code> resizes to 200% of the original.
- */
- void resize(double scale);
-
- ClientAnchor getPreferredSize();
-
-}
+/* ==================================================================== + 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; + +/** + * Repersents a picture in a SpreadsheetML document + * + * @author Yegor Kozlov + */ +public interface Picture { + + /** + * Reset the image to the original size. + */ + void resize(); + + /** + * Reset the image to the original size. + * + * @param scale the amount by which image dimensions are multiplied relative to the original size. + * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original, + * <code>resize(2.0)</code> resizes to 200% of the original. + */ + void resize(double scale); + + ClientAnchor getPreferredSize(); + +} diff --git a/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java b/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java index ef8409340c..3c5747ee5a 100755 --- a/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java +++ b/src/java/org/apache/poi/ss/usermodel/ShapeTypes.java @@ -1,212 +1,212 @@ -/* ====================================================================
- 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;
-}
+/* ==================================================================== + 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/VerticalAlignment.java b/src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java index 2f93273287..398565d043 100755 --- a/src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java +++ b/src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java @@ -1,69 +1,69 @@ -/* ====================================================================
- 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.
- */
-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.
- */
- 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
-}
+/* ==================================================================== + 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. + */ +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. + */ + 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 +} |