hssfcell.java

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

JAVA
1,104
字号
/* ====================================================================   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.hssf.usermodel;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import org.apache.poi.hssf.model.HSSFFormulaParser;import org.apache.poi.hssf.model.Sheet;import org.apache.poi.hssf.model.Workbook;import org.apache.poi.hssf.record.BlankRecord;import org.apache.poi.hssf.record.BoolErrRecord;import org.apache.poi.hssf.record.CellValueRecordInterface;import org.apache.poi.hssf.record.CommonObjectDataSubRecord;import org.apache.poi.hssf.record.DrawingRecord;import org.apache.poi.hssf.record.EOFRecord;import org.apache.poi.hssf.record.ExtendedFormatRecord;import org.apache.poi.hssf.record.FormulaRecord;import org.apache.poi.hssf.record.HyperlinkRecord;import org.apache.poi.hssf.record.LabelSSTRecord;import org.apache.poi.hssf.record.NoteRecord;import org.apache.poi.hssf.record.NumberRecord;import org.apache.poi.hssf.record.ObjRecord;import org.apache.poi.hssf.record.Record;import org.apache.poi.hssf.record.RecordBase;import org.apache.poi.hssf.record.StringRecord;import org.apache.poi.hssf.record.SubRecord;import org.apache.poi.hssf.record.TextObjectRecord;import org.apache.poi.hssf.record.UnicodeString;import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;import org.apache.poi.hssf.record.formula.Ptg;import org.apache.poi.hssf.record.formula.eval.ErrorEval;/** * High level representation of a cell in a row of a spreadsheet. * Cells can be numeric, formula-based or string-based (text).  The cell type * specifies this.  String cells cannot conatin numbers and numeric cells cannot * contain strings (at least according to our model).  Client apps should do the * conversions themselves.  Formula cells have the formula string, as well as * the formula result, which can be numeric or string. * <p> * Cells should have their number (0 based) before being added to a row.  Only * cells that have values should be added. * <p> * * @author  Andrew C. Oliver (acoliver at apache dot org) * @author  Dan Sherman (dsherman at isisph.com) * @author  Brian Sanders (kestrel at burdell dot org) Active Cell support * @author  Yegor Kozlov cell comments support * @version 1.0-pre */public final class HSSFCell {    /** Numeric Cell type (0) @see #setCellType(int) @see #getCellType() */    public final static int CELL_TYPE_NUMERIC = 0;    /** String  Cell type (1) @see #setCellType(int) @see #getCellType() */    public final static int CELL_TYPE_STRING  = 1;    /** Formula Cell type (2) @see #setCellType(int) @see #getCellType() */    public final static int CELL_TYPE_FORMULA = 2;    /** Blank   Cell type (3) @see #setCellType(int) @see #getCellType() */    public final static int CELL_TYPE_BLANK   = 3;    /** Boolean Cell type (4) @see #setCellType(int) @see #getCellType() */    public final static int CELL_TYPE_BOOLEAN = 4;    /** Error   Cell type (5) @see #setCellType(int) @see #getCellType() */    public final static int CELL_TYPE_ERROR   = 5;    public final static short        ENCODING_UNCHANGED          = -1;    public final static short        ENCODING_COMPRESSED_UNICODE = 0;    public final static short        ENCODING_UTF_16             = 1;    private final HSSFWorkbook       book;    private final HSSFSheet          sheet;    private int                      cellType;    private HSSFRichTextString       stringValue;    private CellValueRecordInterface record;    private HSSFComment              comment;    /**     * Creates new Cell - Should only be called by HSSFRow.  This creates a cell     * from scratch.     * <p>     * When the cell is initially created it is set to CELL_TYPE_BLANK. Cell types     * can be changed/overwritten by calling setCellValue with the appropriate     * type as a parameter although conversions from one type to another may be     * prohibited.     *     * @param book - Workbook record of the workbook containing this cell     * @param sheet - Sheet record of the sheet containing this cell     * @param row   - the row of this cell     * @param col   - the column for this cell     *     * @see org.apache.poi.hssf.usermodel.HSSFRow#createCell(short)     */    protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col)    {        checkBounds(col);        stringValue  = null;        this.book    = book;        this.sheet   = sheet;        // Relying on the fact that by default the cellType is set to 0 which        // is different to CELL_TYPE_BLANK hence the following method call correctly        // creates a new blank cell.        short xfindex = sheet.getSheet().getXFIndexForColAt(col);        setCellType(CELL_TYPE_BLANK, false, row, col,xfindex);    }    public HSSFSheet getSheet() {        return sheet;    }    /**     * Creates new Cell - Should only be called by HSSFRow.  This creates a cell     * from scratch.     *     * @param book - Workbook record of the workbook containing this cell     * @param sheet - Sheet record of the sheet containing this cell     * @param row   - the row of this cell     * @param col   - the column for this cell     * @param type  - CELL_TYPE_NUMERIC, CELL_TYPE_STRING, CELL_TYPE_FORMULA, CELL_TYPE_BLANK,     *                CELL_TYPE_BOOLEAN, CELL_TYPE_ERROR     *                Type of cell     * @see org.apache.poi.hssf.usermodel.HSSFRow#createCell(short,int)     */    protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, int row, short col,                       int type)    {        checkBounds(col);        cellType     = -1; // Force 'setCellType' to create a first Record        stringValue  = null;        this.book    = book;        this.sheet   = sheet;        short xfindex = sheet.getSheet().getXFIndexForColAt(col);        setCellType(type,false,row,col,xfindex);    }    /**     * Creates an HSSFCell from a CellValueRecordInterface.  HSSFSheet uses this when     * reading in cells from an existing sheet.     *     * @param book - Workbook record of the workbook containing this cell     * @param sheet - Sheet record of the sheet containing this cell     * @param cval - the Cell Value Record we wish to represent     */    protected HSSFCell(HSSFWorkbook book, HSSFSheet sheet, CellValueRecordInterface cval) {        record      = cval;        cellType    = determineType(cval);        stringValue = null;        this.book   = book;        this.sheet  = sheet;        switch (cellType)        {            case CELL_TYPE_STRING :                stringValue = new HSSFRichTextString(book.getWorkbook(), (LabelSSTRecord ) cval);                break;            case CELL_TYPE_BLANK :                break;            case CELL_TYPE_FORMULA :                stringValue=new HSSFRichTextString(((FormulaRecordAggregate) cval).getStringValue());                break;        }        ExtendedFormatRecord xf = book.getWorkbook().getExFormatAt(cval.getXFIndex());        setCellStyle(new HSSFCellStyle(cval.getXFIndex(), xf, book));    }    /**     * used internally -- given a cell value record, figure out its type     */    private static int determineType(CellValueRecordInterface cval) {        if (cval instanceof FormulaRecordAggregate) {            return HSSFCell.CELL_TYPE_FORMULA;        }        // all others are plain BIFF records        Record record = ( Record ) cval;        switch (record.getSid()) {            case NumberRecord.sid :   return HSSFCell.CELL_TYPE_NUMERIC;            case BlankRecord.sid :    return HSSFCell.CELL_TYPE_BLANK;            case LabelSSTRecord.sid : return HSSFCell.CELL_TYPE_STRING;            case BoolErrRecord.sid :                BoolErrRecord boolErrRecord = ( BoolErrRecord ) record;                return boolErrRecord.isBoolean()                         ? HSSFCell.CELL_TYPE_BOOLEAN                         : HSSFCell.CELL_TYPE_ERROR;        }        throw new RuntimeException("Bad cell value rec (" + cval.getClass().getName() + ")");    }    /**     * Returns the Workbook that this Cell is bound to     * @return     */    protected Workbook getBoundWorkbook() {        return book.getWorkbook();    }    /**     * @return the (zero based) index of the row containing this cell     */    public int getRowIndex() {        return record.getRow();    }    /**     * Set the cell's number within the row (0 based).     * @param num  short the cell number     * @deprecated (Jan 2008) Doesn't update the row's idea of what cell this is, use {@link HSSFRow#moveCell(HSSFCell, short)} instead     */    public void setCellNum(short num)    {        record.setColumn(num);    }    /**     * Updates the cell record's idea of what     *  column it belongs in (0 based)     * @param num the new cell number     */    protected void updateCellNum(short num)    {        record.setColumn(num);    }    /**     * @deprecated (Oct 2008) use {@link #getColumnIndex()}     */    public short getCellNum() {        return (short) getColumnIndex();    }        public int getColumnIndex() {    	return record.getColumn() & 0xFFFF;    }    /**     * set the cells type (numeric, formula or string)     * @see #CELL_TYPE_NUMERIC     * @see #CELL_TYPE_STRING     * @see #CELL_TYPE_FORMULA     * @see #CELL_TYPE_BLANK     * @see #CELL_TYPE_BOOLEAN     * @see #CELL_TYPE_ERROR     */    public void setCellType(int cellType)    {        int row=record.getRow();        short col=record.getColumn();        short styleIndex=record.getXFIndex();        setCellType(cellType, true, row, col, styleIndex);    }    /**     * sets the cell type. The setValue flag indicates whether to bother about     *  trying to preserve the current value in the new record if one is created.     *  <p>     *  The @see #setCellValue method will call this method with false in setValue     *  since it will overwrite the cell value later     *     */    private void setCellType(int cellType, boolean setValue, int row,short col, short styleIndex)    {        if (cellType > CELL_TYPE_ERROR)        {            throw new RuntimeException("I have no idea what type that is!");        }        switch (cellType)        {            case CELL_TYPE_FORMULA :                FormulaRecordAggregate frec;                if (cellType != this.cellType) {                    frec = sheet.getSheet().getRowsAggregate().createFormula(row, col);                } else {                    frec = (FormulaRecordAggregate) record;                    frec.setRow(row);                    frec.setColumn(col);                }                if (setValue)                {                    frec.getFormulaRecord().setValue(getNumericCellValue());                }                frec.setXFIndex(styleIndex);                record = frec;                break;            case CELL_TYPE_NUMERIC :                NumberRecord nrec = null;                if (cellType != this.cellType)                {                    nrec = new NumberRecord();                }                else                {                    nrec = ( NumberRecord ) record;                }                nrec.setColumn(col);                if (setValue)                {                    nrec.setValue(getNumericCellValue());                }                nrec.setXFIndex(styleIndex);                nrec.setRow(row);                record = nrec;                break;            case CELL_TYPE_STRING :                LabelSSTRecord lrec = null;                if (cellType != this.cellType)                {                    lrec = new LabelSSTRecord();                }                else                {                    lrec = ( LabelSSTRecord ) record;                }                lrec.setColumn(col);                lrec.setRow(row);                lrec.setXFIndex(styleIndex);                if (setValue)                {                    if ((getStringCellValue() != null)                            && (!getStringCellValue().equals("")))                    {                        int sst = 0;                        UnicodeString str = getRichStringCellValue().getUnicodeString();//jmh                        if (encoding == ENCODING_COMPRESSED_UNICODE)//jmh                        {//                      jmh                            str.setCompressedUnicode();//                      jmh                        } else if (encoding == ENCODING_UTF_16)//                      jmh                        {//                      jmh                            str.setUncompressedUnicode();//                      jmh                        }                        sst = book.getWorkbook().addSSTString(str);                        lrec.setSSTIndex(sst);                        getRichStringCellValue().setUnicodeString(book.getWorkbook().getSSTString(sst));                    }                }

⌨️ 快捷键说明

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