⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sheet.java

📁 java 读写word excel ppt
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
     * only the record offset is assumed to be 0.     *     * @param records  array containing those records in the sheet in sequence (normally obtained from RecordFactory)     * @param sheetnum integer specifying the sheet's number (0,1 or 2 in this release)     * @return Sheet object     */    public static Sheet createSheet(List records, int sheetnum)    {        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG,                    "Sheet createSheet (exisiting file) assumed offset 0");        return createSheet(records, sheetnum, 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()    {        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet createsheet from scratch called");        Sheet     retval  = new Sheet();        ArrayList records = new ArrayList(30);        records.add(retval.createBOF());        // records.add(retval.createIndex());        records.add(retval.createCalcMode());        records.add(retval.createCalcCount() );        records.add( retval.createRefMode() );        records.add( retval.createIteration() );        records.add( retval.createDelta() );        records.add( retval.createSaveRecalc() );        records.add( retval.createPrintHeaders() );        retval.printGridlines = (PrintGridlinesRecord) retval.createPrintGridlines();        records.add( retval.printGridlines );        retval.gridset = (GridsetRecord) retval.createGridset();        records.add( retval.gridset );        records.add( retval.createGuts() );        retval.defaultrowheight =                (DefaultRowHeightRecord) retval.createDefaultRowHeight();        records.add( retval.defaultrowheight );        records.add( retval.createWSBool() );        retval.rowBreaks = new PageBreakRecord(PageBreakRecord.HORIZONTAL_SID);        records.add(retval.rowBreaks);        retval.colBreaks = new PageBreakRecord(PageBreakRecord.VERTICAL_SID);        records.add(retval.colBreaks);                retval.header = (HeaderRecord) retval.createHeader();        records.add( retval.header );                retval.footer = (FooterRecord) retval.createFooter();        records.add( retval.footer );        records.add( retval.createHCenter() );        records.add( retval.createVCenter() );        retval.printSetup = (PrintSetupRecord) retval.createPrintSetup();        records.add( retval.printSetup );        retval.defaultcolwidth =                (DefaultColWidthRecord) retval.createDefaultColWidth();        records.add( retval.defaultcolwidth);        ColumnInfoRecordsAggregate columns = new ColumnInfoRecordsAggregate();        records.add( columns );        retval.columns = columns;        retval.dims    = ( DimensionsRecord ) retval.createDimensions();        records.add(retval.dims);        retval.dimsloc = records.size()-1;        records.add(retval.windowTwo = retval.createWindowTwo());        retval.setLoc(records.size() - 1);        retval.selection =                 (SelectionRecord) retval.createSelection();        records.add(retval.selection);		retval.protect = (ProtectRecord) retval.createProtect();		records.add(retval.protect);        records.add(retval.createEOF());        retval.records = records;        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet createsheet from scratch exit");        return retval;    }    private void checkCells()    {        if (cells == null)        {            cells = new ValueRecordsAggregate();            records.add(getDimsLoc() + 1, cells);        }    }    private void checkRows()    {        if (rows == null)        {            rows = new RowRecordsAggregate();            records.add(getDimsLoc() + 1, rows);        }    }    //public int addMergedRegion(short rowFrom, short colFrom, short rowTo,    public int addMergedRegion(int rowFrom, short colFrom, int rowTo,                               short colTo)    {        if (merged == null || merged.getNumAreas() == 1027)        {            merged = ( MergeCellsRecord ) createMergedCells();            mergedRecords.add(merged);                        records.add(records.size() - 1, merged);        }        merged.addArea(rowFrom, colFrom, rowTo, colTo);        return numMergedRegions++;     }    public void removeMergedRegion(int index)    {        //safety checks        if (index >= numMergedRegions || mergedRecords.size() == 0)           return;                    int pos = 0;        int startNumRegions = 0;                //optimisation for current record        if (numMergedRegions - index < merged.getNumAreas())        {            pos = mergedRecords.size() - 1;            startNumRegions = numMergedRegions - merged.getNumAreas();         }        else        {            for (int n = 0; n < mergedRecords.size(); n++)            {                MergeCellsRecord record = (MergeCellsRecord) mergedRecords.get(n);                if (startNumRegions + record.getNumAreas() > index)                {                    pos = n;                    break;                }                startNumRegions += record.getNumAreas();             }        }        MergeCellsRecord rec = (MergeCellsRecord) mergedRecords.get(pos);        rec.removeAreaAt(index - startNumRegions);        numMergedRegions--;        if (rec.getNumAreas() == 0)        {			mergedRecords.remove(pos);			//get rid of the record from the sheet			records.remove(merged);                        if (merged == rec) {            	//pull up the LAST record for operations when we finally            	//support continue records for mergedRegions            	if (mergedRecords.size() > 0) {            		merged = (MergeCellsRecord) mergedRecords.get(mergedRecords.size() - 1);            	} else {            		merged = null;            	}            }        }    }    public MergeCellsRecord.MergedRegion getMergedRegionAt(int index)    {        //safety checks        if (index >= numMergedRegions || mergedRecords.size() == 0)            return null;                    int pos = 0;        int startNumRegions = 0;                //optimisation for current record        if (numMergedRegions - index < merged.getNumAreas())        {            pos = mergedRecords.size() - 1;            startNumRegions = numMergedRegions - merged.getNumAreas();        }        else        {            for (int n = 0; n < mergedRecords.size(); n++)            {                MergeCellsRecord record = (MergeCellsRecord) mergedRecords.get(n);                if (startNumRegions + record.getNumAreas() > index)                {                    pos = n;                    break;                }                startNumRegions += record.getNumAreas();             }        }        return ((MergeCellsRecord) mergedRecords.get(pos)).getAreaAt(index - startNumRegions);    }    public int getNumMergedRegions()    {        return numMergedRegions;    }    /**     * Returns the number of low level binary records in this sheet.  This adjusts things for the so called     * AgregateRecords.     *     * @see org.apache.poi.hssf.record.Record     */    public int getNumRecords()    {        checkCells();        checkRows();        if (log.check( POILogger.DEBUG ))        {            log.log(POILogger.DEBUG, "Sheet.getNumRecords");            log.logFormatted(POILogger.DEBUG, "returning % + % + % - 2 = %", new int[]            {                records.size(), cells.getPhysicalNumberOfCells(),                rows.getPhysicalNumberOfRows(),                records.size() + cells.getPhysicalNumberOfCells()                + rows.getPhysicalNumberOfRows() - 2            });        }        return records.size() + cells.getPhysicalNumberOfCells()               + rows.getPhysicalNumberOfRows() - 2;    }    /**     * 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(short firstrow, short firstcol, short lastrow,    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());        }        dims.setFirstCol(firstcol);        dims.setFirstRow(firstrow);        dims.setLastCol(lastcol);        dims.setLastRow(lastrow);        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet.setDimensions exiting");    }    /**     * set the locator for where we should look for the next value record.  The     * algorythm will actually start here and find the correct location so you     * can set this to 0 and watch performance go down the tubes but it will work.     * After a value is set this is automatically advanced.  Its also set by the     * create method.  So you probably shouldn't mess with this unless you have     * a compelling reason why or the help for the method you're calling says so.     * Check the other methods for whether they care about     * the loc pointer.  Many of the "modify" and "remove" methods re-initialize this     * to "dimsloc" which is the location of the Dimensions Record and presumably the     * start of the value section (at or around 19 dec).     *     * @param loc the record number to start at     *     */    public void setLoc(int loc)    {        valueRecIterator = null;        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "sheet.setLoc(): " + loc);        this.loc = loc;    }    /**     * Returns the location pointer to the first record to look for when adding rows/values     *     */    public int getLoc()    {        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "sheet.getLoc():" + loc);        return loc;    }    /**     * Set the preoffset when using DBCELL records (currently unused) - this is     * the position of this sheet within the whole file.     *     * @param offset the offset of the sheet's BOF within the file.     */    public void setPreOffset(int offset)    {        this.preoffset = offset;    }    /**     * get the preoffset when using DBCELL records (currently unused) - this is     * the position of this sheet within the whole file.     *     * @return offset the offset of the sheet's BOF within the file.     */    public int getPreOffset()    {        return preoffset;    }    /**     * Serializes all records in the sheet into one big byte array.  Use this to write     * the sheet out.     *     * @param offset to begin write at     * @param data   array containing the binary representation of the records in this sheet     *     */    public int serialize(int offset, byte [] data)    {        if (log.check( POILogger.DEBUG ))            log.log(POILogger.DEBUG, "Sheet.serialize using offsets");        int pos       = offset;        boolean haveSerializedIndex = false;        for (int k = 0; k < records.size(); k++)        {            Record record = (( Record ) records.get(k));                        //Once the rows have been found in the list of records, start            //writing out the blocked row information. This includes the DBCell references            if (record instanceof RowRecordsAggregate) {              pos += ((RowRecordsAggregate)record).serialize(pos, data, cells);   // rec.length;            } else if (record instanceof ValueRecordsAggregate) {              //Do nothing here. The records were serialized during the RowRecordAggregate block serialization            } else {              pos += record.serialize(pos, data );   // rec.length;            }            //If the BOF record was just serialized then add the IndexRecord            if (record.getSid() == BOFRecord.sid) {              //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 (rows != null && !haveSerializedIndex) {                haveSerializedIndex = true;                pos += serializeIndexRecord(k, pos, data);              }            }            //// uncomment to test record sizes //////            System.out.println( record.getClass().getName() );//            byte[] data2 = new byte[record.getRecordSize()];//            record.serialize(0, data2 );   // rec.length;//            if (LittleEndian.getUShort(data2, 2) != record.getRecordSize() - 4//                    && record instanceof RowRecordsAggregate == false//                    && record instanceof ValueRecordsAggregate == false//                    && record instanceof EscherAggregate == false)//            {//                throw new RuntimeException("Blah!!!  Size off by " + ( LittleEndian.getUShort(data2, 2) - record.getRecordSize() - 4) + " records.");//            }//asd:            int len = record.serialize(pos + offset, data );

⌨️ 快捷键说明

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