org.apache.poi.hssf.record.Record Java Examples

The following examples show how to use org.apache.poi.hssf.record.Record. 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: RowBlock.java    From dremio-oss with Apache License 2.0 7 votes vote down vote up
public void process(Record r) {
  switch (r.getSid()) {
    case MergeCellsRecord.sid:
      mergeCellRecords.add((MergeCellsRecord) r);
      break;
    case SharedFormulaRecord.sid:
      shFrmRecords.add((SharedFormulaRecord) r);
      if (!(prevRec instanceof FormulaRecord)) {
        throw new RuntimeException("Shared formula record should follow a FormulaRecord");
      }
      FormulaRecord fr = (FormulaRecord) prevRec;
      firstCellRefs.add(new CellReference(fr.getRow(), fr.getColumn()));
      break;
    case ArrayRecord.sid:
      arrayRecords.add((ArrayRecord) r);
      break;
    case TableRecord.sid:
      tableRecords.add((TableRecord) r);
      break;
    default:
      plainRecords.add(r);
      break;
  }
  prevRec = r;
}
 
Example #2
Source File: FormulaViewer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method run
 * 
 * @throws IOException if the file contained errors 
 */
public void run() throws IOException {
    NPOIFSFileSystem fs  = new NPOIFSFileSystem(new File(file), true);
    try {
        InputStream is = BiffViewer.getPOIFSInputStream(fs);
        try {
            List<Record> records = RecordFactory.createRecords(is);

            for (Record record : records) {
                if (record.getSid() == FormulaRecord.sid) {
                    if (list) {
                        listFormula((FormulaRecord) record);
                    } else {
                        parseFormulaRecord((FormulaRecord) record);
                    }
                }
            }
        } finally {
            is.close();
        }
    } finally {
        fs.close();
    }
}
 
Example #3
Source File: Default03RecordHandlerContext.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
protected void initHeadHandler() {
	// The head handler do nothing, just pass
	headRecordHandler = new Abstract03RecordHandler(this) {
		@Override
		public void decode(Record record) throws Exception {
		}		
		@Override
		public boolean couldDecode(Record record) {
			return false;
		}
	};
	SSTRecordHandler sstRecordHandler = new SSTRecordHandler(this);
	StringRecordHandler stringRecordHandler = new StringRecordHandler(this);
	NumberRecordHandler numberRecordHandler = new NumberRecordHandler(this);
	BlankRecordHandler blankRecordHandler = new BlankRecordHandler(this);
	RowEndRecordHandler rowEndRecordHandler = new RowEndRecordHandler(this);
	BoundSheetRecordHandler boundSheetRecordHandler = new BoundSheetRecordHandler(this);
	EofRecordHandler eofRecordHandler = new EofRecordHandler(this);
	TailRecordHandler tailRecordHandler = new TailRecordHandler(this);
	headRecordHandler.setNext(sstRecordHandler).setNext(stringRecordHandler).setNext(numberRecordHandler)
			.setNext(blankRecordHandler).setNext(rowEndRecordHandler).setNext(boundSheetRecordHandler)
			.setNext(eofRecordHandler).setNext(tailRecordHandler);
}
 
Example #4
Source File: XlsSaxAnalyser.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Override
public void processRecord(Record record) {
    XlsRecordHandler handler = XLS_RECORD_HANDLER_MAP.get(record.getSid());
    if (handler == null) {
        return;
    }
    boolean ignoreRecord =
        (handler instanceof IgnorableXlsRecordHandler) && xlsReadContext.xlsReadWorkbookHolder().getIgnoreRecord();
    if (ignoreRecord) {
        // No need to read the current sheet
        return;
    }
    if (!handler.support(xlsReadContext, record)) {
        return;
    }
    handler.processRecord(xlsReadContext, record);
}
 
