Rainer Klute klute@rainer-klute.de
Bruno Girin brunogirin@gmail.com
Yegor Kozlov yegor at apache.org
+ Dominik Stadler centic at apache.org
This build was tested with ant 1.6.2 although it will probably work with
other versions. The following jar files should be available on the
To build the documentation you will need to install forrest and set
the FORREST_HOME environment variable. Forrest 0.5.1 required.
- You currently need JDK 1.6 or newer to build POI.
+ Since POI 3.11 you will need JDK 1.6 or newer to build POI.
Some people may find the tests hang when run through Ant. If this
happens to you, try giving Ant some more memory when you run it, eg:
/**
* @see java.util.AbstractSet#hashCode()
*/
+ @Override
public int hashCode()
{
return (int) this.getID();
*
* @return the sheet this cell belongs to
*/
+ @Override
public XSSFSheet getSheet() {
return getRow().getSheet();
}
*
* @return the row this cell belongs to
*/
+ @Override
public XSSFRow getRow() {
return _row;
}
* @throws IllegalStateException if the cell type returned by {@link #getCellType()}
* is not CELL_TYPE_BOOLEAN, CELL_TYPE_BLANK or CELL_TYPE_FORMULA
*/
+ @Override
public boolean getBooleanCellValue() {
int cellType = getCellType();
switch(cellType) {
* precalculated value, for booleans we'll set its value. For other types we
* will change the cell to a boolean cell and set its value.
*/
+ @Override
public void setCellValue(boolean value) {
_cell.setT(STCellType.B);
_cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
* @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
* @see DataFormatter for turning this number into a string similar to that which Excel would render this number as.
*/
+ @Override
public double getNumericCellValue() {
int cellType = getCellType();
switch(cellType) {
* precalculated value, for numerics we'll set its value. For other types we
* will change the cell to a numeric cell and set its value.
*/
+ @Override
public void setCellValue(double value) {
if(Double.isInfinite(value)) {
// Excel does not support positive/negative infinities,
* </p>
* @return the value of the cell as a string
*/
+ @Override
public String getStringCellValue() {
XSSFRichTextString str = getRichStringCellValue();
return str == null ? null : str.getString();
* </p>
* @return the value of the cell as a XSSFRichTextString
*/
+ @Override
public XSSFRichTextString getRichStringCellValue() {
int cellType = getCellType();
XSSFRichTextString rt;
* change the cell to a string cell and set its value.
* If value is null then we will change the cell to a Blank cell.
*/
+ @Override
public void setCellValue(String str) {
setCellValue(str == null ? null : new XSSFRichTextString(str));
}
* change the cell to a string cell and set its value.
* If value is null then we will change the cell to a Blank cell.
*/
+ @Override
public void setCellValue(RichTextString str) {
if(str == null || str.getString() == null){
setCellType(Cell.CELL_TYPE_BLANK);
* @return a formula for the cell
* @throws IllegalStateException if the cell type returned by {@link #getCellType()} is not CELL_TYPE_FORMULA
*/
+ @Override
public String getCellFormula() {
int cellType = getCellType();
if(cellType != CELL_TYPE_FORMULA) throw typeMismatch(CELL_TYPE_FORMULA, cellType, false);
* @throws IllegalStateException if the operation is not allowed, for example,
* when the cell is a part of a multi-cell array formula
*/
+ @Override
public void setCellFormula(String formula) {
if(isPartOfArrayFormulaGroup()){
notifyArrayFormulaChanging();
*
* @return zero-based column index of a column in a sheet.
*/
+ @Override
public int getColumnIndex() {
return this._cellNum;
}
*
* @return zero-based row index of a row in the sheet that contains this cell
*/
+ @Override
public int getRowIndex() {
return _row.getRowNum();
}
*
* @return the cell's style.</code>
*/
+ @Override
public XSSFCellStyle getCellStyle() {
XSSFCellStyle style = null;
if(_stylesSource.getNumCellStyles() > 0){
* @param style reference contained in the workbook.
* If the value is null then the style information is removed causing the cell to used the default workbook style.
*/
+ @Override
public void setCellStyle(CellStyle style) {
if(style == null) {
if(_cell.isSetS()) _cell.unsetS();
* @see Cell#CELL_TYPE_BOOLEAN
* @see Cell#CELL_TYPE_ERROR
*/
+ @Override
public int getCellType() {
if (_cell.getF() != null || getSheet().isCellInArrayFormulaContext(this)) {
* {@link #CELL_TYPE_BOOLEAN}, {@link #CELL_TYPE_ERROR}) depending
* on the cached value of the formula
*/
+ @Override
public int getCachedFormulaResultType() {
if (_cell.getF() == null) {
throw new IllegalStateException("Only formula cells have cached results");
* @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
* @see DataFormatter for formatting this date into a string similar to how excel does.
*/
+ @Override
public Date getDateCellValue() {
int cellType = getCellType();
if (cellType == CELL_TYPE_BLANK) {
* precalculated value, for numerics we'll set its value. For other types we
* will change the cell to a numeric cell and set its value.
*/
+ @Override
public void setCellValue(Date value) {
boolean date1904 = getSheet().getWorkbook().isDate1904();
setCellValue(DateUtil.getExcelDate(value, date1904));
* precalculated value, for numerics we'll set its value. For othertypes we
* will change the cell to a numeric cell and set its value.
*/
+ @Override
public void setCellValue(Calendar value) {
boolean date1904 = getSheet().getWorkbook().isDate1904();
setCellValue( DateUtil.getExcelDate(value, date1904 ));
* @throws IllegalStateException if the cell type returned by {@link #getCellType()} isn't CELL_TYPE_ERROR
* @see FormulaError
*/
+ @Override
public byte getErrorCellValue() {
String code = getErrorCellString();
if (code == null) {
* cell and set its value.
* @see FormulaError
*/
+ @Override
public void setCellErrorValue(byte errorCode) {
FormulaError error = FormulaError.forInt(errorCode);
setCellErrorValue(error);
/**
* Sets this cell as the active cell for the worksheet.
*/
+ @Override
public void setAsActiveCell() {
getSheet().setActiveCell(getReference());
}
* @see #CELL_TYPE_BOOLEAN
* @see #CELL_TYPE_ERROR
*/
+ @Override
public void setCellType(int cellType) {
int prevType = getCellType();
-
+
if(isPartOfArrayFormulaGroup()){
notifyArrayFormulaChanging();
}
if(prevType == CELL_TYPE_FORMULA && cellType != CELL_TYPE_FORMULA) {
getSheet().getWorkbook().onDeleteFormula(this);
}
-
+
switch (cellType) {
case CELL_TYPE_BLANK:
setBlank();
*
* @return the cell comment associated with this cell or <code>null</code>
*/
+ @Override
public XSSFComment getCellComment() {
return getSheet().getCellComment(_row.getRowNum(), getColumnIndex());
}
*
* @param comment the XSSFComment associated with this cell
*/
+ @Override
public void setCellComment(Comment comment) {
if(comment == null) {
removeCellComment();
/**
* Removes the comment for this cell, if there is one.
*/
+ @Override
public void removeCellComment() {
XSSFComment comment = getCellComment();
if(comment != null){
*
* @return hyperlink associated with this cell or <code>null</code> if not found
*/
+ @Override
public XSSFHyperlink getHyperlink() {
return getSheet().getHyperlink(_row.getRowNum(), _cellNum);
}
*
* @param hyperlink the hyperlink to associate with this cell
*/
+ @Override
public void setHyperlink(Hyperlink hyperlink) {
XSSFHyperlink link = (XSSFHyperlink)hyperlink;
throw new IllegalStateException("Unexpected formula result type (" + cellType + ")");
}
+ @Override
public CellRangeAddress getArrayFormulaRange() {
XSSFCell cell = getSheet().getFirstCellInArrayFormula(this);
if (cell == null) {
return CellRangeAddress.valueOf(formulaRef);
}
+ @Override
public boolean isPartOfArrayFormulaGroup() {
return getSheet().isCellInArrayFormulaContext(this);
}
*
* @return the parent XSSFWorkbook
*/
+ @Override
public XSSFWorkbook getWorkbook() {
return (XSSFWorkbook)getParent();
}
*
* @return the name of this sheet
*/
+ @Override
public String getSheetName() {
return sheet.getName();
}
* @param region (rowfrom/colfrom-rowto/colto) to merge
* @return index of this region
*/
+ @Override
public int addMergedRegion(CellRangeAddress region) {
region.validate(SpreadsheetVersion.EXCEL2007);
*
* @param column the column index
*/
- public void autoSizeColumn(int column) {
+ @Override
+ public void autoSizeColumn(int column) {
autoSizeColumn(column, false);
}
* @param column the column index
* @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
*/
+ @Override
public void autoSizeColumn(int column, boolean useMergedCells) {
double width = SheetUtil.getColumnWidth(this, column, useMergedCells);
*
* @return a SpreadsheetML drawing
*/
+ @Override
public XSSFDrawing createDrawingPatriarch() {
XSSFDrawing drawing = null;
CTDrawing ctDrawing = getCTDrawing();
* @param colSplit Horizonatal position of split.
* @param rowSplit Vertical position of split.
*/
+ @Override
public void createFreezePane(int colSplit, int rowSplit) {
createFreezePane( colSplit, rowSplit, colSplit, rowSplit );
}
* @param leftmostColumn Left column visible in right pane.
* @param topRow Top row visible in bottom pane
*/
+ @Override
public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
CTSheetView ctView = getDefaultSheetView();
* @return High level {@link XSSFRow} object representing a row in the sheet
* @see #removeRow(org.apache.poi.ss.usermodel.Row)
*/
+ @Override
public XSSFRow createRow(int rownum) {
CTRow ctRow;
XSSFRow prev = _rows.get(rownum);
ctRow = prev.getCTRow();
ctRow.set(CTRow.Factory.newInstance());
} else {
- if(_rows.isEmpty() || rownum > _rows.lastKey()) {
- // we can append the new row at the end
- ctRow = worksheet.getSheetData().addNewRow();
- } else {
- // get number of rows where row index < rownum
- // --> this tells us where our row should go
- int idx = _rows.headMap(rownum).size();
- ctRow = worksheet.getSheetData().insertNewRow(idx);
- }
+ if(_rows.isEmpty() || rownum > _rows.lastKey()) {
+ // we can append the new row at the end
+ ctRow = worksheet.getSheetData().addNewRow();
+ } else {
+ // get number of rows where row index < rownum
+ // --> this tells us where our row should go
+ int idx = _rows.headMap(rownum).size();
+ ctRow = worksheet.getSheetData().insertNewRow(idx);
+ }
}
XSSFRow r = new XSSFRow(ctRow, this);
r.setRowNum(rownum);
* @see org.apache.poi.ss.usermodel.Sheet#PANE_UPPER_LEFT
* @see org.apache.poi.ss.usermodel.Sheet#PANE_UPPER_RIGHT
*/
+ @Override
public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) {
createFreezePane(xSplitPos, ySplitPos, leftmostColumn, topRow);
getPane().setState(STPaneState.SPLIT);
getPane().setActivePane(STPane.Enum.forInt(activePane));
}
+ @Override
public XSSFComment getCellComment(int row, int column) {
if (sheetComments == null) {
return null;
*
* @return column indexes of all the vertical page breaks, never <code>null</code>
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public int[] getColumnBreaks() {
if (!worksheet.isSetColBreaks() || worksheet.getColBreaks().sizeOfBrkArray() == 0) {
* @param columnIndex - the column to set (0-based)
* @return width - the width in units of 1/256th of a character width
*/
+ @Override
public int getColumnWidth(int columnIndex) {
CTCol col = columnHelper.getColumn(columnIndex, false);
double width = col == null || !col.isSetWidth() ? getDefaultColumnWidth() : col.getWidth();
* </p>
* @return column width, default value is 8
*/
+ @Override
public int getDefaultColumnWidth() {
CTSheetFormatPr pr = worksheet.getSheetFormatPr();
return pr == null ? 8 : (int)pr.getBaseColWidth();
*
* @return default row height
*/
+ @Override
public short getDefaultRowHeight() {
return (short)(getDefaultRowHeightInPoints() * 20);
}
*
* @return default row height in points
*/
+ @Override
public float getDefaultRowHeightInPoints() {
CTSheetFormatPr pr = worksheet.getSheetFormatPr();
return (float)(pr == null ? 0 : pr.getDefaultRowHeight());
* (0 based) column, or null if no style has been
* set for that column
*/
+ @Override
public CellStyle getColumnStyle(int column) {
int idx = columnHelper.getColDefaultStyle(column);
return getWorkbook().getCellStyleAt((short)(idx == -1 ? 0 : idx));
*
* @param value true for right to left, false otherwise.
*/
+ @Override
public void setRightToLeft(boolean value)
{
CTSheetView view = getDefaultSheetView();
*
* @return whether the text is displayed in right-to-left mode in the window
*/
+ @Override
public boolean isRightToLeft()
{
CTSheetView view = getDefaultSheetView();
*
* @return boolean - guts or no guts
*/
+ @Override
public boolean getDisplayGuts() {
CTSheetPr sheetPr = getSheetTypeSheetPr();
CTOutlinePr outlinePr = sheetPr.getOutlinePr() == null ? CTOutlinePr.Factory.newInstance() : sheetPr.getOutlinePr();
*
* @param value - guts or no guts
*/
+ @Override
public void setDisplayGuts(boolean value) {
CTSheetPr sheetPr = getSheetTypeSheetPr();
CTOutlinePr outlinePr = sheetPr.getOutlinePr() == null ? sheetPr.addNewOutlinePr() : sheetPr.getOutlinePr();
*
* @return whether all zero values on the worksheet are displayed
*/
+ @Override
public boolean isDisplayZeros(){
CTSheetView view = getDefaultSheetView();
return view == null ? true : view.getShowZeros();
*
* @param value whether to display or hide all zero values on the worksheet
*/
+ @Override
public void setDisplayZeros(boolean value){
CTSheetView view = getSheetTypeSheetView();
view.setShowZeros(value);
*
* @return the number of the first logical row on the sheet, zero based
*/
+ @Override
public int getFirstRowNum() {
return _rows.size() == 0 ? 0 : _rows.firstKey();
}
*
* @return <code>true</code>
*/
+ @Override
public boolean getFitToPage() {
CTSheetPr sheetPr = getSheetTypeSheetPr();
CTPageSetUpPr psSetup = (sheetPr == null || !sheetPr.isSetPageSetUpPr()) ?
* {@link #getOddFooter()} and
* {@link #getEvenFooter()}
*/
+ @Override
public Footer getFooter() {
// The default footer is an odd footer
return getOddFooter();
* {@link #getOddHeader()} and
* {@link #getEvenHeader()}
*/
+ @Override
public Header getHeader() {
// The default header is an odd header
return getOddHeader();
/**
* Determine whether printed output for this sheet will be horizontally centered.
*/
+ @Override
public boolean getHorizontallyCenter() {
CTPrintOptions opts = worksheet.getPrintOptions();
return opts != null && opts.getHorizontalCentered();
}
+ @Override
public int getLastRowNum() {
return _rows.size() == 0 ? 0 : _rows.lastKey();
}
+ @Override
public short getLeftCol() {
String cellRef = worksheet.getSheetViews().getSheetViewArray(0).getTopLeftCell();
if(cellRef == null) {
- return 0;
+ return 0;
}
CellReference cellReference = new CellReference(cellRef);
return cellReference.getCol();
* @see Sheet#HeaderMargin
* @see Sheet#FooterMargin
*/
+ @Override
public double getMargin(short margin) {
if (!worksheet.isSetPageMargins()) return 0;
* @see Sheet#HeaderMargin
* @see Sheet#FooterMargin
*/
+ @Override
public void setMargin(short margin, double size) {
CTPageMargins pageMargins = worksheet.isSetPageMargins() ?
worksheet.getPageMargins() : worksheet.addNewPageMargins();
* @return the merged region at the specified index
* @throws IllegalStateException if this worksheet does not contain merged regions
*/
+ @Override
public CellRangeAddress getMergedRegion(int index) {
CTMergeCells ctMergeCells = worksheet.getMergeCells();
if(ctMergeCells == null) throw new IllegalStateException("This worksheet does not contain merged regions");
*
* @return number of merged regions in this worksheet
*/
+ @Override
public int getNumMergedRegions() {
CTMergeCells ctMergeCells = worksheet.getMergeCells();
return ctMergeCells == null ? 0 : ctMergeCells.sizeOfMergeCellArray();
*
* @return null if no pane configured, or the pane information.
*/
+ @Override
public PaneInformation getPaneInformation() {
CTPane pane = getDefaultSheetView().getPane();
// no pane configured
*
* @return the number of phsyically defined rows
*/
+ @Override
public int getPhysicalNumberOfRows() {
return _rows.size();
}
*
* @return The user model for the print setup object.
*/
+ @Override
public XSSFPrintSetup getPrintSetup() {
return new XSSFPrintSetup(worksheet);
}
*
* @return true => protection enabled; false => protection disabled
*/
+ @Override
public boolean getProtect() {
return worksheet.isSetSheetProtection() && sheetProtectionEnabled();
}
*
* @param password to set for protection. Pass <code>null</code> to remove protection
*/
+ @Override
public void protectSheet(String password) {
- if(password != null) {
- CTSheetProtection sheetProtection = worksheet.addNewSheetProtection();
- sheetProtection.xsetPassword(stringToExcelPassword(password));
- sheetProtection.setSheet(true);
- sheetProtection.setScenarios(true);
- sheetProtection.setObjects(true);
- } else {
- worksheet.unsetSheetProtection();
- }
- }
-
- /**
- * Converts a String to a {@link STUnsignedShortHex} value that contains the {@link PasswordRecord#hashPassword(String)}
- * value in hexadecimal format
- *
- * @param password the password string you wish convert to an {@link STUnsignedShortHex}
- * @return {@link STUnsignedShortHex} that contains Excel hashed password in Hex format
- */
- private STUnsignedShortHex stringToExcelPassword(String password) {
- STUnsignedShortHex hexPassword = STUnsignedShortHex.Factory.newInstance();
- hexPassword.setStringValue(String.valueOf(HexDump.shortToHex(PasswordRecord.hashPassword(password))).substring(2));
- return hexPassword;
- }
+ if(password != null) {
+ CTSheetProtection sheetProtection = worksheet.addNewSheetProtection();
+ sheetProtection.xsetPassword(stringToExcelPassword(password));
+ sheetProtection.setSheet(true);
+ sheetProtection.setScenarios(true);
+ sheetProtection.setObjects(true);
+ } else {
+ worksheet.unsetSheetProtection();
+ }
+ }
+
+ /**
+ * Converts a String to a {@link STUnsignedShortHex} value that contains the {@link PasswordRecord#hashPassword(String)}
+ * value in hexadecimal format
+ *
+ * @param password the password string you wish convert to an {@link STUnsignedShortHex}
+ * @return {@link STUnsignedShortHex} that contains Excel hashed password in Hex format
+ */
+ private STUnsignedShortHex stringToExcelPassword(String password) {
+ STUnsignedShortHex hexPassword = STUnsignedShortHex.Factory.newInstance();
+ hexPassword.setStringValue(String.valueOf(HexDump.shortToHex(PasswordRecord.hashPassword(password))).substring(2));
+ return hexPassword;
+ }
/**
* Returns the logical row ( 0-based). If you ask for a row that is not
* @param rownum row to get
* @return <code>XSSFRow</code> representing the rownumber or <code>null</code> if its not defined on the sheet
*/
+ @Override
public XSSFRow getRow(int rownum) {
return _rows.get(rownum);
}
*
* @return row indexes of all the horizontal page breaks, never <code>null</code>
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public int[] getRowBreaks() {
if (!worksheet.isSetRowBreaks() || worksheet.getRowBreaks().sizeOfBrkArray() == 0) {
* </p>
* @return <code>true</code> if row summaries appear below detail in the outline
*/
+ @Override
public boolean getRowSumsBelow() {
CTSheetPr sheetPr = worksheet.getSheetPr();
CTOutlinePr outlinePr = (sheetPr != null && sheetPr.isSetOutlinePr())
* </p>
* @param value <code>true</code> if row summaries appear below detail in the outline
*/
+ @Override
public void setRowSumsBelow(boolean value) {
ensureOutlinePr().setSummaryBelow(value);
}
* </p>
* @return <code>true</code> if col summaries appear right of the detail in the outline
*/
+ @Override
public boolean getRowSumsRight() {
CTSheetPr sheetPr = worksheet.getSheetPr();
CTOutlinePr outlinePr = (sheetPr != null && sheetPr.isSetOutlinePr())
* </p>
* @param value <code>true</code> if col summaries appear right of the detail in the outline
*/
+ @Override
public void setRowSumsRight(boolean value) {
ensureOutlinePr().setSummaryRight(value);
}
*
* @return true => protection enabled; false => protection disabled
*/
+ @Override
public boolean getScenarioProtect() {
return worksheet.isSetSheetProtection() && worksheet.getSheetProtection().getScenarios();
}
*
* @return integer indicating the rownum (0 based) of the top row
*/
+ @Override
public short getTopRow() {
String cellRef = getSheetTypeSheetView().getTopLeftCell();
if(cellRef == null) {
- return 0;
+ return 0;
}
CellReference cellReference = new CellReference(cellRef);
return (short) cellReference.getRow();
*
* @return whether printed output for this sheet will be vertically centered.
*/
+ @Override
public boolean getVerticallyCenter() {
CTPrintOptions opts = worksheet.getPrintOptions();
return opts != null && opts.getVerticalCentered();
/**
* Group between (0 based) columns
*/
+ @Override
public void groupColumn(int fromColumn, int toColumn) {
groupColumn1Based(fromColumn+1, toColumn+1);
}
private void groupColumn1Based(int fromColumn, int toColumn) {
CTCols ctCols=worksheet.getColsArray(0);
CTCol ctCol=CTCol.Factory.newInstance();
-
+
// copy attributes, as they might be removed by merging with the new column
// TODO: check if this fix is really necessary or if the sweeping algorithm
// in addCleanColIntoCols needs to be adapted ...
CTCol fixCol_before = this.columnHelper.getColumn1Based(toColumn, false);
if (fixCol_before != null) {
- fixCol_before = (CTCol)fixCol_before.copy();
+ fixCol_before = (CTCol)fixCol_before.copy();
}
-
+
ctCol.setMin(fromColumn);
ctCol.setMax(toColumn);
this.columnHelper.addCleanColIntoCols(ctCols, ctCol);
*/
private void setColWidthAttribute(CTCols ctCols) {
for (CTCol col : ctCols.getColList()) {
- if (!col.isSetWidth()) {
- col.setWidth(getDefaultColumnWidth());
- col.setCustomWidth(false);
- }
+ if (!col.isSetWidth()) {
+ col.setWidth(getDefaultColumnWidth());
+ col.setCustomWidth(false);
+ }
}
}
* @param fromRow start row (0-based)
* @param toRow end row (0-based)
*/
+ @Override
public void groupRow(int fromRow, int toRow) {
for (int i = fromRow; i <= toRow; i++) {
XSSFRow xrow = getRow(i);
/**
* Determines if there is a page break at the indicated column
*/
+ @Override
public boolean isColumnBroken(int column) {
int[] colBreaks = getColumnBreaks();
- for (int i = 0 ; i < colBreaks.length ; i++) {
- if (colBreaks[i] == column) {
+ for (int colBreak : colBreaks) {
+ if (colBreak == column) {
return true;
}
}
* @param columnIndex - the column to set (0-based)
* @return hidden - <code>false</code> if the column is visible
*/
+ @Override
public boolean isColumnHidden(int columnIndex) {
CTCol col = columnHelper.getColumn(columnIndex, false);
return col != null && col.getHidden();
*
* @return <code>true</code> if this sheet should display formulas.
*/
+ @Override
public boolean isDisplayFormulas() {
return getSheetTypeSheetView().getShowFormulas();
}
* @return <code>true</code> if this sheet displays gridlines.
* @see #isPrintGridlines() to check if printing of gridlines is turned on or off
*/
+ @Override
public boolean isDisplayGridlines() {
return getSheetTypeSheetView().getShowGridLines();
}
* @param show <code>true</code> if this sheet should display gridlines.
* @see #setPrintGridlines(boolean)
*/
+ @Override
public void setDisplayGridlines(boolean show) {
getSheetTypeSheetView().setShowGridLines(show);
}
*
* @return <code>true</code> if this sheet should display row and column headings.
*/
+ @Override
public boolean isDisplayRowColHeadings() {
return getSheetTypeSheetView().getShowRowColHeaders();
}
*
* @param show <code>true</code> if this sheet should display row and column headings.
*/
+ @Override
public void setDisplayRowColHeadings(boolean show) {
getSheetTypeSheetView().setShowRowColHeaders(show);
}
*
* @return whether gridlines are printed
*/
+ @Override
public boolean isPrintGridlines() {
CTPrintOptions opts = worksheet.getPrintOptions();
return opts != null && opts.getGridLines();
*
* @param value boolean to turn on or off the printing of gridlines
*/
+ @Override
public void setPrintGridlines(boolean value) {
CTPrintOptions opts = worksheet.isSetPrintOptions() ?
worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
* @param row index of the row to test
* @return <code>true</code> if there is a page break at the indicated row
*/
+ @Override
public boolean isRowBroken(int row) {
int[] rowBreaks = getRowBreaks();
- for (int i = 0 ; i < rowBreaks.length ; i++) {
- if (rowBreaks[i] == row) {
+ for (int rowBreak : rowBreaks) {
+ if (rowBreak == row) {
return true;
}
}
*
* @param row the row to break, inclusive
*/
+ @Override
public void setRowBreak(int row) {
CTPageBreak pgBreak = worksheet.isSetRowBreaks() ? worksheet.getRowBreaks() : worksheet.addNewRowBreaks();
if (! isRowBroken(row)) {
/**
* Removes a page break at the indicated column
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public void removeColumnBreak(int column) {
if (!worksheet.isSetColBreaks()) {
*
* @param index of the region to unmerge
*/
+ @Override
public void removeMergedRegion(int index) {
CTMergeCells ctMergeCells = worksheet.getMergeCells();
*
* @param row the row to remove.
*/
+ @Override
public void removeRow(Row row) {
if (row.getSheet() != this) {
throw new IllegalArgumentException("Specified row does not belong to this sheet");
/**
* Removes the page break at the indicated row
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public void removeRowBreak(int row) {
if(!worksheet.isSetRowBreaks()) {
*
* @see org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)
*/
+ @Override
public void setForceFormulaRecalculation(boolean value) {
CTCalcPr calcPr = getWorkbook().getCTWorkbook().getCalcPr();
* Whether Excel will be asked to recalculate all formulas when the
* workbook is opened.
*/
+ @Override
public boolean getForceFormulaRecalculation() {
if(worksheet.isSetSheetCalcPr()) {
CTSheetCalcPr calc = worksheet.getSheetCalcPr();
* be the third row if say for instance the second row is undefined.
* Call getRowNum() on each row if you care which one it is.
*/
+ @Override
@SuppressWarnings("unchecked")
- public Iterator<Row> rowIterator() {
+ public Iterator<Row> rowIterator() {
return (Iterator<Row>)(Iterator<? extends Row>) _rows.values().iterator();
}
* Alias for {@link #rowIterator()} to
* allow foreach loops
*/
+ @Override
public Iterator<Row> iterator() {
return rowIterator();
}
*
* @return <code>true</code> if the sheet displays Automatic Page Breaks.
*/
- public boolean getAutobreaks() {
+ @Override
+ public boolean getAutobreaks() {
CTSheetPr sheetPr = getSheetTypeSheetPr();
CTPageSetUpPr psSetup = (sheetPr == null || !sheetPr.isSetPageSetUpPr()) ?
CTPageSetUpPr.Factory.newInstance() : sheetPr.getPageSetUpPr();
*
* @param value <code>true</code> if the sheet displays Automatic Page Breaks.
*/
+ @Override
public void setAutobreaks(boolean value) {
CTSheetPr sheetPr = getSheetTypeSheetPr();
CTPageSetUpPr psSetup = sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr();
*
* @param column the column to break, inclusive
*/
+ @Override
public void setColumnBreak(int column) {
if (! isColumnBroken(column)) {
CTPageBreak pgBreak = worksheet.isSetColBreaks() ? worksheet.getColBreaks() : worksheet.addNewColBreaks();
}
}
+ @Override
public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) {
if (collapsed) {
collapseColumn(columnNumber);
* @param columnIndex - the column to get (0-based)
* @param hidden - the visiblity state of the column
*/
- public void setColumnHidden(int columnIndex, boolean hidden) {
+ @Override
+ public void setColumnHidden(int columnIndex, boolean hidden) {
columnHelper.setColHidden(columnIndex, hidden);
}
* @param width - the width in units of 1/256th of a character width
* @throws IllegalArgumentException if width > 255*256 (the maximum column width in Excel is 255 characters)
*/
+ @Override
public void setColumnWidth(int columnIndex, int width) {
if(width > 255*256) throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters.");
columnHelper.setCustomWidth(columnIndex, true);
}
+ @Override
public void setDefaultColumnStyle(int column, CellStyle style) {
columnHelper.setColDefaultStyle(column, style);
}
*
* @param width the number of characters. Default value is <code>8</code>.
*/
+ @Override
public void setDefaultColumnWidth(int width) {
getSheetTypeSheetFormatPr().setBaseColWidth(width);
}
*
* @param height default row height in twips (1/20 of a point)
*/
+ @Override
public void setDefaultRowHeight(short height) {
setDefaultRowHeightInPoints((float)height / 20);
}
*
* @param height default row height measured in point size.
*/
+ @Override
public void setDefaultRowHeightInPoints(float height) {
CTSheetFormatPr pr = getSheetTypeSheetFormatPr();
pr.setDefaultRowHeight(height);
*
* @param show <code>true</code> if this sheet should display formulas.
*/
+ @Override
public void setDisplayFormulas(boolean show) {
getSheetTypeSheetView().setShowFormulas(show);
}
*
* @param b <code>true</code> if the Fit to Page print option is enabled.
*/
- public void setFitToPage(boolean b) {
+ @Override
+ public void setFitToPage(boolean b) {
getSheetTypePageSetUpPr().setFitToPage(b);
}
*
* @param value whether to center on page horizontally when printing.
*/
+ @Override
public void setHorizontallyCenter(boolean value) {
CTPrintOptions opts = worksheet.isSetPrintOptions() ?
worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
*
* @param value true to vertically center, false otherwise.
*/
+ @Override
public void setVerticallyCenter(boolean value) {
CTPrintOptions opts = worksheet.isSetPrintOptions() ?
worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
* @param collapse -
* boolean value for collapse
*/
+ @Override
public void setRowGroupCollapsed(int rowIndex, boolean collapse) {
if (collapse) {
collapseRow(rowIndex);
int level = xRow.getCTRow().getOutlineLevel();
for (Iterator<Row> it = rowIterator(); it.hasNext();) {
xRow = (XSSFRow) it.next();
-
+
// skip rows before the start of this group
if(xRow.getRowNum() < rowIndex) {
continue;
* @param denominator The denominator for the zoom magnification.
* @see #setZoom(int)
*/
+ @Override
public void setZoom(int numerator, int denominator) {
int zoom = 100*numerator/denominator;
setZoom(zoom);
* @param endRow the row to end shifting
* @param n the number of rows to shift
*/
+ @Override
public void shiftRows(int startRow, int endRow, int n) {
shiftRows(startRow, endRow, n, false, false);
}
* @param copyRowHeight whether to copy the row height during the shift
* @param resetOriginalRowHeight whether to set the original row's height to the default
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) {
- // first remove all rows which will be overwritten
- for (Iterator<Row> it = rowIterator() ; it.hasNext() ; ) {
+ // first remove all rows which will be overwritten
+ for (Iterator<Row> it = rowIterator() ; it.hasNext() ; ) {
XSSFRow row = (XSSFRow)it.next();
int rownum = row.getRowNum();
-
+
// check if we should remove this row as it will be overwritten by the data later
if (removeRow(startRow, endRow, n, rownum)) {
- // remove row from worksheet.getSheetData row array
- int idx = _rows.headMap(row.getRowNum()).size();
- worksheet.getSheetData().removeRow(idx);
+ // remove row from worksheet.getSheetData row array
+ int idx = _rows.headMap(row.getRowNum()).size();
+ worksheet.getSheetData().removeRow(idx);
// remove row from _rows
it.remove();
}
- }
+ }
- // then do the actual moving and also adjust comments/rowHeight
- for (Iterator<Row> it = rowIterator() ; it.hasNext() ; ) {
+ // then do the actual moving and also adjust comments/rowHeight
+ for (Iterator<Row> it = rowIterator() ; it.hasNext() ; ) {
XSSFRow row = (XSSFRow)it.next();
int rownum = row.getRowNum();
-
+
if(sheetComments != null){
//TODO shift Note's anchor in the associated /xl/drawing/vmlDrawings#.vml
CTCommentList lst = sheetComments.getCTComments().getCommentList();
}
}
}
-
+
if(rownum < startRow || rownum > endRow) continue;
if (!copyRowHeight) {
* @param toprow the top row to show in desktop window pane
* @param leftcol the left column to show in desktop window pane
*/
+ @Override
public void showInPane(int toprow, int leftcol) {
CellReference cellReference = new CellReference(toprow, leftcol);
String cellRef = cellReference.formatAsString();
*
* @deprecated Use {@link #showInPane(int, int)} as there can be more than 32767 rows.
*/
+ @Override
@Deprecated
- public void showInPane(short toprow, short leftcol) {
+ public void showInPane(short toprow, short leftcol) {
showInPane((int)toprow, (int)leftcol);
}
+ @Override
public void ungroupColumn(int fromColumn, int toColumn) {
CTCols cols = worksheet.getColsArray(0);
for (int index = fromColumn; index <= toColumn; index++) {
* @param fromRow start row (0-based)
* @param toRow end row (0-based)
*/
+ @Override
public void ungroupRow(int fromRow, int toRow) {
for (int i = fromRow; i <= toRow; i++) {
XSSFRow xrow = getRow(i);
*
* @return <code>true</code> if this sheet is selected
*/
+ @Override
public boolean isSelected() {
CTSheetView view = getDefaultSheetView();
return view != null && view.getTabSelected();
*
* @param value <code>true</code> if this sheet is selected
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public void setSelected(boolean value) {
CTSheetViews views = getSheetTypeSheetViews();
}
private boolean removeRow(int startRow, int endRow, int n, int rownum) {
- // is this row in the target-window where the moved rows will land?
+ // is this row in the target-window where the moved rows will land?
if (rownum >= (startRow + n) && rownum <= (endRow + n)) {
- // only remove it if the current row is not part of the data that is copied
+ // only remove it if the current row is not part of the data that is copied
if (n > 0 && rownum > endRow) {
return true;
}
}
protected void write(OutputStream out) throws IOException {
- boolean setToNull = false;
+ boolean setToNull = false;
if(worksheet.sizeOfColsArray() == 1) {
- CTCols col = worksheet.getColsArray(0);
+ CTCols col = worksheet.getColsArray(0);
if(col.sizeOfColArray() == 0) {
- setToNull = true;
- // this is necessary so that we do not write an empty <cols/> item into the sheet-xml in the xlsx-file
- // Excel complains about a corrupted file if this shows up there!
+ setToNull = true;
+ // this is necessary so that we do not write an empty <cols/> item into the sheet-xml in the xlsx-file
+ // Excel complains about a corrupted file if this shows up there!
worksheet.setColsArray(null);
} else {
- setColWidthAttribute(col);
+ setColWidthAttribute(col);
}
}
worksheet.save(out, xmlOptions);
// Bug 52233: Ensure that we have a col-array even if write() removed it
- if(setToNull) {
- worksheet.addNewCols();
- }
+ if(setToNull) {
+ worksheet.addNewCols();
+ }
}
/**
return SSCellRange.create(firstRow, firstColumn, height, width, temp, XSSFCell.class);
}
+ @Override
public CellRange<XSSFCell> setArrayFormula(String formula, CellRangeAddress range) {
CellRange<XSSFCell> cr = getCellRange(range);
return cr;
}
+ @Override
public CellRange<XSSFCell> removeArrayFormula(Cell cell) {
if (cell.getSheet() != this) {
throw new IllegalArgumentException("Specified cell does not belong to this sheet.");
}
- public DataValidationHelper getDataValidationHelper() {
- return dataValidationHelper;
- }
+ @Override
+ public DataValidationHelper getDataValidationHelper() {
+ return dataValidationHelper;
+ }
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public List<XSSFDataValidation> getDataValidations() {
- List<XSSFDataValidation> xssfValidations = new ArrayList<XSSFDataValidation>();
- CTDataValidations dataValidations = this.worksheet.getDataValidations();
- if( dataValidations!=null && dataValidations.getCount() > 0 ) {
- for (CTDataValidation ctDataValidation : dataValidations.getDataValidationArray()) {
- CellRangeAddressList addressList = new CellRangeAddressList();
-
- @SuppressWarnings("unchecked")
- List<String> sqref = ctDataValidation.getSqref();
- for (String stRef : sqref) {
- String[] regions = stRef.split(" ");
- for (int i = 0; i < regions.length; i++) {
- String[] parts = regions[i].split(":");
- CellReference begin = new CellReference(parts[0]);
- CellReference end = parts.length > 1 ? new CellReference(parts[1]) : begin;
- CellRangeAddress cellRangeAddress = new CellRangeAddress(begin.getRow(), end.getRow(), begin.getCol(), end.getCol());
- addressList.addCellRangeAddress(cellRangeAddress);
- }
- }
- XSSFDataValidation xssfDataValidation = new XSSFDataValidation(addressList, ctDataValidation);
- xssfValidations.add(xssfDataValidation);
- }
- }
- return xssfValidations;
- }
-
- public void addValidationData(DataValidation dataValidation) {
- XSSFDataValidation xssfDataValidation = (XSSFDataValidation)dataValidation;
- CTDataValidations dataValidations = worksheet.getDataValidations();
- if( dataValidations==null ) {
- dataValidations = worksheet.addNewDataValidations();
- }
- int currentCount = dataValidations.sizeOfDataValidationArray();
+ List<XSSFDataValidation> xssfValidations = new ArrayList<XSSFDataValidation>();
+ CTDataValidations dataValidations = this.worksheet.getDataValidations();
+ if( dataValidations!=null && dataValidations.getCount() > 0 ) {
+ for (CTDataValidation ctDataValidation : dataValidations.getDataValidationArray()) {
+ CellRangeAddressList addressList = new CellRangeAddressList();
+
+ @SuppressWarnings("unchecked")
+ List<String> sqref = ctDataValidation.getSqref();
+ for (String stRef : sqref) {
+ String[] regions = stRef.split(" ");
+ for (String region : regions) {
+ String[] parts = region.split(":");
+ CellReference begin = new CellReference(parts[0]);
+ CellReference end = parts.length > 1 ? new CellReference(parts[1]) : begin;
+ CellRangeAddress cellRangeAddress = new CellRangeAddress(begin.getRow(), end.getRow(), begin.getCol(), end.getCol());
+ addressList.addCellRangeAddress(cellRangeAddress);
+ }
+ }
+ XSSFDataValidation xssfDataValidation = new XSSFDataValidation(addressList, ctDataValidation);
+ xssfValidations.add(xssfDataValidation);
+ }
+ }
+ return xssfValidations;
+ }
+
+ @Override
+ public void addValidationData(DataValidation dataValidation) {
+ XSSFDataValidation xssfDataValidation = (XSSFDataValidation)dataValidation;
+ CTDataValidations dataValidations = worksheet.getDataValidations();
+ if( dataValidations==null ) {
+ dataValidations = worksheet.addNewDataValidations();
+ }
+ int currentCount = dataValidations.sizeOfDataValidationArray();
CTDataValidation newval = dataValidations.addNewDataValidation();
- newval.set(xssfDataValidation.getCtDdataValidation());
- dataValidations.setCount(currentCount + 1);
+ newval.set(xssfDataValidation.getCtDdataValidation());
+ dataValidations.setCount(currentCount + 1);
- }
+ }
+ @Override
public XSSFAutoFilter setAutoFilter(CellRangeAddress range) {
CTAutoFilter af = worksheet.getAutoFilter();
if(af == null) af = worksheet.addNewAutoFilter();
if (name == null) {
name = wb.createBuiltInName(XSSFName.BUILTIN_FILTER_DB, sheetIndex);
}
-
+
name.getCTName().setHidden(true);
CellReference r1 = new CellReference(getSheetName(), range.getFirstRow(), range.getFirstColumn(), true, true);
CellReference r2 = new CellReference(null, range.getLastRow(), range.getLastColumn(), true, true);
return tableList;
}
+ @Override
public XSSFSheetConditionalFormatting getSheetConditionalFormatting(){
return new XSSFSheetConditionalFormatting(this);
}
}
+ @Override
public CellRangeAddress getRepeatingRows() {
return getRepeatingRowsOrColums(true);
}
+ @Override
public CellRangeAddress getRepeatingColumns() {
return getRepeatingRowsOrColums(false);
}
+ @Override
public void setRepeatingRows(CellRangeAddress rowRangeRef) {
CellRangeAddress columnRangeRef = getRepeatingColumns();
setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
}
+ @Override
public void setRepeatingColumns(CellRangeAddress columnRangeRef) {
CellRangeAddress rowRangeRef = getRepeatingRows();
setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef);
* // work with the wb object
* ......
* pkg.close(); // gracefully closes the underlying zip file
- * </code></pre>
+ * </code></pre>
*/
public XSSFWorkbook(InputStream is) throws IOException {
super(PackageHelper.open(is));
-
+
//build a tree of POIXMLDocumentParts, this workbook being the root
load(XSSFFactory.getInstance());
}
* then pass the data to ZipInputStream.
* </li>
* <ol>
- * <p>
+ * <p>
* It should be noted, that (2) uses quite a bit more memory than (1), which
* doesn't need to hold the whole zip file in memory, and can take advantage
* of native methods.
* // work with the wb object
* ......
* pkg.close(); // gracefully closes the underlying zip file
- * </code></pre>
+ * </code></pre>
* </p>
- *
+ *
* @param path the file name.
* @deprecated
*/
* @see Workbook#PICTURE_TYPE_DIB
* @see #getAllPictures()
*/
+ @Override
public int addPicture(byte[] pictureData, int format) {
int imageNumber = getAllPictures().size() + 1;
XSSFPictureData img = (XSSFPictureData)createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true);
* @throws IllegalArgumentException if the sheet index in invalid
* @throws POIXMLException if there were errors when cloning
*/
+ @Override
public XSSFSheet cloneSheet(int sheetNum) {
validateSheetIndex(sheetNum);
*
* @return the new XSSFCellStyle object
*/
+ @Override
public XSSFCellStyle createCellStyle() {
return stylesSource.createCellStyle();
}
* @return the XSSFDataFormat object
* @see org.apache.poi.ss.usermodel.DataFormat
*/
+ @Override
public XSSFDataFormat createDataFormat() {
if (formatter == null)
formatter = new XSSFDataFormat(stylesSource);
*
* @return new font object
*/
+ @Override
public XSSFFont createFont() {
XSSFFont font = new XSSFFont();
font.registerTo(stylesSource);
return font;
}
+ @Override
public XSSFName createName() {
CTDefinedName ctName = CTDefinedName.Factory.newInstance();
ctName.setName("");
*
* @return XSSFSheet representing the new sheet.
*/
+ @Override
public XSSFSheet createSheet() {
String sheetname = "Sheet" + (sheets.size());
int idx = 0;
* or workbook already contains a sheet with this name
* @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
*/
+ @Override
public XSSFSheet createSheet(String sheetname) {
if (sheetname == null) {
throw new IllegalArgumentException("sheetName must not be null");
/**
* Finds a font that matches the one with the supplied attributes
*/
+ @Override
public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
return stylesSource.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline);
}
* which is currently displayed when the workbook is viewed in Excel.
* 'Selected' sheet(s) is a distinct concept.
*/
+ @Override
public int getActiveSheetIndex() {
//activeTab (Active Sheet Index) Specifies an unsignedInt
//that contains the index to the active sheet in this book view.
* @return the list of pictures (a list of {@link XSSFPictureData} objects.)
* @see #addPicture(byte[], int)
*/
+ @Override
public List<XSSFPictureData> getAllPictures() {
if(pictures == null){
List<PackagePart> mediaParts = getPackage().getPartsByName(Pattern.compile("/xl/media/.*?"));
* @param idx index within the set of styles
* @return XSSFCellStyle object at the index
*/
+ @Override
public XSSFCellStyle getCellStyleAt(short idx) {
return stylesSource.getStyleAt(idx);
}
* @param idx index number
* @return XSSFFont at the index
*/
+ @Override
public XSSFFont getFontAt(short idx) {
return stylesSource.getFontAt(idx);
}
+ @Override
public XSSFName getName(String name) {
int nameIndex = getNameIndex(name);
if (nameIndex < 0) {
return namedRanges.get(nameIndex);
}
+ @Override
public XSSFName getNameAt(int nameIndex) {
int nNames = namedRanges.size();
if (nNames < 1) {
* @param name named range name
* @return named range index
*/
+ @Override
public int getNameIndex(String name) {
int i = 0;
for(XSSFName nr : namedRanges) {
*
* @return count of cell styles
*/
+ @Override
public short getNumCellStyles() {
return (short) (stylesSource).getNumCellStyles();
}
*
* @return number of fonts
*/
+ @Override
public short getNumberOfFonts() {
return (short)stylesSource.getFonts().size();
}
*
* @return number of named ranges
*/
+ @Override
public int getNumberOfNames() {
return namedRanges.size();
}
*
* @return number of worksheets
*/
+ @Override
public int getNumberOfSheets() {
return sheets.size();
}
* @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
* @return String Null if no print area has been defined
*/
+ @Override
public String getPrintArea(int sheetIndex) {
XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
if (name == null) return null;
* @param name of the sheet
* @return XSSFSheet with the name provided or <code>null</code> if it does not exist
*/
+ @Override
public XSSFSheet getSheet(String name) {
for (XSSFSheet sheet : sheets) {
if (name.equalsIgnoreCase(sheet.getSheetName())) {
* @throws IllegalArgumentException if the index is out of range (index
* < 0 || index >= getNumberOfSheets()).
*/
+ @Override
public XSSFSheet getSheetAt(int index) {
validateSheetIndex(index);
return sheets.get(index);
* @param name the sheet name
* @return index of the sheet (0 based) or <tt>-1</tt if not found
*/
+ @Override
public int getSheetIndex(String name) {
for (int i = 0 ; i < sheets.size() ; ++i) {
XSSFSheet sheet = sheets.get(i);
* @param sheet the sheet to look up
* @return index of the sheet (0 based). <tt>-1</tt> if not found
*/
+ @Override
public int getSheetIndex(Sheet sheet) {
int idx = 0;
for(XSSFSheet sh : sheets){
* @param sheetIx Number
* @return Sheet name
*/
+ @Override
public String getSheetName(int sheetIx) {
validateSheetIndex(sheetIx);
return sheets.get(sheetIx).getSheetName();
* }
* </code></pre>
*/
+ @Override
public Iterator<XSSFSheet> iterator() {
return sheets.iterator();
}
return getPackagePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType());
}
+ @Override
public void removeName(int nameIndex) {
namedRanges.remove(nameIndex);
}
+ @Override
public void removeName(String name) {
for (int i = 0; i < namedRanges.size(); i++) {
XSSFName nm = namedRanges.get(i);
/**
- * As {@link #removeName(String)} is not necessarily unique
+ * As {@link #removeName(String)} is not necessarily unique
* (name + sheet index is unique), this method is more accurate.
- *
+ *
* @param name the name to remove.
*/
void removeName(XSSFName name) {
*
* @param sheetIndex 0-based sheet index (0 = First Sheet)
*/
+ @Override
public void removePrintArea(int sheetIndex) {
int cont = 0;
for (XSSFName name : namedRanges) {
*
* @param index of the sheet (0-based)
*/
+ @Override
public void removeSheetAt(int index) {
validateSheetIndex(index);
* The default is to return blank and null cells.
* {@link MissingCellPolicy}
*/
+ @Override
public MissingCellPolicy getMissingCellPolicy() {
return _missingCellPolicy;
}
* {@link Row#getCell(int)}}. See
* {@link MissingCellPolicy}
*/
+ @Override
public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) {
_missingCellPolicy = missingCellPolicy;
}
* which is currently displayed when the workbook is viewed in Excel.
* 'Selected' sheet(s) is a distinct concept.
*/
+ @Override
@SuppressWarnings("deprecation") //YK: getXYZArray() array accessors are deprecated in xmlbeans with JDK 1.5 support
public void setActiveSheet(int index) {
*
* @return integer that contains the index to the active sheet in this book view.
*/
+ @Override
public int getFirstVisibleTab() {
CTBookViews bookViews = workbook.getBookViews();
CTBookView bookView = bookViews.getWorkbookViewArray(0);
*
* @param index integer that contains the index to the active sheet in this book view.
*/
+ @Override
public void setFirstVisibleTab(int index) {
CTBookViews bookViews = workbook.getBookViews();
CTBookView bookView= bookViews.getWorkbookViewArray(0);
* @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
* @param reference Valid name Reference for the Print Area
*/
+ @Override
public void setPrintArea(int sheetIndex, String reference) {
XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
if (name == null) {
* @param startRow Row to begin the printarea
* @param endRow Row to end the printarea
*/
+ @Override
public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) {
String reference=getReferencePrintArea(getSheetName(sheetIndex), startColumn, endColumn, startRow, endRow);
setPrintArea(sheetIndex, reference);
* @param endColumn 0 based end of repeating columns.
* @param startRow 0 based start of repeating rows.
* @param endRow 0 based end of repeating rows.
- *
+ *
* @deprecated use {@link XSSFSheet#setRepeatingRows(CellRangeAddress)}
* or {@link XSSFSheet#setRepeatingColumns(CellRangeAddress)}
*/
+ @Deprecated
+ @Override
public void setRepeatingRowsAndColumns(int sheetIndex,
int startColumn, int endColumn,
int startRow, int endRow) {
XSSFSheet sheet = getSheetAt(sheetIndex);
-
+
CellRangeAddress rows = null;
CellRangeAddress cols = null;
-
+
if (startRow != -1) {
rows = new CellRangeAddress(startRow, endRow, -1, -1);
}
/**
* We only set one sheet as selected for compatibility with HSSF.
*/
+ @Override
public void setSelectedTab(int index) {
for (int i = 0 ; i < sheets.size() ; ++i) {
XSSFSheet sheet = sheets.get(i);
* @see #createSheet(String)
* @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)
*/
+ @Override
public void setSheetName(int sheetIndex, String sheetname) {
validateSheetIndex(sheetIndex);
* @param sheetname the name of the sheet to reorder
* @param pos the position that we want to insert the sheet into (0 based)
*/
+ @Override
public void setSheetOrder(String sheetname, int pos) {
int idx = getSheetIndex(sheetname);
sheets.add(pos, sheets.remove(idx));
* Returns an object that handles instantiating concrete
* classes of the various instances for XSSF.
*/
+ @Override
public XSSFCreationHelper getCreationHelper() {
if(_creationHelper == null) _creationHelper = new XSSFCreationHelper(this);
return _creationHelper;
return embedds;
}
+ @Override
public boolean isHidden() {
throw new RuntimeException("Not implemented yet");
}
+ @Override
public void setHidden(boolean hiddenFlag) {
throw new RuntimeException("Not implemented yet");
}
* @param sheetIx Number
* @return <code>true</code> if sheet is hidden
*/
+ @Override
public boolean isSheetHidden(int sheetIx) {
validateSheetIndex(sheetIx);
CTSheet ctSheet = sheets.get(sheetIx).sheet;
* @param sheetIx sheet index to check
* @return <code>true</code> if sheet is very hidden
*/
+ @Override
public boolean isSheetVeryHidden(int sheetIx) {
validateSheetIndex(sheetIx);
CTSheet ctSheet = sheets.get(sheetIx).sheet;
* @param hidden whether this sheet is hidden
* @see #setSheetHidden(int, int)
*/
+ @Override
public void setSheetHidden(int sheetIx, boolean hidden) {
setSheetHidden(sheetIx, hidden ? SHEET_STATE_HIDDEN : SHEET_STATE_VISIBLE);
}
* <code>Workbook.SHEET_STATE_VERY_HIDDEN</code>.
* @throws IllegalArgumentException if the supplied sheet index or state is invalid
*/
+ @Override
public void setSheetHidden(int sheetIx, int state) {
validateSheetIndex(sheetIx);
WorkbookUtil.validateSheetState(state);
* A value true indicates the structure of the workbook is locked. Worksheets in the workbook can't be moved,
* deleted, hidden, unhidden, or renamed, and new worksheets can't be inserted.<br/>
* A value of false indicates the structure of the workbook is not locked.<br/>
- *
+ *
* @return true if structure of workbook is locked
*/
public boolean isStructureLocked() {
* A value of true indicates the workbook windows are locked. Windows are the same size and position each time the
* workbook is opened.<br/>
* A value of false indicates the workbook windows are not locked.
- *
+ *
* @return true if windows that comprise the workbook are locked
*/
public boolean isWindowsLocked() {
/**
* Specifies a boolean value that indicates whether the workbook is locked for revisions.
- *
+ *
* @return true if the workbook is locked for revisions.
*/
public boolean isRevisionLocked() {
return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockRevision();
}
-
+
/**
* Locks the structure of workbook.
*/
createProtectionFieldIfNotPresent();
workbook.getWorkbookProtection().setLockStructure(true);
}
-
+
/**
* Unlocks the structure of workbook.
*/
}
/**
- * Locks the windows that comprise the workbook.
+ * Locks the windows that comprise the workbook.
*/
public void lockWindows() {
createProtectionFieldIfNotPresent();
workbook.getWorkbookProtection().setLockWindows(true);
}
-
+
/**
- * Unlocks the windows that comprise the workbook.
+ * Unlocks the windows that comprise the workbook.
*/
public void unLockWindows() {
createProtectionFieldIfNotPresent();
workbook.getWorkbookProtection().setLockWindows(false);
}
-
+
/**
* Locks the workbook for revisions.
*/
createProtectionFieldIfNotPresent();
workbook.getWorkbookProtection().setLockRevision(false);
}
-
+
private boolean workbookProtectionPresent() {
return workbook.getWorkbookProtection() != null;
}
*
* @param toopack the toolpack to register
*/
+ @Override
public void addToolPack(UDFFinder toopack){
_udfFinder.add(toopack);
}
* workbook values when the workbook is opened
* @since 3.8
*/
- public void setForceFormulaRecalculation(boolean value){
+ @Override
+ public void setForceFormulaRecalculation(boolean value){
CTWorkbook ctWorkbook = getCTWorkbook();
CTCalcPr calcPr = ctWorkbook.isSetCalcPr() ? ctWorkbook.getCalcPr() : ctWorkbook.addNewCalcPr();
// when set to 0, will tell Excel that it needs to recalculate all formulas
*
* @since 3.8
*/
+ @Override
public boolean getForceFormulaRecalculation(){
CTWorkbook ctWorkbook = getCTWorkbook();
CTCalcPr calcPr = ctWorkbook.getCalcPr();
assertNotNull(text);\r
assertEquals("This is password protected Word document.", text.trim());\r
ex.close();\r
+ \r
+ filesystem.close();\r
}\r
\r
/**\r
// I know ... a stupid typo, maybe next time ...\r
assertEquals("The is a password protected document.", text.trim());\r
ex.close();\r
+ \r
+ filesystem.close();\r
}\r
}\r
private List<Attachment> attachments = new ArrayList<Attachment>();
public HMEFMessage(InputStream inp) throws IOException {
- // Check the signature matches
- int sig = LittleEndian.readInt(inp);
- if(sig != HEADER_SIGNATURE) {
- throw new IllegalArgumentException(
- "TNEF signature not detected in file, " +
- "expected " + HEADER_SIGNATURE + " but got " + sig
- );
+ try {
+ // Check the signature matches
+ int sig = LittleEndian.readInt(inp);
+ if(sig != HEADER_SIGNATURE) {
+ throw new IllegalArgumentException(
+ "TNEF signature not detected in file, " +
+ "expected " + HEADER_SIGNATURE + " but got " + sig
+ );
+ }
+
+ // Read the File ID
+ fileId = LittleEndian.readUShort(inp);
+
+ // Now begin processing the contents
+ process(inp);
+ } finally {
+ inp.close();
}
-
- // Read the File ID
- fileId = LittleEndian.readUShort(inp);
-
- // Now begin processing the contents
- process(inp);
}
private void process(InputStream inp) throws IOException {
package org.apache.poi.hmef;
import java.io.IOException;
+import java.io.InputStream;
import junit.framework.TestCase;
}
protected void assertContents(String filename, byte[] actual)
throws IOException {
- byte[] expected = IOUtils.toByteArray(
- _samples.openResourceAsStream("quick-contents/" + filename)
- );
-
- assertEquals(expected.length, actual.length);
- for(int i=0; i<expected.length; i++) {
- assertEquals("Byte " + i + " wrong", expected[i], actual[i]);
+ InputStream stream = _samples.openResourceAsStream("quick-contents/" + filename);
+ try {
+ byte[] expected = IOUtils.toByteArray(stream);
+
+ assertEquals(expected.length, actual.length);
+ for(int i=0; i<expected.length; i++) {
+ assertEquals("Byte " + i + " wrong", expected[i], actual[i]);
+ }
+ } finally {
+ stream.close();
}
}
}
package org.apache.poi.hmef;
import java.io.ByteArrayInputStream;
+import java.io.InputStream;
import junit.framework.TestCase;
assertNotNull(attr);
MAPIRtfAttribute rtfAttr = (MAPIRtfAttribute)attr;
- byte[] expected = IOUtils.toByteArray(
- _samples.openResourceAsStream("quick-contents/message.rtf")
- );
-
- CompressedRTF comp = new CompressedRTF();
- byte[] data = rtfAttr.getRawData();
- byte[] decomp = comp.decompress(new ByteArrayInputStream(data));
-
- // Check the length was as expected
- assertEquals(data.length, comp.getCompressedSize() + 16);
- assertEquals(expected.length, comp.getDeCompressedSize());
-
- // Will have been padded though
- assertEquals(expected.length+2, decomp.length);
- byte[] tmp = new byte[expected.length];
- System.arraycopy(decomp, 0, tmp, 0, tmp.length);
- decomp = tmp;
-
- // By byte
- assertEquals(expected.length, decomp.length);
- for(int i=0; i<expected.length; i++) {
- assertEquals(expected[i], decomp[i]);
+ InputStream stream = _samples.openResourceAsStream("quick-contents/message.rtf");
+ try {
+ byte[] expected = IOUtils.toByteArray(stream);
+
+ CompressedRTF comp = new CompressedRTF();
+ byte[] data = rtfAttr.getRawData();
+ byte[] decomp = comp.decompress(new ByteArrayInputStream(data));
+
+ // Check the length was as expected
+ assertEquals(data.length, comp.getCompressedSize() + 16);
+ assertEquals(expected.length, comp.getDeCompressedSize());
+
+ // Will have been padded though
+ assertEquals(expected.length+2, decomp.length);
+ byte[] tmp = new byte[expected.length];
+ System.arraycopy(decomp, 0, tmp, 0, tmp.length);
+ decomp = tmp;
+
+ // By byte
+ assertEquals(expected.length, decomp.length);
+ for(int i=0; i<expected.length; i++) {
+ assertEquals(expected[i], decomp[i]);
+ }
+
+ // By String
+ String expString = new String(expected, "ASCII");
+ String decompStr = rtfAttr.getDataString();
+ assertEquals(expString.length(), decompStr.length());
+ assertEquals(expString, decompStr);
+ } finally {
+ stream.close();
}
-
- // By String
- String expString = new String(expected, "ASCII");
- String decompStr = rtfAttr.getDataString();
- assertEquals(expString.length(), decompStr.length());
- assertEquals(expString, decompStr);
}
}
package org.apache.poi.hmef.attribute;
import java.io.ByteArrayInputStream;
+import java.io.InputStream;
import java.text.DateFormat;
import java.util.Locale;
import java.util.TimeZone;
public final class TestMAPIAttributes extends TestCase {
private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance();
private HMEFMessage quick;
+ private InputStream stream;
@Override
protected void setUp() throws Exception {
super.setUp();
- quick = new HMEFMessage(
- _samples.openResourceAsStream("quick-winmail.dat")
- );
+ stream = _samples.openResourceAsStream("quick-winmail.dat");
+ quick = new HMEFMessage(stream);
}
-
- /**
+
+
+ protected void tearDown() throws Exception {
+ stream.close();
+
+ super.tearDown();
+ }
+
+
+/**
* Test counts
*/
public void testCounts() throws Exception {
assertEquals( SAMPLE_TEXT, ext.getText() );
// And with NPOIFS
- HPBFDocument docNPOIFS = new HPBFDocument(
- new NPOIFSFileSystem(sample)
+ NPOIFSFileSystem fs = new NPOIFSFileSystem(sample);
+ HPBFDocument docNPOIFS = new HPBFDocument(
+ fs
);
ext = new PublisherTextExtractor(docNPOIFS);
assertEquals( SAMPLE_TEXT, ext.getText() );
new FileInputStream(simple)
);
assertEquals( SIMPLE_TEXT, ext.getText() );
+ fs.close();
}
/**
// Open the two filesystems
DirectoryNode[] files = new DirectoryNode[2];
files[0] = (new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt"))).getRoot();
- files[1] = (new NPOIFSFileSystem(slTests.getFile("basic_test_ppt_file.ppt"))).getRoot();
+ NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(slTests.getFile("basic_test_ppt_file.ppt"));
+ files[1] = npoifsFileSystem.getRoot();
// Open directly
for(DirectoryNode dir : files) {
PowerPointExtractor extractor = new PowerPointExtractor(slideshow);
assertEquals(expectText, extractor.getText());
}
+
+ npoifsFileSystem.close();
}
public void testTable() throws Exception{
// Open the two filesystems
DirectoryNode[] files = new DirectoryNode[2];
files[0] = (new POIFSFileSystem(docTests.openResourceAsStream("test2.doc"))).getRoot();
- files[1] = (new NPOIFSFileSystem(docTests.getFile("test2.doc"))).getRoot();
+ NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(docTests.getFile("test2.doc"));
+ files[1] = npoifsFileSystem.getRoot();
// Open directly
for(DirectoryNode dir : files) {
WordExtractor extractor = new WordExtractor(doc);
assertEquals(p_text1_block, extractor.getText());
}
+
+ npoifsFileSystem.close();
}
/**
import java.lang.reflect.Field;
import junit.framework.TestCase;
+
import org.apache.poi.hwpf.HWPFDocFixture;
-public final class TestFileInformationBlock
- extends TestCase
-{
- private FileInformationBlock _fileInformationBlock = null;
- private HWPFDocFixture _hWPFDocFixture;
+public final class TestFileInformationBlock extends TestCase {
+ private FileInformationBlock _fileInformationBlock = null;
+ private HWPFDocFixture _hWPFDocFixture;
- public void testReadWrite()
- throws Exception
- {
- int size = _fileInformationBlock.getSize();
- byte[] buf = new byte[size];
+ public void testReadWrite() throws Exception {
+ int size = _fileInformationBlock.getSize();
+ byte[] buf = new byte[size];
- _fileInformationBlock.getFibBase().serialize(buf, 0);
+ _fileInformationBlock.getFibBase().serialize(buf, 0);
- FileInformationBlock newFileInformationBlock =
- new FileInformationBlock(buf);
+ FileInformationBlock newFileInformationBlock = new FileInformationBlock(
+ buf);
- Field[] fields = FileInformationBlock.class.getSuperclass().getDeclaredFields();
- AccessibleObject.setAccessible(fields, true);
+ Field[] fields = FileInformationBlock.class.getSuperclass()
+ .getDeclaredFields();
+ AccessibleObject.setAccessible(fields, true);
- for (int x = 0; x < fields.length; x++)
- {
- assertEquals(fields[x].get(_fileInformationBlock), fields[x].get(newFileInformationBlock));
+ for (int x = 0; x < fields.length; x++) {
+ assertEquals(fields[x].get(_fileInformationBlock),
+ fields[x].get(newFileInformationBlock));
+ }
+
+ assertNotNull(_fileInformationBlock.toString());
}
- }
-
- protected void setUp()
- throws Exception
- {
- super.setUp();
- /**@todo verify the constructors*/
- _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE);
- _hWPFDocFixture.setUp();
- _fileInformationBlock = _hWPFDocFixture._fib;
- }
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ /** @todo verify the constructors */
+ _hWPFDocFixture = new HWPFDocFixture(this,
+ HWPFDocFixture.DEFAULT_TEST_FILE);
- protected void tearDown()
- throws Exception
- {
- _fileInformationBlock = null;
- _hWPFDocFixture.tearDown();
+ _hWPFDocFixture.setUp();
+ _fileInformationBlock = _hWPFDocFixture._fib;
+ }
- _hWPFDocFixture = null;
- super.tearDown();
- }
+ @Override
+ protected void tearDown() throws Exception {
+ _fileInformationBlock = null;
+ _hWPFDocFixture.tearDown();
+ _hWPFDocFixture = null;
+ super.tearDown();
+ }
}
import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.apache.poi.hwpf.model.io.HWPFFileSystem;
-
+@SuppressWarnings("deprecation")
public final class TestTextPieceTable extends TestCase {
- private HWPFDocFixture _hWPFDocFixture;
- //private String dirname;
-
- public void testReadWrite()
- throws Exception
- {
- FileInformationBlock fib = _hWPFDocFixture._fib;
- byte[] mainStream = _hWPFDocFixture._mainStream;
- byte[] tableStream = _hWPFDocFixture._tableStream;
- int fcMin = fib.getFibBase().getFcMin();
-
- ComplexFileTable cft = new ComplexFileTable(mainStream, tableStream, fib.getFcClx(), fcMin);
-
-
- HWPFFileSystem fileSys = new HWPFFileSystem();
-
- cft.writeTo(fileSys);
- ByteArrayOutputStream tableOut = fileSys.getStream("1Table");
- ByteArrayOutputStream mainOut = fileSys.getStream("WordDocument");
-
- byte[] newTableStream = tableOut.toByteArray();
- byte[] newMainStream = mainOut.toByteArray();
-
- ComplexFileTable newCft = new ComplexFileTable(newMainStream, newTableStream, 0,0);
-
- TextPieceTable oldTextPieceTable = cft.getTextPieceTable();
- TextPieceTable newTextPieceTable = newCft.getTextPieceTable();
-
- assertEquals(oldTextPieceTable, newTextPieceTable);
- }
-
- /**
- * Check that we do the positions correctly when
- * working with pure-ascii
- */
- public void testAsciiParts() throws Exception {
- HWPFDocument doc = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc");
- TextPieceTable tbl = doc.getTextTable();
-
- // All ascii, so stored in one big lump
- assertEquals(1, tbl.getTextPieces().size());
- TextPiece tp = tbl.getTextPieces().get(0);
-
- assertEquals(0, tp.getStart());
- assertEquals(339, tp.getEnd());
- assertEquals(339, tp.characterLength());
- assertEquals(339, tp.bytesLength());
- assertTrue(tp.getStringBuilder().toString().startsWith("This is a sample word document"));
-
-
- // Save and re-load
- HWPFDocument docB = saveAndReload(doc);
- tbl = docB.getTextTable();
-
- assertEquals(1, tbl.getTextPieces().size());
- tp = tbl.getTextPieces().get(0);
-
- assertEquals(0, tp.getStart());
- assertEquals(339, tp.getEnd());
- assertEquals(339, tp.characterLength());
- assertEquals(339, tp.bytesLength());
- assertTrue(tp.getStringBuilder().toString().startsWith("This is a sample word document"));
- }
-
- /**
- * Check that we do the positions correctly when
- * working with a mix ascii, unicode file
- */
- public void testUnicodeParts() throws Exception {
- HWPFDocument doc = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc");
- TextPieceTable tbl = doc.getTextTable();
-
- // In three bits, split every 512 bytes
- assertEquals(3, tbl.getTextPieces().size());
- TextPiece tpA = (TextPiece)tbl.getTextPieces().get(0);
- TextPiece tpB = (TextPiece)tbl.getTextPieces().get(1);
- TextPiece tpC = (TextPiece)tbl.getTextPieces().get(2);
-
- assertTrue(tpA.isUnicode());
- assertTrue(tpB.isUnicode());
- assertTrue(tpC.isUnicode());
-
- assertEquals(256, tpA.characterLength());
- assertEquals(256, tpB.characterLength());
- assertEquals(19, tpC.characterLength());
-
- assertEquals(512, tpA.bytesLength());
- assertEquals(512, tpB.bytesLength());
- assertEquals(38, tpC.bytesLength());
-
- assertEquals(0, tpA.getStart());
- assertEquals(256, tpA.getEnd());
- assertEquals(256, tpB.getStart());
- assertEquals(512, tpB.getEnd());
- assertEquals(512, tpC.getStart());
- assertEquals(531, tpC.getEnd());
-
-
- // Save and re-load
- HWPFDocument docB = saveAndReload(doc);
- tbl = docB.getTextTable();
-
- assertEquals(3, tbl.getTextPieces().size());
- tpA = (TextPiece)tbl.getTextPieces().get(0);
- tpB = (TextPiece)tbl.getTextPieces().get(1);
- tpC = (TextPiece)tbl.getTextPieces().get(2);
-
- assertTrue(tpA.isUnicode());
- assertTrue(tpB.isUnicode());
- assertTrue(tpC.isUnicode());
-
- assertEquals(256, tpA.characterLength());
- assertEquals(256, tpB.characterLength());
- assertEquals(19, tpC.characterLength());
-
- assertEquals(512, tpA.bytesLength());
- assertEquals(512, tpB.bytesLength());
- assertEquals(38, tpC.bytesLength());
-
- assertEquals(0, tpA.getStart());
- assertEquals(256, tpA.getEnd());
- assertEquals(256, tpB.getStart());
- assertEquals(512, tpB.getEnd());
- assertEquals(512, tpC.getStart());
- assertEquals(531, tpC.getEnd());
- }
-
- protected HWPFDocument saveAndReload(HWPFDocument doc) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- doc.write(baos);
-
- return new HWPFDocument(
- new ByteArrayInputStream(baos.toByteArray())
- );
- }
-
- protected void setUp()
- throws Exception
- {
- super.setUp();
- System.setProperty( "org.apache.poi.hwpf.preserveTextTable", Boolean.TRUE.toString() );
-
- _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE);
- _hWPFDocFixture.setUp();
- }
-
- protected void tearDown()
- throws Exception
- {
- _hWPFDocFixture.tearDown();
- _hWPFDocFixture = null;
-
- System.setProperty( "org.apache.poi.hwpf.preserveTextTable", Boolean.FALSE.toString() );
- super.tearDown();
- }
+ private HWPFDocFixture _hWPFDocFixture;
+
+ // private String dirname;
+
+ public void testReadWrite() throws Exception {
+ FileInformationBlock fib = _hWPFDocFixture._fib;
+ byte[] mainStream = _hWPFDocFixture._mainStream;
+ byte[] tableStream = _hWPFDocFixture._tableStream;
+ int fcMin = fib.getFibBase().getFcMin();
+
+ ComplexFileTable cft = new ComplexFileTable(mainStream, tableStream,
+ fib.getFcClx(), fcMin);
+
+ HWPFFileSystem fileSys = new HWPFFileSystem();
+
+ cft.writeTo(fileSys);
+ ByteArrayOutputStream tableOut = fileSys.getStream("1Table");
+ ByteArrayOutputStream mainOut = fileSys.getStream("WordDocument");
+
+ byte[] newTableStream = tableOut.toByteArray();
+ byte[] newMainStream = mainOut.toByteArray();
+
+ ComplexFileTable newCft = new ComplexFileTable(newMainStream,
+ newTableStream, 0, 0);
+
+ TextPieceTable oldTextPieceTable = cft.getTextPieceTable();
+ TextPieceTable newTextPieceTable = newCft.getTextPieceTable();
+
+ assertEquals(oldTextPieceTable, newTextPieceTable);
+ }
+
+ /**
+ * Check that we do the positions correctly when working with pure-ascii
+ */
+ public void testAsciiParts() throws Exception {
+ HWPFDocument doc = HWPFTestDataSamples
+ .openSampleFile("ThreeColHeadFoot.doc");
+ TextPieceTable tbl = doc.getTextTable();
+
+ // All ascii, so stored in one big lump
+ assertEquals(1, tbl.getTextPieces().size());
+ TextPiece tp = tbl.getTextPieces().get(0);
+
+ assertEquals(0, tp.getStart());
+ assertEquals(339, tp.getEnd());
+ assertEquals(339, tp.characterLength());
+ assertEquals(339, tp.bytesLength());
+ assertTrue(tp.getStringBuilder().toString()
+ .startsWith("This is a sample word document"));
+
+ // Save and re-load
+ HWPFDocument docB = saveAndReload(doc);
+ tbl = docB.getTextTable();
+
+ assertEquals(1, tbl.getTextPieces().size());
+ tp = tbl.getTextPieces().get(0);
+
+ assertEquals(0, tp.getStart());
+ assertEquals(339, tp.getEnd());
+ assertEquals(339, tp.characterLength());
+ assertEquals(339, tp.bytesLength());
+ assertTrue(tp.getStringBuilder().toString()
+ .startsWith("This is a sample word document"));
+ }
+
+ /**
+ * Check that we do the positions correctly when working with a mix ascii,
+ * unicode file
+ */
+ public void testUnicodeParts() throws Exception {
+ HWPFDocument doc = HWPFTestDataSamples
+ .openSampleFile("HeaderFooterUnicode.doc");
+ TextPieceTable tbl = doc.getTextTable();
+
+ // In three bits, split every 512 bytes
+ assertEquals(3, tbl.getTextPieces().size());
+ TextPiece tpA = tbl.getTextPieces().get(0);
+ TextPiece tpB = tbl.getTextPieces().get(1);
+ TextPiece tpC = tbl.getTextPieces().get(2);
+
+ assertTrue(tpA.isUnicode());
+ assertTrue(tpB.isUnicode());
+ assertTrue(tpC.isUnicode());
+
+ assertEquals(256, tpA.characterLength());
+ assertEquals(256, tpB.characterLength());
+ assertEquals(19, tpC.characterLength());
+
+ assertEquals(512, tpA.bytesLength());
+ assertEquals(512, tpB.bytesLength());
+ assertEquals(38, tpC.bytesLength());
+
+ assertEquals(0, tpA.getStart());
+ assertEquals(256, tpA.getEnd());
+ assertEquals(256, tpB.getStart());
+ assertEquals(512, tpB.getEnd());
+ assertEquals(512, tpC.getStart());
+ assertEquals(531, tpC.getEnd());
+
+ // Save and re-load
+ HWPFDocument docB = saveAndReload(doc);
+ tbl = docB.getTextTable();
+
+ assertEquals(3, tbl.getTextPieces().size());
+ tpA = tbl.getTextPieces().get(0);
+ tpB = tbl.getTextPieces().get(1);
+ tpC = tbl.getTextPieces().get(2);
+
+ assertTrue(tpA.isUnicode());
+ assertTrue(tpB.isUnicode());
+ assertTrue(tpC.isUnicode());
+
+ assertEquals(256, tpA.characterLength());
+ assertEquals(256, tpB.characterLength());
+ assertEquals(19, tpC.characterLength());
+
+ assertEquals(512, tpA.bytesLength());
+ assertEquals(512, tpB.bytesLength());
+ assertEquals(38, tpC.bytesLength());
+
+ assertEquals(0, tpA.getStart());
+ assertEquals(256, tpA.getEnd());
+ assertEquals(256, tpB.getStart());
+ assertEquals(512, tpB.getEnd());
+ assertEquals(512, tpC.getStart());
+ assertEquals(531, tpC.getEnd());
+ }
+
+ protected HWPFDocument saveAndReload(HWPFDocument doc) throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ doc.write(baos);
+
+ return new HWPFDocument(new ByteArrayInputStream(baos.toByteArray()));
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ System.setProperty("org.apache.poi.hwpf.preserveTextTable",
+ Boolean.TRUE.toString());
+
+ _hWPFDocFixture = new HWPFDocFixture(this,
+ HWPFDocFixture.DEFAULT_TEST_FILE);
+ _hWPFDocFixture.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ _hWPFDocFixture.tearDown();
+ _hWPFDocFixture = null;
+
+ System.setProperty("org.apache.poi.hwpf.preserveTextTable",
+ Boolean.FALSE.toString());
+ super.tearDown();
+ }
}
// document as text file using encoding UTF-8)
InputStream is = POIDataSamples.getDocumentInstance()
.openResourceAsStream( "Bug47742-text.txt" );
- byte[] expectedBytes = IOUtils.toByteArray( is );
- String expectedText = new String( expectedBytes, "utf-8" )
- .substring( 1 ); // strip-off the unicode marker
-
- assertEquals( expectedText, foundText );
+ try {
+ byte[] expectedBytes = IOUtils.toByteArray( is );
+ String expectedText = new String( expectedBytes, "utf-8" )
+ .substring( 1 ); // strip-off the unicode marker
+
+ assertEquals( expectedText, foundText );
+ } finally {
+ is.close();
+ }
}
/**
assertNotNull(psa[0]);
assertTrue(psa[0].isSummaryInformation());
- final Section s = (Section) (psa[0].getSections().get(0));
+ final Section s = (psa[0].getSections().get(0));
Object p1 = s.getProperty(PropertyIDMap.PID_AUTHOR);
Object p2 = s.getProperty(PropertyIDMap.PID_TITLE);
assertEquals(AUTHOR, p1);
stream.close();
}
assertNotNull(psa[0]);
- Section s = (Section) (psa[0].getSections().get(0));
+ Section s = (psa[0].getSections().get(0));
assertEquals(s.getFormatID(), formatID);
Object p = s.getProperty(2);
assertEquals(SECTION1, p);
- s = (Section) (psa[0].getSections().get(1));
+ s = (psa[0].getSections().get(1));
p = s.getProperty(2);
assertEquals(SECTION2, p);
}
PropertySet psr = new PropertySet(bytes);
assertTrue(psr.isSummaryInformation());
- Section sr = (Section) psr.getSections().get(0);
+ Section sr = psr.getSections().get(0);
String title = (String) sr.getProperty(PropertyIDMap.PID_TITLE);
assertEquals(TITLE, title);
}
final String[] poiFiles)
throws FileNotFoundException, IOException
{
- final List files = new ArrayList();
+ final List<POIFile> files = new ArrayList<POIFile>();
POIFSReader r = new POIFSReader();
POIFSReaderListener pfl = new POIFSReaderListener()
{
r.read(new FileInputStream(poiFs));
POIFile[] result = new POIFile[files.size()];
for (int i = 0; i < result.length; i++)
- result[i] = (POIFile) files.get(i);
+ result[i] = files.get(i);
return result;
}
public static POIFile[] readPropertySets(final File poiFs)
throws FileNotFoundException, IOException
{
- final List files = new ArrayList(7);
+ final List<POIFile> files = new ArrayList<POIFile>(7);
final POIFSReader r = new POIFSReader();
POIFSReaderListener pfl = new POIFSReaderListener()
{
for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) {
assertEquals(512, fs.getBigBlockSize());
}
+ fsA.close();
+ fsB.close();
// Now with a simple 4096 block file
fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) {
assertEquals(4096, fs.getBigBlockSize());
}
+ fsA.close();
+ fsB.close();
}
@Test
assertEquals(i+1, ministore.getNextBlock(i));
}
assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
+
+ fs.close();
}
// Now with a simple 4096 block file
assertEquals(i+1, ministore.getNextBlock(i));
}
assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
+
+ fs.close();
}
}
for(int i=100; i<fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) {
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i));
}
+
+ fs.close();
}
// Quick check on 4096 byte blocks too
assertEquals(i+1, fs.getNextBlock(i));
}
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11));
+
+ fs.close();
}
}
assertEquals((byte)0x00, b.get());
assertEquals((byte)0x00, b.get());
assertEquals((byte)0x00, b.get());
+
+ fs.close();
}
// Quick check on 4096 byte blocks too
assertEquals((byte)0x00, b.get());
assertEquals((byte)0x00, b.get());
assertEquals((byte)0x00, b.get());
+
+ fs.close();
}
}
// Look inside another
DirectoryEntry imageD = (DirectoryEntry)image;
assertEquals(7, imageD.getEntryCount());
+
+ fs.close();
}
}
ps = PropertySetFactory.create(inp);
DocumentSummaryInformation dinf = (DocumentSummaryInformation)ps;
assertEquals(131333, dinf.getOSVersion());
+
+ fs.close();
}
}
/**
* Tests for the Mini Store in the NIO POIFS
*/
-@SuppressWarnings("resource")
public final class TestNPOIFSMiniStore extends TestCase {
private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance();
for(int i=181; i<fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) {
assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i));
}
+
+ fs.close();
}
}
assertEquals((byte)0, b.get());
assertEquals((byte)0, b.get());
}
+
+ fs.close();
}
}
// Allocate it, then ask again
ministore.setNextBlock(181, POIFSConstants.END_OF_CHAIN);
assertEquals(182, ministore.getFreeBlock());
+
+ fs.close();
}
/**
assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(255)); // 2nd SBAT
assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(256)); // 3rd SBAT
assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(257)); // 3rd SBAT
+
+ fs.close();
}
/**
for(int i=193; i<256; i++) {
assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i));
}
+
+ fs.close();
}
}
assertEquals((byte)0x00, b.get());
assertEquals((byte)0x00, b.get());
assertEquals((byte)0x00, b.get());
+
+ fs.close();
}
/**
assertEquals((byte)0x00, b98.get());
assertEquals((byte)0x00, b98.get());
assertEquals((byte)0x00, b98.get());
+
+ fs.close();
}
/**
assertEquals((byte)0x01, b22.get());
assertEquals((byte)0x02, b22.get());
assertEquals((byte)0x00, b22.get());
+
+ fs.close();
}
/**
assertEquals((byte)0x00, b2.get());
assertEquals((byte)0x46, b2.get());
assertEquals((byte)0x00, b2.get());
+
+ fs.close();
}
/**
// Good, it was detected
}
assertEquals(true, i.hasNext());
+
+ fs.close();
}
/**
assertEquals((byte)0x00, b180.get());
assertEquals((byte)0x00, b180.get());
assertEquals((byte)0x80, b180.get());
+
+ fs.close();
}
/**
byte exp = (byte)(i%256);
assertEquals(exp, data[i]);
}
+
+ fs.close();
}
/**
byte exp = (byte)(i%256);
assertEquals(exp, data[i]);
}
+
+ fs.close();
}
/**
count++;
}
assertEquals(3, count);
+
+ fs.close();
}
/**
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
+
+ fs.close();
}
/**
assertEquals(130, fs.getNextBlock(129));
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130));
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131));
+
+ fs.close();
}
/**
count++;
}
assertEquals(5, count);
+
+ fs.close();
}
/**
assertEquals((byte)0x42, b183.get(1));
assertEquals((byte)0x81, b184.get(0));
assertEquals((byte)0x82, b184.get(1));
+
+ fs.close();
}
/**
stream.updateContents(data);
fail("Loop should have been detected but wasn't!");
} catch(IllegalStateException e) {}
+
+ fs.close();
}
/**
}
assertEquals(false, it.hasNext());
+
+ fs.close();
}
/**
normal = (DocumentEntry)fs.getRoot().getEntry("Normal");
assertEquals(4096, normal.getSize());
assertEquals(4096, ((DocumentNode)normal).getProperty().getSize());
+
+ fs.close();
}
}