Search in sources :

Example 1 with NumberRecord

use of org.apache.poi.hssf.record.NumberRecord in project poi by apache.

the class HSSFCell method setCellType.

/**
     * 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(CellType cellType, boolean setValue, int row, short col, short styleIndex) {
    switch(cellType) {
        case FORMULA:
            FormulaRecordAggregate frec;
            if (cellType != _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 NUMERIC:
            NumberRecord nrec = null;
            if (cellType != _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 STRING:
            LabelSSTRecord lrec;
            if (cellType == _cellType) {
                lrec = (LabelSSTRecord) _record;
            } else {
                lrec = new LabelSSTRecord();
                lrec.setColumn(col);
                lrec.setRow(row);
                lrec.setXFIndex(styleIndex);
            }
            if (setValue) {
                String str = convertCellValueToString();
                if (str == null) {
                    // bug 55668: don't try to store null-string when formula
                    // results in empty/null value
                    setCellType(CellType.BLANK, false, row, col, styleIndex);
                    return;
                } else {
                    int sstIndex = _book.getWorkbook().addSSTString(new UnicodeString(str));
                    lrec.setSSTIndex(sstIndex);
                    UnicodeString us = _book.getWorkbook().getSSTString(sstIndex);
                    _stringValue = new HSSFRichTextString();
                    _stringValue.setUnicodeString(us);
                }
            }
            _record = lrec;
            break;
        case BLANK:
            BlankRecord brec = null;
            if (cellType != _cellType) {
                brec = new BlankRecord();
            } else {
                brec = (BlankRecord) _record;
            }
            brec.setColumn(col);
            // During construction the cellStyle may be null for a Blank cell.
            brec.setXFIndex(styleIndex);
            brec.setRow(row);
            _record = brec;
            break;
        case BOOLEAN:
            BoolErrRecord boolRec = null;
            if (cellType != _cellType) {
                boolRec = new BoolErrRecord();
            } else {
                boolRec = (BoolErrRecord) _record;
            }
            boolRec.setColumn(col);
            if (setValue) {
                boolRec.setValue(convertCellValueToBoolean());
            }
            boolRec.setXFIndex(styleIndex);
            boolRec.setRow(row);
            _record = boolRec;
            break;
        case ERROR:
            BoolErrRecord errRec = null;
            if (cellType != _cellType) {
                errRec = new BoolErrRecord();
            } else {
                errRec = (BoolErrRecord) _record;
            }
            errRec.setColumn(col);
            if (setValue) {
                errRec.setValue(FormulaError.VALUE.getCode());
            }
            errRec.setXFIndex(styleIndex);
            errRec.setRow(row);
            _record = errRec;
            break;
        default:
            throw new IllegalStateException("Invalid cell type: " + cellType);
    }
    if (cellType != _cellType && // Special Value to indicate an uninitialized Cell
    _cellType != CellType._NONE) {
        _sheet.getSheet().replaceValueRecord(_record);
    }
    _cellType = cellType;
}
Also used : BoolErrRecord(org.apache.poi.hssf.record.BoolErrRecord) BlankRecord(org.apache.poi.hssf.record.BlankRecord) UnicodeString(org.apache.poi.hssf.record.common.UnicodeString) FormulaRecordAggregate(org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate) RichTextString(org.apache.poi.ss.usermodel.RichTextString) UnicodeString(org.apache.poi.hssf.record.common.UnicodeString) NumberRecord(org.apache.poi.hssf.record.NumberRecord) LabelSSTRecord(org.apache.poi.hssf.record.LabelSSTRecord)

Example 2 with NumberRecord

use of org.apache.poi.hssf.record.NumberRecord in project poi by apache.

the class TestRowRecordsAggregate method testUnknownContinue_bug46280.

/**
	 * This problem was noted as the overt symptom of bug 46280.  The logic for skipping {@link
	 * UnknownRecord}s in the constructor {@link RowRecordsAggregate} did not allow for the
	 * possibility of tailing {@link ContinueRecord}s.<br/>
	 * The functionality change being tested here is actually not critical to the overall fix
	 * for bug 46280, since the fix involved making sure the that offending <i>PivotTable</i>
	 * records do not get into {@link RowRecordsAggregate}.<br/>
	 * This fix in {@link RowRecordsAggregate} was implemented anyway since any {@link
	 * UnknownRecord} has the potential of being 'continued'.
	 */