Example #5
Source File: ExcelRecordCleanerTest.java    From DocBleach with MIT License 6 votes vote down vote up
@Test
void removeObProjRecord() {
  Record valid1 = new UnknownRecord(0x01, new byte[]{});
  Record obProj1 = new UnknownRecord(0xD3, new byte[]{});
  Record valid2 = new UnknownRecord(0x02, new byte[]{});
  Collection<Record> records = new HashSet<>();
  records.add(valid1);
  records.add(obProj1);
  records.add(valid2);

  ExcelRecordCleaner.removeObProjRecord(records);

  assertTrue(records.contains(valid1), "A valid record is not removed");
  assertTrue(records.contains(valid2), "A valid record is not removed");
  assertFalse(records.contains(obProj1), "The ObProj record is removed");
}
 
Example #6
Source File: CFRecordsAggregate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create CFRecordsAggregate from a list of CF Records
 * @param rs - the stream to read from
 * @return CFRecordsAggregate object
 */
public static CFRecordsAggregate createCFAggregate(RecordStream rs) {
    Record rec = rs.getNext();
    if (rec.getSid() != CFHeaderRecord.sid &&
        rec.getSid() != CFHeader12Record.sid) {
        throw new IllegalStateException("next record sid was " + rec.getSid() 
                + " instead of " + CFHeaderRecord.sid + " or " +
                CFHeader12Record.sid + " as expected");
    }

    CFHeaderBase header = (CFHeaderBase)rec;
    int nRules = header.getNumberOfConditionalFormats();

    CFRuleBase[] rules = new CFRuleBase[nRules];
    for (int i = 0; i < rules.length; i++) {
        rules[i] = (CFRuleBase) rs.getNext();
    }

    return new CFRecordsAggregate(header, rules);
}
 
Example #7
Source File: ValueRecordsAggregate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void visitCellsForRow(int rowIndex, RecordVisitor rv) {

		CellValueRecordInterface[] rowCells = records[rowIndex];
		if(rowCells == null) {
			throw new IllegalArgumentException("Row [" + rowIndex + "] is empty");
		}


		for (int i = 0; i < rowCells.length; i++) {
			RecordBase cvr = (RecordBase) rowCells[i];
			if(cvr == null) {
				continue;
			}
			int nBlank = countBlanks(rowCells, i);
			if (nBlank > 1) {
				rv.visitRecord(createMBR(rowCells, i, nBlank));
				i+=nBlank-1;
			} else if (cvr instanceof RecordAggregate) {
				RecordAggregate agg = (RecordAggregate) cvr;
				agg.visitContainedRecords(rv);
			} else {
				rv.visitRecord((Record) cvr);
			}
		}
	}
 
Example #8
Source File: LabelSstRecordHandler.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
    LabelSSTRecord lsrec = (LabelSSTRecord)record;
    ReadCache readCache = xlsReadContext.readWorkbookHolder().getReadCache();
    Map<Integer, Cell> cellMap = xlsReadContext.xlsReadSheetHolder().getCellMap();
    if (readCache == null) {
        cellMap.put((int)lsrec.getColumn(), CellData.newEmptyInstance(lsrec.getRow(), (int)lsrec.getColumn()));
        return;
    }
    String data = readCache.get(lsrec.getSSTIndex());
    if (data == null) {
        cellMap.put((int)lsrec.getColumn(), CellData.newEmptyInstance(lsrec.getRow(), (int)lsrec.getColumn()));
        return;
    }
    if (xlsReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
        data = data.trim();
    }
    cellMap.put((int)lsrec.getColumn(), CellData.newInstance(data, lsrec.getRow(), (int)lsrec.getColumn()));
    xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
}
 
Example #9
Source File: InternalWorkbook.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new StyleRecord, for the given Extended
 *  Format index, and adds it onto the end of the
 *  records collection
 *
 * @param xfIndex the extended format index
 *
 * @return a new StyleRecord
 */
public StyleRecord createStyleRecord(int xfIndex) {
    // Style records always follow after
    //  the ExtendedFormat records
    StyleRecord newSR = new StyleRecord();
    newSR.setXFIndex(xfIndex);

    // Find the spot
    int addAt = -1;
    for(int i=records.getXfpos(); i<records.size() &&
            addAt == -1; i++) {
        Record r = records.get(i);
        if(r instanceof ExtendedFormatRecord ||
                r instanceof StyleRecord) {
            // Keep going
        } else {
            addAt = i;
        }
    }
    if(addAt == -1) {
        throw new IllegalStateException("No XF Records found!");
    }
    records.add(addAt, newSR);

    return newSR;
}
 
