hssfworkbook.java
来自「EXCEL read and write」· Java 代码 · 共 1,687 行 · 第 1/4 页
JAVA
1,687 行
} } if (!someOtherSheetIsStillSelected) { setSelectedTab(newSheetIndex); } } } /** * determine whether the Excel GUI will backup the workbook when saving. * * @param backupValue true to indicate a backup will be performed. */ public void setBackupFlag(boolean backupValue) { BackupRecord backupRecord = workbook.getBackupRecord(); backupRecord.setBackup(backupValue ? (short) 1 : (short) 0); } /** * determine whether the Excel GUI will backup the workbook when saving. * * @return the current setting for backups. */ public boolean getBackupFlag() { BackupRecord backupRecord = workbook.getBackupRecord(); return (backupRecord.getBackup() == 0) ? false : true; } /** * Sets the repeating rows and columns for a sheet (as found in * 2003:File->PageSetup->Sheet, 2007:Page Layout->Print Titles). * This is function is included in the workbook * because it creates/modifies name records which are stored at the * workbook level. * <p> * To set just repeating columns: * <pre> * workbook.setRepeatingRowsAndColumns(0,0,1,-1-1); * </pre> * To set just repeating rows: * <pre> * workbook.setRepeatingRowsAndColumns(0,-1,-1,0,4); * </pre> * To remove all repeating rows and columns for a sheet. * <pre> * workbook.setRepeatingRowsAndColumns(0,-1,-1,-1,-1); * </pre> * * @param sheetIndex 0 based index to sheet. * @param startColumn 0 based start of repeating columns. * @param endColumn 0 based end of repeating columns. * @param startRow 0 based start of repeating rows. * @param endRow 0 based end of repeating rows. */ public void setRepeatingRowsAndColumns(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) { // Check arguments if (startColumn == -1 && endColumn != -1) throw new IllegalArgumentException("Invalid column range specification"); if (startRow == -1 && endRow != -1) throw new IllegalArgumentException("Invalid row range specification"); if (startColumn < -1 || startColumn >= MAX_COLUMN) throw new IllegalArgumentException("Invalid column range specification"); if (endColumn < -1 || endColumn >= MAX_COLUMN) throw new IllegalArgumentException("Invalid column range specification"); if (startRow < -1 || startRow > MAX_ROW) throw new IllegalArgumentException("Invalid row range specification"); if (endRow < -1 || endRow > MAX_ROW) throw new IllegalArgumentException("Invalid row range specification"); if (startColumn > endColumn) throw new IllegalArgumentException("Invalid column range specification"); if (startRow > endRow) throw new IllegalArgumentException("Invalid row range specification"); HSSFSheet sheet = getSheetAt(sheetIndex); short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex); boolean settingRowAndColumn = startColumn != -1 && endColumn != -1 && startRow != -1 && endRow != -1; boolean removingRange = startColumn == -1 && endColumn == -1 && startRow == -1 && endRow == -1; int rowColHeaderNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_PRINT_TITLE); if (removingRange) { if (rowColHeaderNameIndex >= 0) { workbook.removeName(rowColHeaderNameIndex); } return; } boolean isNewRecord; NameRecord nameRecord; if (rowColHeaderNameIndex < 0) { //does a lot of the house keeping for builtin records, like setting lengths to zero etc nameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_TITLE, sheetIndex+1); isNewRecord = true; } else { nameRecord = workbook.getNameRecord(rowColHeaderNameIndex); isNewRecord = false; } List temp = new ArrayList(); if (settingRowAndColumn) { final int exprsSize = 2 * 11 + 1; // 2 * Area3DPtg.SIZE + UnionPtg.SIZE temp.add(new MemFuncPtg(exprsSize)); } if (startColumn >= 0) { Area3DPtg colArea = new Area3DPtg(0, MAX_ROW, startColumn, endColumn, false, false, false, false, externSheetIndex); temp.add(colArea); } if (startRow >= 0) { Area3DPtg rowArea = new Area3DPtg(startRow, endRow, 0, MAX_COLUMN, false, false, false, false, externSheetIndex); temp.add(rowArea); } if (settingRowAndColumn) { temp.add(UnionPtg.instance); } Ptg[] ptgs = new Ptg[temp.size()]; temp.toArray(ptgs); nameRecord.setNameDefinition(ptgs); if (isNewRecord) { HSSFName newName = new HSSFName(this, nameRecord); names.add(newName); } HSSFPrintSetup printSetup = sheet.getPrintSetup(); printSetup.setValidSettings(false); sheet.setActive(true); } private int findExistingBuiltinNameRecordIdx(int sheetIndex, byte builtinCode) { for(int defNameIndex =0; defNameIndex<names.size(); defNameIndex++) { NameRecord r = workbook.getNameRecord(defNameIndex); if (r == null) { throw new RuntimeException("Unable to find all defined names to iterate over"); } if (!r.isBuiltInName() || r.getBuiltInName() != builtinCode) { continue; } if (r.getSheetNumber() -1 == sheetIndex) { return defNameIndex; } } return -1; } /** * create a new Font and add it to the workbook's font table * @return new font object */ public HSSFFont createFont() { FontRecord font = workbook.createNewFont(); short fontindex = (short) (getNumberOfFonts() - 1); if (fontindex > 3) { fontindex++; // THERE IS NO FOUR!! } if(fontindex == Short.MAX_VALUE){ throw new IllegalArgumentException("Maximum number of fonts was exceeded"); } // Ask getFontAt() to build it for us, // so it gets properly cached return getFontAt(fontindex); } /** * Finds a font that matches the one with the supplied attributes */ public HSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { for (short i=0; i<=getNumberOfFonts(); i++) { // Remember - there is no 4! if(i == 4) continue; HSSFFont hssfFont = getFontAt(i); if (hssfFont.getBoldweight() == boldWeight && hssfFont.getColor() == color && hssfFont.getFontHeight() == fontHeight && hssfFont.getFontName().equals(name) && hssfFont.getItalic() == italic && hssfFont.getStrikeout() == strikeout && hssfFont.getTypeOffset() == typeOffset && hssfFont.getUnderline() == underline) { return hssfFont; } } return null; } /** * get the number of fonts in the font table * @return number of fonts */ public short getNumberOfFonts() { return (short) workbook.getNumberOfFontRecords(); } /** * Get the font at the given index number * @param idx index number * @return HSSFFont at the index */ public HSSFFont getFontAt(short idx) { if(fonts == null) fonts = new Hashtable(); // So we don't confuse users, give them back // the same object every time, but create // them lazily Short sIdx = new Short(idx); if(fonts.containsKey(sIdx)) { return (HSSFFont)fonts.get(sIdx); } FontRecord font = workbook.getFontRecordAt(idx); HSSFFont retval = new HSSFFont(idx, font); fonts.put(sIdx, retval); return retval; } /** * Reset the fonts cache, causing all new calls * to getFontAt() to create new objects. * Should only be called after deleting fonts, * and that's not something you should normally do */ protected void resetFontCache() { fonts = new Hashtable(); } /** * create a new Cell style and add it to the workbook's style table * @return the new Cell Style object */ public HSSFCellStyle createCellStyle() { ExtendedFormatRecord xfr = workbook.createCellXF(); short index = (short) (getNumCellStyles() - 1); HSSFCellStyle style = new HSSFCellStyle(index, xfr, this); return style; } /** * get the number of styles the workbook contains * @return count of cell styles */ public short getNumCellStyles() { return (short) workbook.getNumExFormats(); } /** * get the cell style object at the given index * @param idx index within the set of styles * @return HSSFCellStyle object at the index */ public HSSFCellStyle getCellStyleAt(short idx) { ExtendedFormatRecord xfr = workbook.getExFormatAt(idx); HSSFCellStyle style = new HSSFCellStyle(idx, xfr, this); return style; } /** * Method write - write out this workbook to an Outputstream. Constructs * a new POI POIFSFileSystem, passes in the workbook binary representation and * writes it out. * * @param stream - the java OutputStream you wish to write the XLS to * * @exception IOException if anything can't be written. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem */ public void write(OutputStream stream) throws IOException { byte[] bytes = getBytes(); POIFSFileSystem fs = new POIFSFileSystem(); // For tracking what we've written out, used if we're // going to be preserving nodes List excepts = new ArrayList(1); // Write out the Workbook stream fs.createDocument(new ByteArrayInputStream(bytes), "Workbook"); // Write out our HPFS properties, if we have them writeProperties(fs, excepts); if (preserveNodes) { // Don't write out the old Workbook, we'll be doing our new one excepts.add("Workbook"); // If the file had WORKBOOK instead of Workbook, we'll write it // out correctly shortly, so don't include the old one excepts.add("WORKBOOK"); // Copy over all the other nodes to our new poifs copyNodes(this.filesystem,fs,excepts); } fs.writeFilesystem(stream); //poifs.writeFilesystem(stream); } /** * Totals the sizes of all sheet records and eventually serializes them */ private static final class SheetRecordCollector implements RecordVisitor { private List _list; private int _totalSize; public SheetRecordCollector() { _totalSize = 0; _list = new ArrayList(128); } public int getTotalSize() { return _totalSize; } public void visitRecord(Record r) { _list.add(r); _totalSize+=r.getRecordSize(); } public int serialize(int offset, byte[] data) { int result = 0; int nRecs = _list.size(); for(int i=0; i<nRecs; i++) { Record rec = (Record)_list.get(i); result += rec.serialize(offset + result, data); } return result; } } /** * Method getBytes - get the bytes of just the HSSF portions of the XLS file. * Use this to construct a POI POIFSFileSystem yourself. * * * @return byte[] array containing the binary representation of this workbook and all contained * sheets, rows, cells, etc. * * @see org.apache.poi.hssf.model.Workbook * @see org.apache.poi.hssf.model.Sheet */ public byte[] getBytes() { if (log.check( POILogger.DEBUG )) { log.log(DEBUG, "HSSFWorkbook.getBytes()"); } HSSFSheet[] sheets = getSheets(); int nSheets = sheets.length; // before getting the workbook size we must tell the sheets that // serialization is about to occur. for (int i = 0; i < nSheets; i++) { sheets[i].getSheet().preSerialize(); } int totalsize = workbook.getSize(); // pre-calculate all the sheet sizes and set BOF indexes SheetRecordCollector[] srCollectors = new SheetRecordCollector[nSheets]; for (int k = 0; k < nSheets; k++) { workbook.setSheetBof(k, totalsize); SheetRecordCollector src = new SheetRecordCollector(); sheets[k].getSheet().visitContainedRecords(src, totalsize); totalsize += src.getTotalSize(); srCollectors[k] = src; } byte[] retval = new byte[totalsize]; int pos = workbook.serialize(0, retval); for (int k = 0; k < nSheets; k++) { SheetRecordCollector src = srCollectors[k]; int serializedSize = src.serialize(pos, retval); if (serializedSize != src.getTotalSize()) { // Wrong offset values have been passed in the call to setSheetBof() above. // For books with more than one sheet, this discrepancy would cause excel // to report errors and loose data while reading the workbook throw new IllegalStateException("Actual serialized sheet size (" + serializedSize + ") differs from pre-calculated size (" + src.getTotalSize() + ") for sheet (" + k + ")"); // TODO - add similar sanity check to ensure that Sheet.serializeIndexRecord() does not write mis-aligned offsets either } pos += serializedSize; } return retval; } /** @deprecated Do not call this method from your applications. Use the methods * available in the HSSFRow to add string HSSFCells */ public int addSSTString(String string) { return workbook.addSSTString(new UnicodeString(string)); }
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?