@Test
public void testUnknownContinue_bug46280() {
    Record[] inRecs = { new RowRecord(0), new NumberRecord(), new UnknownRecord(0x5555, "dummydata".getBytes(LocaleUtil.CHARSET_1252)), new ContinueRecord("moredummydata".getBytes(LocaleUtil.CHARSET_1252)) };
    RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0);
    RowRecordsAggregate rra;
    try {
        rra = new RowRecordsAggregate(rs, SharedValueManager.createEmpty());
    } catch (RuntimeException e) {
        if (e.getMessage().startsWith("Unexpected record type")) {
            fail("Identified bug 46280a");
        }
        throw e;
    }
    RecordCollector rv = new RecordCollector();
    rra.visitContainedRecords(rv);
    Record[] outRecs = rv.getRecords();
    assertEquals(5, outRecs.length);
}
Also used : RecordStream(org.apache.poi.hssf.model.RecordStream) RecordCollector(org.apache.poi.hssf.usermodel.RecordInspector.RecordCollector) RowRecord(org.apache.poi.hssf.record.RowRecord) UnknownRecord(org.apache.poi.hssf.record.UnknownRecord) ContinueRecord(org.apache.poi.hssf.record.ContinueRecord) Record(org.apache.poi.hssf.record.Record) NumberRecord(org.apache.poi.hssf.record.NumberRecord) UnknownRecord(org.apache.poi.hssf.record.UnknownRecord) ArrayRecord(org.apache.poi.hssf.record.ArrayRecord) ContinueRecord(org.apache.poi.hssf.record.ContinueRecord) TableRecord(org.apache.poi.hssf.record.TableRecord) RowRecord(org.apache.poi.hssf.record.RowRecord) SharedFormulaRecord(org.apache.poi.hssf.record.SharedFormulaRecord) FormulaRecord(org.apache.poi.hssf.record.FormulaRecord) NumberRecord(org.apache.poi.hssf.record.NumberRecord) Test(org.junit.Test)

Example 3 with NumberRecord

use of org.apache.poi.hssf.record.NumberRecord in project poi by apache.

the class TestHSSFEventFactory method testWithPasswordProtectedWorkbooks.

public void testWithPasswordProtectedWorkbooks() throws Exception {
    HSSFRequest req = new HSSFRequest();
    MockHSSFListener mockListen = new MockHSSFListener();
    req.addListenerForAllRecords(mockListen);
    // Without a password, can't be read
    Biff8EncryptionKey.setCurrentUserPassword(null);
    POIFSFileSystem fs = new POIFSFileSystem(openSample("xor-encryption-abc.xls"));
    HSSFEventFactory factory = new HSSFEventFactory();
    try {
        factory.processWorkbookEvents(req, fs);
        fail("Shouldn't be able to process protected workbook without the password");
    } catch (EncryptedDocumentException e) {
    }
    // With the password, is properly processed
    Biff8EncryptionKey.setCurrentUserPassword("abc");
    req = new HSSFRequest();
    mockListen = new MockHSSFListener();
    req.addListenerForAllRecords(mockListen);
    factory.processWorkbookEvents(req, fs);
    // Check we got the sheet and the contents
    Record[] recs = mockListen.getRecords();
    assertTrue(recs.length > 50);
    // Has one sheet, with values 1,2,3 in column A rows 1-3
    boolean hasSheet = false, hasA1 = false, hasA2 = false, hasA3 = false;
    for (Record r : recs) {
        if (r instanceof BoundSheetRecord) {
            BoundSheetRecord bsr = (BoundSheetRecord) r;
            assertEquals("Sheet1", bsr.getSheetname());
            hasSheet = true;
        }
        if (r instanceof NumberRecord) {
            NumberRecord nr = (NumberRecord) r;
            if (nr.getColumn() == 0 && nr.getRow() == 0) {
                assertEquals(1, (int) nr.getValue());
                hasA1 = true;
            }
            if (nr.getColumn() == 0 && nr.getRow() == 1) {
                assertEquals(2, (int) nr.getValue());
                hasA2 = true;
            }
            if (nr.getColumn() == 0 && nr.getRow() == 2) {
                assertEquals(3, (int) nr.getValue());
                hasA3 = true;
            }
        }
    }
    assertTrue("Sheet record not found", hasSheet);
    assertTrue("Numeric record for A1 not found", hasA1);
    assertTrue("Numeric record for A2 not found", hasA2);
    assertTrue("Numeric record for A3 not found", hasA3);
}
Also used : EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) POIFSFileSystem(org.apache.poi.poifs.filesystem.POIFSFileSystem) Record(org.apache.poi.hssf.record.Record) NumberRecord(org.apache.poi.hssf.record.NumberRecord) EOFRecord(org.apache.poi.hssf.record.EOFRecord) FeatHdrRecord(org.apache.poi.hssf.record.FeatHdrRecord) SelectionRecord(org.apache.poi.hssf.record.SelectionRecord) ContinueRecord(org.apache.poi.hssf.record.ContinueRecord) BoundSheetRecord(org.apache.poi.hssf.record.BoundSheetRecord) WindowTwoRecord(org.apache.poi.hssf.record.WindowTwoRecord) DVALRecord(org.apache.poi.hssf.record.DVALRecord) DVRecord(org.apache.poi.hssf.record.DVRecord) NumberRecord(org.apache.poi.hssf.record.NumberRecord) BoundSheetRecord(org.apache.poi.hssf.record.BoundSheetRecord)