Example #10
Source File: RecordOrderer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isDVTPriorRecord(RecordBase rb) {
	if (rb instanceof MergedCellsTable || rb instanceof ConditionalFormattingTable) {
		return true;
	}
	short sid = ((Record)rb).getSid();
	switch(sid) {
		case WindowTwoRecord.sid:
		case UnknownRecord.SCL_00A0:
		case PaneRecord.sid:
		case SelectionRecord.sid:
		case UnknownRecord.STANDARDWIDTH_0099:
		// MergedCellsTable
		case UnknownRecord.LABELRANGES_015F:
		case UnknownRecord.PHONETICPR_00EF:
		// ConditionalFormattingTable
		case HyperlinkRecord.sid:
		case UnknownRecord.QUICKTIP_0800:
           // name of a VBA module    
           case UnknownRecord.CODENAME_1BA:
			return true;
	}
	return false;
}
 
Example #11
Source File: EFBiffViewer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void run() throws IOException {
    NPOIFSFileSystem fs   = new NPOIFSFileSystem(new File(file), true);
    try {
        InputStream     din   = BiffViewer.getPOIFSInputStream(fs);
        try {
            HSSFRequest     req   = new HSSFRequest();
    
            req.addListenerForAllRecords(new HSSFListener()
            {
                public void processRecord(Record rec)
                {
                    System.out.println(rec);
                }
            });
            HSSFEventFactory factory = new HSSFEventFactory();
    
            factory.processEvents(req, din);
        } finally {
            din.close();
        }
    } finally {
        fs.close();
    }
}
 
Example #12
Source File: RowEndRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void decode(Record record) throws Exception {
	// 产生新行,结束当前行
	if (handlerContext.getCurrColNum() != 0) {
		handlerContext.newRow(handlerContext.getCurrRowList());
		handlerContext.setCurrColNum(0);
	}
	handlerContext.initCurrRowList(0);
}
 
Example #13
Source File: EventWorkbookBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Process this record ourselves, and then
 *  pass it on to our child listener
 */
@Override
      public void processRecord(Record record) {
	// Handle it ourselves
	processRecordInternally(record);

	// Now pass on to our child
	childListener.processRecord(record);
}
 
Example #14
Source File: WorkbookRecordList.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the given record in the record list by identity and removes it
 *
 * @param record the identical record to be searched for
 */
public void remove( Object record ) {
   // can't use List.indexOf here because it checks the records for equality and not identity
   int i = 0;
   for (Record r : records) {
       if (r == record) {
           remove(i);
           break;
       }
       i++;
   }
}
 
Example #15
Source File: RecordStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the {@link Class} of the next Record. <code>null</code> if this stream is exhausted.
 */
public Class<? extends Record> peekNextClass() {
	if(!hasNext()) {
		return null;
	}
	return _list.get(_nextIndex).getClass();
}
 
Example #16
Source File: InternalWorkbook.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
   * sets the order of appearance for a given sheet.
   *
   * @param sheetname the name of the sheet to reorder
   * @param pos the position that we want to insert the sheet into (0 based)
   */
  public void setSheetOrder(String sheetname, int pos ) {
      int sheetNumber = getSheetIndex(sheetname);
      //remove the sheet that needs to be reordered and place it in the spot we want
      boundsheets.add(pos, boundsheets.remove(sheetNumber));

      // also adjust order of Records, calculate the position of the Boundsheets via getBspos()...
      int initialBspos = records.getBspos();
      int pos0 = initialBspos - (boundsheets.size() - 1);
      Record removed = records.get(pos0 + sheetNumber);
      records.remove(pos0 + sheetNumber);
records.add(pos0 + pos, removed);
      records.setBspos(initialBspos);
  }
 
