sheet.java

来自「EXCEL read and write」· Java 代码 · 共 1,758 行 · 第 1/5 页

JAVA
1,758
字号
            Record rec = (Record) ((Record) rb).clone();            clonedRecords.add(rec);        }        return createSheet(new RecordStream(clonedRecords, 0));    }    /**     * Creates a sheet with all the usual records minus values and the "index"     * record (not required).  Sets the location pointer to where the first value     * records should go.  Use this to create a sheet from "scratch".     *     * @return Sheet object with all values set to defaults     */    public static Sheet createSheet() {        return new Sheet();    }    private Sheet() {        _mergedCellsTable = new MergedCellsTable();        records = new ArrayList(32);        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet createsheet from scratch called");        records.add(createBOF());        records.add(createCalcMode());        records.add(createCalcCount() );        records.add(createRefMode() );        records.add(createIteration() );        records.add(createDelta() );        records.add(createSaveRecalc() );        records.add(createPrintHeaders() );        printGridlines = createPrintGridlines();        records.add( printGridlines );        gridset = createGridset();        records.add( gridset );        _gutsRecord = createGuts();        records.add( _gutsRecord );        defaultrowheight = createDefaultRowHeight();        records.add( defaultrowheight );        records.add( createWSBool() );        // 'Page Settings Block'        _psBlock = new PageSettingsBlock();        records.add(_psBlock);        // 'Worksheet Protection Block' (after 'Page Settings Block' and before DEFCOLWIDTH)        // PROTECT record normally goes here, don't add yet since the flag is initially false        defaultcolwidth = createDefaultColWidth();        records.add( defaultcolwidth);        ColumnInfoRecordsAggregate columns = new ColumnInfoRecordsAggregate();        records.add( columns );        _columnInfos = columns;        _dimensions = createDimensions();        records.add(_dimensions);        _rowsAggregate = new RowRecordsAggregate();        records.add(_rowsAggregate);        // 'Sheet View Settings'        records.add(windowTwo = createWindowTwo());        selection = createSelection();        records.add(selection);        records.add(_mergedCellsTable); // MCT comes after 'Sheet View Settings'        records.add(EOFRecord.instance);        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet createsheet from scratch exit");    }    public RowRecordsAggregate getRowsAggregate() {        return _rowsAggregate;    }    private MergedCellsTable getMergedRecords() {        // always present        return _mergedCellsTable;    }    /**     * Updates formulas in cells and conditional formats due to moving of cells     * @param externSheetIndex the externSheet index of this sheet     */    public void updateFormulasAfterCellShift(FormulaShifter shifter, int externSheetIndex) {        getRowsAggregate().updateFormulasAfterRowShift(shifter, externSheetIndex);        getConditionalFormattingTable().updateFormulasAfterCellShift(shifter, externSheetIndex);        // TODO - adjust data validations    }    public int addMergedRegion(int rowFrom, int colFrom, int rowTo, int colTo) {        // Validate input        if (rowTo < rowFrom) {            throw new IllegalArgumentException("The 'to' row (" + rowTo                    + ") must not be less than the 'from' row (" + rowFrom + ")");        }        if (colTo < colFrom) {            throw new IllegalArgumentException("The 'to' col (" + colTo                    + ") must not be less than the 'from' col (" + colFrom + ")");        }        MergedCellsTable mrt = getMergedRecords();        mrt.addArea(rowFrom, colFrom, rowTo, colTo);        return mrt.getNumberOfMergedRegions()-1;    }    public void removeMergedRegion(int index)    {        //safety checks        MergedCellsTable mrt = getMergedRecords();        if (index >= mrt.getNumberOfMergedRegions()) {            return;        }        mrt.remove(index);    }    public CellRangeAddress getMergedRegionAt(int index) {        //safety checks        MergedCellsTable mrt = getMergedRecords();        if (index >=  mrt.getNumberOfMergedRegions()) {            return null;        }        return mrt.get(index);    }    public int getNumMergedRegions() {        return getMergedRecords().getNumberOfMergedRegions();    }    public ConditionalFormattingTable getConditionalFormattingTable() {        if (condFormatting == null) {            condFormatting = new ConditionalFormattingTable();            RecordOrderer.addNewSheetRecord(records, condFormatting);        }        return condFormatting;    }    /**     * Per an earlier reported bug in working with Andy Khan's excel read library.  This     * sets the values in the sheet's DimensionsRecord object to be correct.  Excel doesn't     * really care, but we want to play nice with other libraries.     *     * @see org.apache.poi.hssf.record.DimensionsRecord     */    public void setDimensions(int firstrow, short firstcol, int lastrow,                              short lastcol)    {        if (log.check( POILogger.DEBUG ))        {            log.log(POILogger.DEBUG, "Sheet.setDimensions");            log.log(POILogger.DEBUG,                    (new StringBuffer("firstrow")).append(firstrow)                        .append("firstcol").append(firstcol).append("lastrow")                        .append(lastrow).append("lastcol").append(lastcol)                        .toString());        }        _dimensions.setFirstCol(firstcol);        _dimensions.setFirstRow(firstrow);        _dimensions.setLastCol(lastcol);        _dimensions.setLastRow(lastrow);        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet.setDimensions exiting");    }    public void visitContainedRecords(RecordVisitor rv, int offset) {        PositionTrackingVisitor ptv = new PositionTrackingVisitor(rv, offset);        boolean haveSerializedIndex = false;        for (int k = 0; k < records.size(); k++)        {            RecordBase record = (RecordBase) records.get(k);            if (record instanceof RecordAggregate) {                RecordAggregate agg = (RecordAggregate) record;                agg.visitContainedRecords(ptv);            } else {                ptv.visitRecord((Record) record);            }            // If the BOF record was just serialized then add the IndexRecord            if (record instanceof BOFRecord) {              if (!haveSerializedIndex) {                haveSerializedIndex = true;                // Add an optional UncalcedRecord. However, we should add                //  it in only the once, after the sheet's own BOFRecord.                // If there are diagrams, they have their own BOFRecords,                //  and one shouldn't go in after that!                if (_isUncalced) {                    ptv.visitRecord(new UncalcedRecord());                }                //Can there be more than one BOF for a sheet? If not then we can                //remove this guard. So be safe it is left here.                if (_rowsAggregate != null) {                    // find forward distance to first RowRecord                    int initRecsSize = getSizeOfInitialSheetRecords(k);                    int currentPos = ptv.getPosition();                    ptv.visitRecord(_rowsAggregate.createIndexRecord(currentPos, initRecsSize));                }              }            }        }    }    /**     * 'initial sheet records' are between INDEX and the 'Row Blocks'     * @param bofRecordIndex index of record after which INDEX record is to be placed     * @return count of bytes from end of INDEX record to first ROW record.     */    private int getSizeOfInitialSheetRecords(int bofRecordIndex) {        int result = 0;        // start just after BOF record (INDEX is not present in this list)        for (int j = bofRecordIndex + 1; j < records.size(); j++) {            RecordBase tmpRec = (RecordBase) records.get(j);            if (tmpRec instanceof RowRecordsAggregate) {                break;            }            result += tmpRec.getRecordSize();        }        if (_isUncalced) {            result += UncalcedRecord.getStaticRecordSize();        }        return result;    }    /**     * Adds a value record to the sheet's contained binary records     * (i.e. LabelSSTRecord or NumberRecord).     * <P>     * This method is "loc" sensitive.  Meaning you need to set LOC to where you     * want it to start searching.  If you don't know do this: setLoc(getDimsLoc).     * When adding several rows you can just start at the last one by leaving loc     * at what this sets it to.     *     * @param row the row to add the cell value to     * @param col the cell value record itself.     */    public void addValueRecord(int row, CellValueRecordInterface col) {        if(log.check(POILogger.DEBUG)) {          log.log(POILogger.DEBUG, "add value record  row" + row);        }        DimensionsRecord d = _dimensions;        if (col.getColumn() > d.getLastCol())        {            d.setLastCol(( short ) (col.getColumn() + 1));        }        if (col.getColumn() < d.getFirstCol())        {            d.setFirstCol(col.getColumn());        }        _rowsAggregate.insertCell(col);    }    /**     * remove a value record from the records array.     *     * This method is not loc sensitive, it resets loc to = dimsloc so no worries.     *     * @param row - the row of the value record you wish to remove     * @param col - a record supporting the CellValueRecordInterface.     * @see org.apache.poi.hssf.record.CellValueRecordInterface     */    public void removeValueRecord(int row, CellValueRecordInterface col) {        log.logFormatted(POILogger.DEBUG, "remove value record row %",                         new int[]{row } );        _rowsAggregate.removeCell(col);    }    /**     * replace a value record from the records array.     *     * This method is not loc sensitive, it resets loc to = dimsloc so no worries.     *     * @param newval - a record supporting the CellValueRecordInterface.  this will replace     *                the cell value with the same row and column.  If there isn't one, one will     *                be added.     */    public void replaceValueRecord(CellValueRecordInterface newval) {        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "replaceValueRecord ");        //The ValueRecordsAggregate use a tree map underneath.        //The tree Map uses the CellValueRecordInterface as both the        //key and the value, if we dont do a remove, then        //the previous instance of the key is retained, effectively using        //double the memory        _rowsAggregate.removeCell(newval);        _rowsAggregate.insertCell(newval);    }    /**     * Adds a row record to the sheet     *     * <P>     * This method is "loc" sensitive.  Meaning you need to set LOC to where you     * want it to start searching.  If you don't know do this: setLoc(getDimsLoc).     * When adding several rows you can just start at the last one by leaving loc     * at what this sets it to.     *     * @param row the row record to be added     * @see #setLoc(int)     */    public void addRow(RowRecord row)    {        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "addRow ");        DimensionsRecord d = _dimensions;        if (row.getRowNumber() >= d.getLastRow())        {            d.setLastRow(row.getRowNumber() + 1);        }        if (row.getRowNumber() < d.getFirstRow())        {            d.setFirstRow(row.getRowNumber());        }        //If the row exists remove it, so that any cells attached to the row are removed        RowRecord existingRow = _rowsAggregate.getRow(row.getRowNumber());        if (existingRow != null) {            _rowsAggregate.removeRow(existingRow);        }        _rowsAggregate.insertRow(row);        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "exit addRow");    }    /**     * Removes a row record     *     * This method is not loc sensitive, it resets loc to = dimsloc so no worries.     *     * @param row  the row record to remove     */    public void removeRow(RowRecord row) {        _rowsAggregate.removeRow(row);    }    /**     * get the NEXT value record (from LOC).  The first record that is a value record     * (starting at LOC) will be returned.     *     * <P>     * This method is "loc" sensitive.  Meaning you need to set LOC to where you     * want it to start searching.  If you don't know do this: setLoc(getDimsLoc).     * When adding several rows you can just start at the last one by leaving loc

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?