Example 4 with NumberRecord

use of org.apache.poi.hssf.record.NumberRecord in project poi by apache.

the class XLS2CSVmra method processRecord.

/**
	 * Main HSSFListener method, processes events, and outputs the
	 *  CSV as the file is processed.
	 */
@Override
public void processRecord(Record record) {
    int thisRow = -1;
    int thisColumn = -1;
    String thisStr = null;
    switch(record.getSid()) {
        case BoundSheetRecord.sid:
            boundSheetRecords.add((BoundSheetRecord) record);
            break;
        case BOFRecord.sid:
            BOFRecord br = (BOFRecord) record;
            if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
                // Create sub workbook if required
                if (workbookBuildingListener != null && stubWorkbook == null) {
                    stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
                }
                // Output the worksheet name
                // Works by ordering the BSRs by the location of
                //  their BOFRecords, and then knowing that we
                //  process BOFRecords in byte offset order
                sheetIndex++;
                if (orderedBSRs == null) {
                    orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
                }
                output.println();
                output.println(orderedBSRs[sheetIndex].getSheetname() + " [" + (sheetIndex + 1) + "]:");
            }
            break;
        case SSTRecord.sid:
            sstRecord = (SSTRecord) record;
            break;
        case BlankRecord.sid:
            BlankRecord brec = (BlankRecord) record;
            thisRow = brec.getRow();
            thisColumn = brec.getColumn();
            thisStr = "";
            break;
        case BoolErrRecord.sid:
            BoolErrRecord berec = (BoolErrRecord) record;
            thisRow = berec.getRow();
            thisColumn = berec.getColumn();
            thisStr = "";
            break;
        case FormulaRecord.sid:
            FormulaRecord frec = (FormulaRecord) record;
            thisRow = frec.getRow();
            thisColumn = frec.getColumn();
            if (outputFormulaValues) {
                if (Double.isNaN(frec.getValue())) {
                    // Formula result is a string
                    // This is stored in the next record
                    outputNextStringRecord = true;
                    nextRow = frec.getRow();
                    nextColumn = frec.getColumn();
                } else {
                    thisStr = formatListener.formatNumberDateCell(frec);
                }
            } else {
                thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
            }
            break;
        case StringRecord.sid:
            if (outputNextStringRecord) {
                // String for formula
                StringRecord srec = (StringRecord) record;
                thisStr = srec.getString();
                thisRow = nextRow;
                thisColumn = nextColumn;
                outputNextStringRecord = false;
            }
            break;
        case LabelRecord.sid:
            LabelRecord lrec = (LabelRecord) record;
            thisRow = lrec.getRow();
            thisColumn = lrec.getColumn();
            thisStr = '"' + lrec.getValue() + '"';
            break;
        case LabelSSTRecord.sid:
            LabelSSTRecord lsrec = (LabelSSTRecord) record;
            thisRow = lsrec.getRow();
            thisColumn = lsrec.getColumn();
            if (sstRecord == null) {
                thisStr = '"' + "(No SST Record, can't identify string)" + '"';
            } else {
                thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"';
            }
            break;
        case NoteRecord.sid:
            NoteRecord nrec = (NoteRecord) record;
            thisRow = nrec.getRow();
            thisColumn = nrec.getColumn();
            // TODO: Find object to match nrec.getShapeId()
            thisStr = '"' + "(TODO)" + '"';
            break;
        case NumberRecord.sid:
            NumberRecord numrec = (NumberRecord) record;
            thisRow = numrec.getRow();
            thisColumn = numrec.getColumn();
            // Format
            thisStr = formatListener.formatNumberDateCell(numrec);
            break;
        case RKRecord.sid:
            RKRecord rkrec = (RKRecord) record;
            thisRow = rkrec.getRow();
            thisColumn = rkrec.getColumn();
            thisStr = '"' + "(TODO)" + '"';
            break;
        default:
            break;
    }
    // Handle new row
    if (thisRow != -1 && thisRow != lastRowNumber) {
        lastColumnNumber = -1;
    }
    // Handle missing column
    if (record instanceof MissingCellDummyRecord) {
        MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
        thisRow = mc.getRow();
        thisColumn = mc.getColumn();
        thisStr = "";
    }
    // If we got something to print out, do so
    if (thisStr != null) {
        if (thisColumn > 0) {
            output.print(',');
        }
        output.print(thisStr);
    }
    // Update column and row count
    if (thisRow > -1)
        lastRowNumber = thisRow;
    if (thisColumn > -1)
        lastColumnNumber = thisColumn;
    // Handle end of row
    if (record instanceof LastCellOfRowDummyRecord) {
        // Print out any missing commas if needed
        if (minColumns > 0) {
            // Columns are 0 based
            if (lastColumnNumber == -1) {
                lastColumnNumber = 0;
            }
            for (int i = lastColumnNumber; i < (minColumns); i++) {
                output.print(',');
            }
        }
        // We're onto a new row
        lastColumnNumber = -1;
        // End the row
        output.println();
    }
}
Also used : BlankRecord(org.apache.poi.hssf.record.BlankRecord) BOFRecord(org.apache.poi.hssf.record.BOFRecord) LabelRecord(org.apache.poi.hssf.record.LabelRecord) LabelSSTRecord(org.apache.poi.hssf.record.LabelSSTRecord) StringRecord(org.apache.poi.hssf.record.StringRecord) BoolErrRecord(org.apache.poi.hssf.record.BoolErrRecord) FormulaRecord(org.apache.poi.hssf.record.FormulaRecord) RKRecord(org.apache.poi.hssf.record.RKRecord) LastCellOfRowDummyRecord(org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord) NoteRecord(org.apache.poi.hssf.record.NoteRecord) NumberRecord(org.apache.poi.hssf.record.NumberRecord) MissingCellDummyRecord(org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord)