Example #17
Source File: HSSFWorkbook.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets all pictures from the Workbook.
 *
 * @return the list of pictures (a list of {@link HSSFPictureData} objects.)
 */
@Override
public List<HSSFPictureData> getAllPictures()
{
    // The drawing group record always exists at the top level, so we won't need to do this recursively.
    List<HSSFPictureData> pictures = new ArrayList<HSSFPictureData>();
    for (Record r : workbook.getRecords()) {
        if (r instanceof AbstractEscherHolderRecord) {
            ((AbstractEscherHolderRecord) r).decode();
            List<EscherRecord> escherRecords = ((AbstractEscherHolderRecord) r).getEscherRecords();
            searchForPictures(escherRecords, pictures);
        }
    }
    return Collections.unmodifiableList(pictures);
}
 
Example #18
Source File: NoteRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
    NoteRecord nr = (NoteRecord)record;
    String text = xlsReadContext.xlsReadSheetHolder().getObjectCacheMap().get(nr.getShapeId());
    CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, text, nr.getRow(), nr.getColumn());
    xlsReadContext.xlsReadSheetHolder().setCellExtra(cellExtra);
    xlsReadContext.analysisEventProcessor().extra(xlsReadContext);
}
 
Example #19
Source File: HSSFWorkbook.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public int serialize(int offset, byte[] data) {
    int result = 0;
    for (Record rec : _list) {
        result += rec.serialize(offset + result, data);
    }
    return result;
}
 
Example #20
Source File: RecordOrderer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find correct position to add new CFHeader record
 */
private static int findInsertPosForNewCondFormatTable(List<RecordBase> records) {

	for (int i = records.size() - 2; i >= 0; i--) { // -2 to skip EOF record
		Object rb = records.get(i);
		if (rb instanceof MergedCellsTable) {
			return i + 1;
		}
		if (rb instanceof DataValidityTable) {
			continue;
		}

		Record rec = (Record) rb;
		switch (rec.getSid()) {
			case WindowTwoRecord.sid:
			case SCLRecord.sid:
			case PaneRecord.sid:
			case SelectionRecord.sid:
			case UnknownRecord.STANDARDWIDTH_0099:
			// MergedCellsTable usually here
			case UnknownRecord.LABELRANGES_015F:
			case UnknownRecord.PHONETICPR_00EF:
				// ConditionalFormattingTable goes here
				return i + 1;
			// HyperlinkTable (not aggregated by POI yet)
			// DataValidityTable
		}
	}
	throw new RuntimeException("Did not find Window2 record");
}
 
Example #21
Source File: LinkTable.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * copied from Workbook
 */
private int findFirstRecordLocBySid(short sid) {
	int index = 0;
	for (Record record : _workbookRecordList.getRecords()) {
		if (record.getSid() == sid) {
			return index;
		}
		index ++;
	}
	return -1;
}
 
Example #22
Source File: HyperlinkRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
    HyperlinkRecord hr = (HyperlinkRecord)record;
    CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.HYPERLINK, hr.getAddress(), hr.getFirstRow(),
        hr.getLastRow(), hr.getFirstColumn(), hr.getLastColumn());
    xlsReadContext.xlsReadSheetHolder().setCellExtra(cellExtra);
    xlsReadContext.analysisEventProcessor().extra(xlsReadContext);
}
 
Example #23
Source File: HSSFWorkbook.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This is basically a kludge to deal with the now obsolete Label records.  If
 * you have to read in a sheet that contains Label records, be aware that the rest
 * of the API doesn't deal with them, the low level structure only provides read-only
 * semi-immutable structures (the sets are there for interface conformance with NO
 * Implementation).  In short, you need to call this function passing it a reference
 * to the Workbook object.  All labels will be converted to LabelSST records and their
 * contained strings will be written to the Shared String table (SSTRecord) within
 * the Workbook.
 *
 * @param records a collection of sheet's records.
 * @param offset the offset to search at
 * @see org.apache.poi.hssf.record.LabelRecord
 * @see org.apache.poi.hssf.record.LabelSSTRecord
 * @see org.apache.poi.hssf.record.SSTRecord
 */

