org.apache.poi.ss.SpreadsheetVersion Java Examples

The following examples show how to use org.apache.poi.ss.SpreadsheetVersion. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HSSFSheetConditionalFormatting.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Allows to add a new Conditional Formatting set to the sheet.
 *
 * @param regions - list of rectangular regions to apply conditional formatting rules
 * @param cfRules - set of up to three conditional formatting rules
 *
 * @return index of the newly created Conditional Formatting object
 */
public int addConditionalFormatting(CellRangeAddress[] regions, HSSFConditionalFormattingRule[] cfRules) {
    if (regions == null) {
        throw new IllegalArgumentException("regions must not be null");
    }
    for(CellRangeAddress range : regions) range.validate(SpreadsheetVersion.EXCEL97);

    if (cfRules == null) {
        throw new IllegalArgumentException("cfRules must not be null");
    }
    if (cfRules.length == 0) {
        throw new IllegalArgumentException("cfRules must not be empty");
    }
    if (cfRules.length > 3) {
        throw new IllegalArgumentException("Number of rules must not exceed 3");
    }

    CFRuleBase[] rules = new CFRuleBase[cfRules.length];
    for (int i = 0; i != cfRules.length; i++) {
        rules[i] = cfRules[i].getCfRuleRecord();
    }
    CFRecordsAggregate cfra = new CFRecordsAggregate(regions, rules);
    return _conditionalFormattingTable.add(cfra);
}
 
Example #2
Source File: CellReference.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isColumnWithinRange(String colStr, SpreadsheetVersion ssVersion) {
    // Equivalent to 0 <= CellReference.convertColStringToIndex(colStr) <= ssVersion.getLastColumnIndex()

    String lastCol = ssVersion.getLastColumnName();
    int lastColLength = lastCol.length();

    int numberOfLetters = colStr.length();
    if(numberOfLetters > lastColLength) {
        // "Sheet1" case etc
        return false; // that was easy
    }
    if(numberOfLetters == lastColLength) {
        if(colStr.toUpperCase(Locale.ROOT).compareTo(lastCol) > 0) {
            return false;
        }
    } else {
        // apparent column name has less chars than max
        // no need to check range
    }
    return true;
}
 
Example #3
Source File: CellReference.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static NameType validateNamedRangeName(String str, SpreadsheetVersion ssVersion) {
    Matcher colMatcher = COLUMN_REF_PATTERN.matcher(str);
    if (colMatcher.matches()) {
        String colStr = colMatcher.group(1);
        if (isColumnWithinRange(colStr, ssVersion)) {
            return NameType.COLUMN;
        }
    }
    Matcher rowMatcher = ROW_REF_PATTERN.matcher(str);
    if (rowMatcher.matches()) {
        String rowStr = rowMatcher.group(1);
        if (isRowWithinRange(rowStr, ssVersion)) {
            return NameType.ROW;
        }
    }
    if (!NAMED_RANGE_NAME_PATTERN.matcher(str).matches()) {
        return NameType.BAD_CELL_OR_NAMED_RANGE;
    }
    return NameType.NAMED_RANGE;
}
 