Example 5 with NumberRecord

use of org.apache.poi.hssf.record.NumberRecord in project poi by apache.

the class OldExcelExtractor method getText.

/**
     * Retrieves the text contents of the file, as best we can
     *  for these old file formats
     * 
     * @return the text contents of the file
     */
public String getText() {
    StringBuffer text = new StringBuffer();
    // To track formats and encodings
    CodepageRecord codepage = null;
    // Process each record in turn, looking for interesting ones
    while (ris.hasNextRecord()) {
        int sid = ris.getNextSid();
        ris.nextRecord();
        switch(sid) {
            case FILE_PASS_RECORD_SID:
                throw new EncryptedDocumentException("Encryption not supported for Old Excel files");
            case OldSheetRecord.sid:
                OldSheetRecord shr = new OldSheetRecord(ris);
                shr.setCodePage(codepage);
                text.append("Sheet: ");
                text.append(shr.getSheetname());
                text.append('\n');
                break;
            case OldLabelRecord.biff2_sid:
            case OldLabelRecord.biff345_sid:
                OldLabelRecord lr = new OldLabelRecord(ris);
                lr.setCodePage(codepage);
                text.append(lr.getValue());
                text.append('\n');
                break;
            case OldStringRecord.biff2_sid:
            case OldStringRecord.biff345_sid:
                OldStringRecord sr = new OldStringRecord(ris);
                sr.setCodePage(codepage);
                text.append(sr.getString());
                text.append('\n');
                break;
            case NumberRecord.sid:
                NumberRecord nr = new NumberRecord(ris);
                handleNumericCell(text, nr.getValue());
                break;
            case OldFormulaRecord.biff2_sid:
            case OldFormulaRecord.biff3_sid:
            case OldFormulaRecord.biff4_sid:
                // Biff 2 and 5+ share the same SID, due to a bug...
                if (biffVersion == 5) {
                    FormulaRecord fr = new FormulaRecord(ris);
                    if (fr.getCachedResultType() == CellType.NUMERIC.getCode()) {
                        handleNumericCell(text, fr.getValue());
                    }
                } else {
                    OldFormulaRecord fr = new OldFormulaRecord(ris);
                    if (fr.getCachedResultType() == CellType.NUMERIC.getCode()) {
                        handleNumericCell(text, fr.getValue());
                    }
                }
                break;
            case RKRecord.sid:
                RKRecord rr = new RKRecord(ris);
                handleNumericCell(text, rr.getRKNumber());
                break;
            case CodepageRecord.sid:
                codepage = new CodepageRecord(ris);
                break;
            default:
                ris.readFully(new byte[ris.remaining()]);
        }
    }
    close();
    ris = null;
    return text.toString();
}
Also used : EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) OldFormulaRecord(org.apache.poi.hssf.record.OldFormulaRecord) FormulaRecord(org.apache.poi.hssf.record.FormulaRecord) OldSheetRecord(org.apache.poi.hssf.record.OldSheetRecord) OldLabelRecord(org.apache.poi.hssf.record.OldLabelRecord) RKRecord(org.apache.poi.hssf.record.RKRecord) CodepageRecord(org.apache.poi.hssf.record.CodepageRecord) OldStringRecord(org.apache.poi.hssf.record.OldStringRecord) OldFormulaRecord(org.apache.poi.hssf.record.OldFormulaRecord) NumberRecord(org.apache.poi.hssf.record.NumberRecord)