private void convertLabelRecords(List<Record> records, int offset)
{
    if (log.check( POILogger.DEBUG )) {
       log.log(POILogger.DEBUG, "convertLabelRecords called");
   }
    for (int k = offset; k < records.size(); k++)
    {
        Record rec = records.get(k);

        if (rec.getSid() == LabelRecord.sid)
        {
            LabelRecord oldrec = ( LabelRecord ) rec;

            records.remove(k);
            LabelSSTRecord newrec   = new LabelSSTRecord();
            int            stringid =
                workbook.addSSTString(new UnicodeString(oldrec.getValue()));

            newrec.setRow(oldrec.getRow());
            newrec.setColumn(oldrec.getColumn());
            newrec.setXFIndex(oldrec.getXFIndex());
            newrec.setSSTIndex(stringid);
                  records.add(k, newrec);
        }
    }
    if (log.check( POILogger.DEBUG )) {
       log.log(POILogger.DEBUG, "convertLabelRecords exit");
   }
}
 
Example #24
Source File: MergeCellsRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
    MergeCellsRecord mcr = (MergeCellsRecord)record;
    for (int i = 0; i < mcr.getNumAreas(); i++) {
        CellRangeAddress cellRangeAddress = mcr.getAreaAt(i);
        CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.MERGE, null, cellRangeAddress.getFirstRow(),
            cellRangeAddress.getLastRow(), cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
        xlsReadContext.xlsReadSheetHolder().setCellExtra(cellExtra);
        xlsReadContext.analysisEventProcessor().extra(xlsReadContext);
    }
}
 
Example #25
Source File: StringRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void decode(Record record) {
	LabelSSTRecord labelSSTRecord = (LabelSSTRecord) record;
	int currColNum = labelSSTRecord.getColumn();
	handlerContext.addCol2CurrRowList(handlerContext.getSSTRecord().getString(labelSSTRecord.getSSTIndex()).toString());
	handlerContext.setCurrColNum(currColNum);
}
 
Example #26
Source File: XlsListener.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(Record record) {
	try {
		context.handle(record);
	} catch (Exception e) {
		// do nothing
	}
}
 
Example #27
Source File: ObjRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
    ObjRecord or = (ObjRecord)record;
    for (SubRecord subRecord : or.getSubRecords()) {
        if (subRecord instanceof CommonObjectDataSubRecord) {
            CommonObjectDataSubRecord codsr = (CommonObjectDataSubRecord)subRecord;
            if (CommonObjectDataSubRecord.OBJECT_TYPE_COMMENT == codsr.getObjectType()) {
                xlsReadContext.xlsReadSheetHolder().setTempObjectIndex(codsr.getObjectId());
            }
            break;
        }
    }
}
 
Example #28
Source File: IndexRecordHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
    if (xlsReadContext.readSheetHolder() == null) {
        return;
    }
    xlsReadContext.readSheetHolder().setApproximateTotalRowNumber(((IndexRecord)record).getLastRowAdd1());
}
 
Example #29
Source File: Default03RecordHandlerContext.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Override
public void processRecord(Record record) {
	try {
		this.handle(record);
	} catch (Exception e) {
		throw new EasyExcelException(e);
	}
}
 
Example #30
Source File: InternalWorkbook.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the StyleRecord for the given
 *  xfIndex, or null if that ExtendedFormat doesn't
 *  have a Style set.
 *
 * @param xfIndex the extended format index
 *
 * @return the StyleRecord, {@code null} if it that ExtendedFormat doesn't have a Style set.
 */
public StyleRecord getStyleRecord(int xfIndex) {
    // Style records always follow after
    //  the ExtendedFormat records
    for(int i=records.getXfpos(); i<records.size(); i++) {
        Record r = records.get(i);
        if (r instanceof StyleRecord) {
            StyleRecord sr = (StyleRecord)r;
            if (sr.getXFIndex() == xfIndex) {
                return sr;
            }
        }
    }
    return null;
}