Example #4
Source File: FormulaShifter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create an instance for shifting row.
 *
 * For example, this will be called on {@link org.apache.poi.hssf.usermodel.HSSFSheet#shiftRows(int, int, int)} }
 */
private FormulaShifter(int externSheetIndex, String sheetName, int firstMovedIndex, int lastMovedIndex, int amountToMove,
        ShiftMode mode, SpreadsheetVersion version) {
    if (amountToMove == 0) {
        throw new IllegalArgumentException("amountToMove must not be zero");
    }
    if (firstMovedIndex > lastMovedIndex) {
        throw new IllegalArgumentException("firstMovedIndex, lastMovedIndex out of order");
    }
    _externSheetIndex = externSheetIndex;
    _sheetName = sheetName;
    _firstMovedIndex = firstMovedIndex;
    _lastMovedIndex = lastMovedIndex;
    _amountToMove = amountToMove;
    _mode = mode;
    _version = version;

    _srcSheetIndex = _dstSheetIndex = -1;
}
 
Example #5
Source File: HSSFSheet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * adds a merged region of cells (hence those cells form one)
 *
 * @param region (rowfrom/colfrom-rowto/colto) to merge
 * @param validate whether to validate merged region
 * @return index of this region
 * @throws IllegalArgumentException if region contains fewer than 2 cells
 * @throws IllegalStateException if region intersects with an existing merged region
 * or multi-cell array formula on this sheet
 */
private int addMergedRegion(CellRangeAddress region, boolean validate) {
    if (region.getNumberOfCells() < 2) {
        throw new IllegalArgumentException("Merged region " + region.formatAsString() + " must contain 2 or more cells");
    }
    region.validate(SpreadsheetVersion.EXCEL97);

    if (validate) {
        // throw IllegalStateException if the argument CellRangeAddress intersects with
        // a multi-cell array formula defined in this sheet
        validateArrayFormulas(region);
    
        // Throw IllegalStateException if the argument CellRangeAddress intersects with
        // a merged region already in this sheet
        validateMergedRegions(region);
    }

    return _sheet.addMergedRegion(region.getFirstRow(),
            region.getFirstColumn(),
            region.getLastRow(),
            region.getLastColumn());
}
 
Example #6
Source File: AreaPtgBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected final String formatReferenceAsString() {
    CellReference topLeft = new CellReference(getFirstRow(),getFirstColumn(),!isFirstRowRelative(),!isFirstColRelative());
    CellReference botRight = new CellReference(getLastRow(),getLastColumn(),!isLastRowRelative(),!isLastColRelative());

    if(AreaReference.isWholeColumnReference(SpreadsheetVersion.EXCEL97, topLeft, botRight)) {
        return (new AreaReference(topLeft, botRight, SpreadsheetVersion.EXCEL97)).formatAsString();
    }
    return topLeft.formatAsString() + ":" + botRight.formatAsString();
}
 
Example #7
Source File: HSSFSheet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets desktop window pane display area, when the
 * file is first opened in a viewer.
 *
 * @param toprow  the top row to show in desktop window pane
 * @param leftcol the left column to show in desktop window pane
 */
@Override
public void showInPane(int toprow, int leftcol) {
    int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
    if (toprow > maxrow) throw new IllegalArgumentException("Maximum row number is " + maxrow);
    
    showInPane((short)toprow, (short)leftcol);
}
 
Example #8
Source File: HSSFSheet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private CellRangeAddress getRepeatingRowsOrColums(boolean rows) {
    NameRecord rec = getBuiltinNameRecord(NameRecord.BUILTIN_PRINT_TITLE);
    if (rec == null) {
        return null;
    }

    Ptg[] nameDefinition = rec.getNameDefinition();
    if (nameDefinition == null) {
        return null;
    }

    int maxRowIndex = SpreadsheetVersion.EXCEL97.getLastRowIndex();
    int maxColIndex = SpreadsheetVersion.EXCEL97.getLastColumnIndex();

    for (Ptg ptg : nameDefinition) {

        if (ptg instanceof Area3DPtg) {
            Area3DPtg areaPtg = (Area3DPtg) ptg;

            if (areaPtg.getFirstColumn() == 0
                    && areaPtg.getLastColumn() == maxColIndex) {
                if (rows) {
                    return new CellRangeAddress(
                            areaPtg.getFirstRow(), areaPtg.getLastRow(), -1, -1);
                }
            } else if (areaPtg.getFirstRow() == 0
                    && areaPtg.getLastRow() == maxRowIndex) {
                if (!rows) {
                    return new CellRangeAddress(-1, -1,
                            areaPtg.getFirstColumn(), areaPtg.getLastColumn());
                }
            }

        }

    }

    return null;
}
 
Example #9
Source File: HSSFRow.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * set the row number of this row.
 * @param rowIndex  the row number (0-based)
 * @throws IndexOutOfBoundsException if the row number is not within the range 0-65535.
 */
@Override
public void setRowNum(int rowIndex) {
    int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
    if ((rowIndex < 0) || (rowIndex > maxrow)) {
      throw new IllegalArgumentException("Invalid row number (" + rowIndex
              + ") outside allowable range (0.." + maxrow + ")");
    }
    rowNum = rowIndex;
    if (row != null) {
        row.setRowNumber(rowIndex);   // used only for KEY comparison (HSSFRow)
    }
}
 
Example #10
Source File: PropertyTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Draws the right border for a range of cells
 * </p>
 *
 * @param range
 *            - {@link CellRangeAddress} range of cells on which borders are
 *            drawn.
 * @param borderType
 *            - Type of border to draw. {@link BorderStyle}.
 */
private void drawRightBorder(CellRangeAddress range,
        BorderStyle borderType) {
    int firstRow = range.getFirstRow();
    int lastRow = range.getLastRow();
    int col = range.getLastColumn();
    for (int i = firstRow; i <= lastRow; i++) {
        addProperty(i, col, CellUtil.BORDER_RIGHT, borderType);
        if (borderType == BorderStyle.NONE
                && col < SpreadsheetVersion.EXCEL2007.getMaxColumns() - 1) {
            addProperty(i, col + 1, CellUtil.BORDER_LEFT, borderType);
        }
    }
}
 
Example #11
Source File: PropertyTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Draws the bottom border for a range of cells
 * </p>
 * 
 * @param range
 *            - {@link CellRangeAddress} range of cells on which borders are
 *            drawn.
 * @param borderType
 *            - Type of border to draw. {@link BorderStyle}.
 */
private void drawBottomBorder(CellRangeAddress range,
        BorderStyle borderType) {
    int row = range.getLastRow();
    int firstCol = range.getFirstColumn();
    int lastCol = range.getLastColumn();
    for (int i = firstCol; i <= lastCol; i++) {
        addProperty(row, i, CellUtil.BORDER_BOTTOM, borderType);
        if (borderType == BorderStyle.NONE
                && row < SpreadsheetVersion.EXCEL2007.getMaxRows() - 1) {
            addProperty(row + 1, i, CellUtil.BORDER_TOP, borderType);
        }
    }
}
 
Example #12
Source File: RowRecordsAggregate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public RowRecord getRow(int rowIndex) {
    int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
    if (rowIndex < 0 || rowIndex > maxrow) {
        throw new IllegalArgumentException("The row number must be between 0 and " + maxrow + ", but had: " + rowIndex);
    }
    return _rowRecords.get(Integer.valueOf(rowIndex));
}
 
Example #13
Source File: SharedFormulaRecord.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the equivalent {@link Ptg} array that the formula would have, were it not shared.
 */
public Ptg[] getFormulaTokens(FormulaRecord formula) {
    int formulaRow = formula.getRow();
    int formulaColumn = formula.getColumn();
    //Sanity checks
    if (!isInRange(formulaRow, formulaColumn)) {
        throw new RuntimeException("Shared Formula Conversion: Coding Error");
    }

    SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
    return sf.convertSharedFormulas(field_7_parsed_expr.getTokens(), formulaRow, formulaColumn);
}
 
Example #14
Source File: JRXlsExporter.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void addRowBreak(int rowIndex)
{
	if(rowIndex >= 0 && rowIndex <= SpreadsheetVersion.EXCEL97.getLastRowIndex())
	{
		sheet.setRowBreak(rowIndex);
	}
}
 
Example #15
Source File: AreaReference.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Is the reference for a whole-column reference,
 *  such as C:C or D:G ?
 */
public static boolean isWholeColumnReference(SpreadsheetVersion version, CellReference topLeft, CellReference botRight) {
    if (null == version) {
        version = DEFAULT_SPREADSHEET_VERSION; // how the code used to behave. 
    }
    
    // These are represented as something like
    //   C$1:C$65535 or D$1:F$0
    // i.e. absolute from 1st row to 0th one
    if(topLeft.getRow() == 0 && topLeft.isRowAbsolute() &&
        botRight.getRow() == version.getLastRowIndex() && botRight.isRowAbsolute()) {
        return true;
    }
    return false;
}
 
Example #16
Source File: WorkbookEvaluator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adjust the formula relative cell references by a given delta
 * @param ptgs
 * @param deltaRow target row offset from the top left cell of a region
 * @param deltaColumn target column offset from the top left cell of a region
 * @return true if any Ptg references were shifted
 * @throws IndexOutOfBoundsException if the resulting shifted row/column indexes are over the document format limits
 * @throws IllegalArgumentException if either of the deltas are negative, as the assumption is we are shifting formulas
 * relative to the top left cell of a region.
 */
protected boolean adjustRegionRelativeReference(Ptg[] ptgs, int deltaRow, int deltaColumn) {
    if (deltaRow < 0) throw new IllegalArgumentException("offset row must be positive");
    if (deltaColumn < 0) throw new IllegalArgumentException("offset column must be positive");
    boolean shifted = false;
    for (Ptg ptg : ptgs) {
        // base class for cell reference "things"
        if (ptg instanceof RefPtgBase) {
            RefPtgBase ref = (RefPtgBase) ptg;
            // re-calculate cell references
            final SpreadsheetVersion version = _workbook.getSpreadsheetVersion();
            if (ref.isRowRelative()) {
                final int rowIndex = ref.getRow() + deltaRow;
                if (rowIndex > version.getMaxRows()) {
                    throw new IndexOutOfBoundsException(version.name() + " files can only have " + version.getMaxRows() + " rows, but row " + rowIndex + " was requested.");
                }
                ref.setRow(rowIndex);
                shifted = true;
            }
            if (ref.isColRelative()) {
                final int colIndex = ref.getColumn() + deltaColumn;
                if (colIndex > version.getMaxColumns()) {
                    throw new IndexOutOfBoundsException(version.name() + " files can only have " + version.getMaxColumns() + " columns, but column " + colIndex + " was requested.");
                }
                ref.setColumn(colIndex);
                shifted = true;
            }
        }
    }
    return shifted;
}
 
Example #17
Source File: AreaReference.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Takes a non-contiguous area reference, and returns an array of contiguous area references
 * @return an array of contiguous area references.
 */
public static AreaReference[] generateContiguous(SpreadsheetVersion version, String reference) {
    if (null == version) {
        version = DEFAULT_SPREADSHEET_VERSION; // how the code used to behave. 
    }
    List<AreaReference> refs = new ArrayList<AreaReference>();
    StringTokenizer st = new StringTokenizer(reference, ",");
    while(st.hasMoreTokens()) {
        refs.add(
                new AreaReference(st.nextToken(), version)
        );
    }
    return refs.toArray(new AreaReference[refs.size()]);
}
 
Example #18
Source File: AbstractHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected static String prepareName( String name ) {
	char c = name.charAt(0);
	boolean requirePreparation = (!(c == '_' || Character.isLetter(c)) || name.indexOf(' ') != -1);
	if( !requirePreparation ) {
		for( int i = 1; i < name.length(); ++i ) {
			c = name.charAt(i);
			if(!(Character.isLetter(c) || Character.isDigit(c) || c == '_' )) {
				requirePreparation = true;
				break;
			}
		}
	}
	
	if( requirePreparation ) {
		name = name.trim();
		char chars[] = name.toCharArray();
		for( int i = 0; i < name.length(); ++i ) {
			c = chars[i];
			if(!(Character.isLetter(c) || Character.isDigit(c) || c == '_' )) {
				chars[i] = '_';
			}
		}
		name = new String(chars);
	}
	
	NameType refType = CellReference.classifyCellReference( name, SpreadsheetVersion.EXCEL2007 );
	if( ( NameType.CELL == refType ) || ( NameType.COLUMN == refType ) || ( NameType.ROW == refType ) ) {
		name = "_" + name;
	}
	
	return name;
}
 
Example #19
Source File: CellRangeAddressBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate the range limits against the supplied version of Excel
 *
 * @param ssVersion the version of Excel to validate against
 * @throws IllegalArgumentException if the range limits are outside of the allowed range
 */
public void validate(SpreadsheetVersion ssVersion) {
	validateRow(_firstRow, ssVersion);
	validateRow(_lastRow, ssVersion);
	validateColumn(_firstCol, ssVersion);
	validateColumn(_lastCol, ssVersion);
}
 
Example #20
Source File: POIUtils.java    From xlsmapper with Apache License 2.0 5 votes vote down vote up
/**
 * シートの種類を判定する。
 *
 * @since 2.0
 * @param sheet 判定対象のオブジェクト
 * @return シートの種類。不明な場合はnullを返す。
 * @throws IllegalArgumentException {@literal sheet == null}
 */
public static SpreadsheetVersion getVersion(final Sheet sheet) {
    ArgUtils.notNull(sheet, "sheet");

    if(sheet instanceof HSSFSheet) {
        return SpreadsheetVersion.EXCEL97;

    } else if(sheet instanceof XSSFSheet) {
        return SpreadsheetVersion.EXCEL2007;
    }

    return null;
}
 
Example #21
Source File: POIUtils.java    From xlsmapper with Apache License 2.0 5 votes vote down vote up
/**
 * 名前の範囲の形式を組み立てる。
 * <code>シート名!$A$1:$A:$5</code>
 * @param sheetName シート名
 * @param startPosition 設定するセルの開始位置
 * @param endPosition 設定するセルの終了位置
 * @param sheetVersion シートの形式
 * @return
 */
public static AreaReference buildNameArea(final String sheetName,
        final Point startPosition, final Point endPosition, SpreadsheetVersion sheetVersion) {

    ArgUtils.notEmpty(sheetName, "sheetName");
    ArgUtils.notNull(startPosition, "startPosition");
    ArgUtils.notNull(endPosition, "endPosition");

    final CellReference firstRefs = new CellReference(sheetName, startPosition.y, startPosition.x, true, true);
    final CellReference lastRefs = new CellReference(sheetName, endPosition.y, endPosition.x, true, true);

    return new AreaReference(firstRefs, lastRefs, sheetVersion);
}
 
Example #22
Source File: HSSFRangeHelper.java    From yarg with Apache License 2.0 5 votes vote down vote up
public static AreaReference getAreaForRange(HSSFWorkbook workbook, String rangeName) {
    int rangeNameIdx = workbook.getNameIndex(rangeName);
    if (rangeNameIdx == -1) return null;

    HSSFName aNamedRange = workbook.getNameAt(rangeNameIdx);
    return new AreaReference(aNamedRange.getRefersToFormula(), SpreadsheetVersion.EXCEL97);
}
 
Example #23
Source File: OperationEvaluationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static NameType classifyCellReference(String str, SpreadsheetVersion ssVersion) {
    int len = str.length();
    if (len < 1) {
        return CellReference.NameType.BAD_CELL_OR_NAMED_RANGE;
    }
    return CellReference.classifyCellReference(str, ssVersion);
}
 
Example #24
Source File: HSSFCell.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Set a string value for the cell.
 *
 * @param value  value to set the cell to.  For formulas we'll set the formula
 * string, for String cells we'll set its value.  For other types we will
 * change the cell to a string cell and set its value.
 * If value is <code>null</code> then we will change the cell to a Blank cell.
 */

public void setCellValue(RichTextString value)
{
    int row=_record.getRow();
    short col=_record.getColumn();
    short styleIndex=_record.getXFIndex();
    if (value == null)
    {
        notifyFormulaChanging();
        setCellType(CellType.BLANK, false, row, col, styleIndex);
        return;
    }

    if(value.length() > SpreadsheetVersion.EXCEL97.getMaxTextLength()){
        throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters");
    }

    if (_cellType == CellType.FORMULA) {
        // Set the 'pre-evaluated result' for the formula
        // note - formulas do not preserve text formatting.
        FormulaRecordAggregate fr = (FormulaRecordAggregate) _record;
        fr.setCachedStringResult(value.getString());
        // Update our local cache to the un-formatted version
        _stringValue = new HSSFRichTextString(value.getString());

        // All done
        return;
    }

    // If we get here, we're not dealing with a formula,
    //  so handle things as a normal rich text cell

    if (_cellType != CellType.STRING) {
        setCellType(CellType.STRING, false, row, col, styleIndex);
    }
    int index = 0;

    HSSFRichTextString hvalue = (HSSFRichTextString) value;
    UnicodeString str = hvalue.getUnicodeString();
    index = _book.getWorkbook().addSSTString(str);
    (( LabelSSTRecord ) _record).setSSTIndex(index);
    _stringValue = hvalue;
    _stringValue.setWorkbookReferences(_book.getWorkbook(), (( LabelSSTRecord ) _record));
    _stringValue.setUnicodeString(_book.getWorkbook().getSSTString(index));
}
 
Example #25
Source File: HSSFEvaluationWorkbook.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SpreadsheetVersion getSpreadsheetVersion(){
    return SpreadsheetVersion.EXCEL97;
}
 
Example #26
Source File: HSSFName.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * https://support.office.com/en-us/article/Define-and-use-names-in-formulas-4D0F13AC-53B7-422E-AFD2-ABD7FF379C64#bmsyntax_rules_for_names
 * 
 * Valid characters:
 *   First character: { letter | underscore | backslash }
 *   Remaining characters: { letter | number | period | underscore }
 *   
 * Cell shorthand: cannot be { "C" | "c" | "R" | "r" }
 * 
 * Cell references disallowed: cannot be a cell reference $A$1 or R1C1
 * 
 * Spaces are not valid (follows from valid characters above)
 * 
 * Name length: (XSSF-specific?) 255 characters maximum
 * 
 * Case sensitivity: all names are case-insensitive
 * 
 * Uniqueness: must be unique (for names with the same scope)
 *
 * @param name
 */
private static void validateName(String name) {

    if (name.length() == 0) {
        throw new IllegalArgumentException("Name cannot be blank");
    }
    if (name.length() > 255) {
        throw new IllegalArgumentException("Invalid name: '"+name+"': cannot exceed 255 characters in length");
    }
    if (name.equalsIgnoreCase("R") || name.equalsIgnoreCase("C")) {
        throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be special shorthand R or C");
    }
    
    // is first character valid?
    char c = name.charAt(0);
    String allowedSymbols = "_\\";
    boolean characterIsValid = (Character.isLetter(c) || allowedSymbols.indexOf(c) != -1);
    if (!characterIsValid) {
        throw new IllegalArgumentException("Invalid name: '"+name+"': first character must be underscore or a letter");
    }
    
    // are all other characters valid?
    allowedSymbols = "_.\\"; //backslashes needed for unicode escape
    for (final char ch : name.toCharArray()) {
        characterIsValid = (Character.isLetterOrDigit(ch) || allowedSymbols.indexOf(ch) != -1);
        if (!characterIsValid) {
            throw new IllegalArgumentException("Invalid name: '"+name+"': name must be letter, digit, period, or underscore");
        }
    }
    
    // Is the name a valid $A$1 cell reference
    // Because $, :, and ! are disallowed characters, A1-style references become just a letter-number combination
    if (name.matches("[A-Za-z]+\\d+")) {
        String col = name.replaceAll("\\d", "");
        String row = name.replaceAll("[A-Za-z]", "");
        if (CellReference.cellReferenceIsWithinRange(col, row, SpreadsheetVersion.EXCEL97)) {
            throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be $A$1-style cell reference");
        }
    }
    
    // Is the name a valid R1C1 cell reference?
    if (name.matches("[Rr]\\d+[Cc]\\d+")) {
        throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be R1C1-style cell reference");
    }
}
 
Example #27
Source File: HSSFSheet.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * bound a row number between 0 and last row index (65535)
 *
 * @param row the row number
 */
private static int clip(int row) {
    return Math.min(
            Math.max(0, row),
            SpreadsheetVersion.EXCEL97.getLastRowIndex());
}
 
Example #28
Source File: XLSFormatter.java    From yarg with Apache License 2.0 4 votes vote down vote up
/**
 * Method creates mapping [rangeName : List&lt;CellRangeAddress&gt;].
 * List contains all merge regions for this named range.
 * Attention: if merged regions writes wrong - look on methods isMergeRegionInsideNamedRange or isNamedRangeInsideMergeRegion
 * todo: how to recognize if merge region must be copied with named range
 *
 * @param currentSheet Sheet which contains merge regions
 */
protected void initMergeRegions(HSSFSheet currentSheet) {
    int rangeNumber = templateWorkbook.getNumberOfNames();
    for (int i = 0; i < rangeNumber; i++) {
        HSSFName aNamedRange = templateWorkbook.getNameAt(i);

        String refersToFormula = aNamedRange.getRefersToFormula();
        if (!AreaReference.isContiguous(refersToFormula)) {
            continue;
        }

        AreaReference aref = new AreaReference(refersToFormula, SpreadsheetVersion.EXCEL97);
        Integer rangeFirstRow = aref.getFirstCell().getRow();
        Integer rangeFirstColumn = (int) aref.getFirstCell().getCol();
        Integer rangeLastRow = aref.getLastCell().getRow();
        Integer rangeLastColumn = (int) aref.getLastCell().getCol();

        for (int j = 0; j < currentSheet.getNumMergedRegions(); j++) {
            CellRangeAddress mergedRegion = currentSheet.getMergedRegion(j);
            if (mergedRegion != null) {
                Integer regionFirstRow = mergedRegion.getFirstRow();
                Integer regionFirstColumn = mergedRegion.getFirstColumn();
                Integer regionLastRow = mergedRegion.getLastRow();
                Integer regionLastColumn = mergedRegion.getLastColumn();

                boolean mergedInsideNamed = isMergeRegionInsideNamedRange(
                        rangeFirstRow, rangeFirstColumn, rangeLastRow, rangeLastColumn,
                        regionFirstRow, regionFirstColumn, regionLastRow, regionLastColumn);

                boolean namedInsideMerged = isNamedRangeInsideMergeRegion(
                        rangeFirstRow, rangeFirstColumn, rangeLastRow, rangeLastColumn,
                        regionFirstRow, regionFirstColumn, regionLastRow, regionLastColumn);

                if (mergedInsideNamed || namedInsideMerged) {
                    String name = aNamedRange.getNameName();
                    SheetRange sheetRange = new SheetRange(mergedRegion, currentSheet.getSheetName());
                    if (mergeRegionsForRangeNames.get(name) == null) {
                        ArrayList<SheetRange> list = new ArrayList<>();
                        list.add(sheetRange);
                        mergeRegionsForRangeNames.put(name, list);
                    } else {
                        mergeRegionsForRangeNames.get(name).add(sheetRange);
                    }
                }
            }
        }
    }
}
 
Example #29
Source File: StreamingWorkbook.java    From excel-streaming-reader with Apache License 2.0 4 votes vote down vote up
/**
 * Not supported
 */
@Override
public SpreadsheetVersion getSpreadsheetVersion() {
  throw new UnsupportedOperationException();
}
 
Example #30
Source File: Area.java    From yarg with Apache License 2.0 4 votes vote down vote up
public AreaReference toAreaReference() {
    return new AreaReference(topLeft.toCellReference(), bottomRight.toCellReference(), SpreadsheetVersion.EXCEL97);
}