Aggregations

NumberRecord (org.apache.poi.hssf.record.NumberRecord)9 FormulaRecord (org.apache.poi.hssf.record.FormulaRecord)6 Record (org.apache.poi.hssf.record.Record)5 Test (org.junit.Test)4 BlankRecord (org.apache.poi.hssf.record.BlankRecord)3 RowRecord (org.apache.poi.hssf.record.RowRecord)3 WindowTwoRecord (org.apache.poi.hssf.record.WindowTwoRecord)3 EncryptedDocumentException (org.apache.poi.EncryptedDocumentException)2 BOFRecord (org.apache.poi.hssf.record.BOFRecord)2 BoolErrRecord (org.apache.poi.hssf.record.BoolErrRecord)2 ContinueRecord (org.apache.poi.hssf.record.ContinueRecord)2 EOFRecord (org.apache.poi.hssf.record.EOFRecord)2 LabelSSTRecord (org.apache.poi.hssf.record.LabelSSTRecord)2 NoteRecord (org.apache.poi.hssf.record.NoteRecord)2 RKRecord (org.apache.poi.hssf.record.RKRecord)2 StringRecord (org.apache.poi.hssf.record.StringRecord)2 UnknownRecord (org.apache.poi.hssf.record.UnknownRecord)2 FormulaRecordAggregate (org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate)2 ArrayList (java.util.ArrayList)1 AssertionFailedError (junit.framework.AssertionFailedError)1