improved test cases: moved common hssf-xssf test to org.apache.poi.ss namespace, removed duplicate tests, refactored code to throw same exceptions, etc

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@759112 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Yegor Kozlov 2009-03-27 11:50:52 +00:00
parent 72d0f15a20
commit 9adb9cc6d3
36 changed files with 1795 additions and 2148 deletions

View File

@ -285,7 +285,7 @@ public final class PageSettingsBlock extends RecordAggregate {
retval.setVResolution(( short ) 300);
retval.setHeaderMargin( 0.5);
retval.setFooterMargin( 0.5);
retval.setCopies(( short ) 0);
retval.setCopies(( short ) 1);
return retval;
}
@ -352,7 +352,7 @@ public final class PageSettingsBlock extends RecordAggregate {
case Sheet.TopMargin: return _topMargin;
case Sheet.BottomMargin: return _bottomMargin;
}
throw new RuntimeException( "Unknown margin constant: " + marginIndex );
throw new IllegalArgumentException( "Unknown margin constant: " + marginIndex );
}
@ -372,7 +372,7 @@ public final class PageSettingsBlock extends RecordAggregate {
case Sheet.TopMargin: return 1.0;
case Sheet.BottomMargin: return 1.0;
}
throw new RuntimeException( "Unknown margin constant: " + margin );
throw new IllegalArgumentException( "Unknown margin constant: " + margin );
}
/**
@ -401,7 +401,7 @@ public final class PageSettingsBlock extends RecordAggregate {
m = _bottomMargin;
break;
default :
throw new RuntimeException( "Unknown margin constant: " + margin );
throw new IllegalArgumentException( "Unknown margin constant: " + margin );
}
}
m.setMargin( size );

View File

@ -91,7 +91,7 @@ public class HSSFCell implements Cell {
/**
* The maximum number of columns in BIFF8
*/
private static final int LAST_COLUMN_NUMBER = 255; // 2^8 - 1
public static final int LAST_COLUMN_NUMBER = 255; // 2^8 - 1
private static final String LAST_COLUMN_NAME = "IV";
public final static short ENCODING_UNCHANGED = -1;
@ -626,6 +626,9 @@ public class HSSFCell implements Cell {
}
public String getCellFormula() {
if (!(_record instanceof FormulaRecordAggregate)) {
throw typeMismatch(CELL_TYPE_FORMULA, _cellType, true);
}
return HSSFFormulaParser.toFormulaString(_book, ((FormulaRecordAggregate)_record).getFormulaTokens());
}

View File

@ -124,6 +124,7 @@ public final class HSSFName implements Name {
if (rec != _definedNameRec) {
if (rec.getNameText().equalsIgnoreCase(nameName) && sheetNumber == rec.getSheetNumber()){
String msg = "The "+(sheetNumber == 0 ? "workbook" : "sheet")+" already contains this name: " + nameName;
_definedNameRec.setNameText(nameName + "(2)");
throw new IllegalArgumentException(msg);
}
}

View File

@ -437,15 +437,17 @@ public final class HSSFRow implements Row {
/**
* set the row's height or set to ff (-1) for undefined/default-height. Set the height in "twips" or
* 1/20th of a point.
* @param height rowheight or 0xff for undefined (use sheet default)
* @param height rowheight or -1 for undefined (use sheet default)
*/
public void setHeight(short height)
{
// row.setOptionFlags(
row.setBadFontHeight(true);
row.setHeight(height);
if(height == -1){
row.setHeight((short)(0xFF | 0x8000));
} else {
row.setBadFontHeight(true);
row.setHeight(height);
}
}
/**
@ -466,15 +468,17 @@ public final class HSSFRow implements Row {
/**
* set the row's height in points.
* @param height row height in points
* @param height row height in points, <code>-1</code> means to use the default height
*/
public void setHeightInPoints(float height)
{
// row.setOptionFlags(
row.setBadFontHeight(true);
row.setHeight((short) (height * 20));
if(height == -1){
row.setHeight((short)(0xFF | 0x8000));
} else {
row.setBadFontHeight(true);
row.setHeight((short) (height * 20));
}
}
/**

View File

@ -67,18 +67,6 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
private static final POILogger log = POILogFactory.getLogger(HSSFSheet.class);
private static final int DEBUG = POILogger.DEBUG;
/* Constants for margins */
public static final short LeftMargin = Sheet.LeftMargin;
public static final short RightMargin = Sheet.RightMargin;
public static final short TopMargin = Sheet.TopMargin;
public static final short BottomMargin = Sheet.BottomMargin;
public static final byte PANE_LOWER_RIGHT = (byte)0;
public static final byte PANE_UPPER_RIGHT = (byte)1;
public static final byte PANE_LOWER_LEFT = (byte)2;
public static final byte PANE_UPPER_LEFT = (byte)3;
/**
* Used for compile-time optimization. This is the initial size for the collection of
* rows. It is currently set to 20. If you generate larger sheets you may benefit
@ -236,14 +224,16 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
*/
public void removeRow(Row row) {
HSSFRow hrow = (HSSFRow) row;
if (row.getSheet() != this) {
throw new IllegalArgumentException("Specified row does not belong to this sheet");
}
if (_rows.size() > 0) {
Integer key = new Integer(row.getRowNum());
HSSFRow removedRow = _rows.remove(key);
if (removedRow != row) {
if (removedRow != null) {
_rows.put(key, removedRow);
}
throw new RuntimeException("Specified row does not belong to this sheet");
//should not happen if the input argument is valid
throw new IllegalArgumentException("Specified row does not belong to this sheet");
}
if (hrow.getRowNum() == getLastRowNum())
{
@ -488,7 +478,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public float getDefaultRowHeightInPoints()
{
return (_sheet.getDefaultRowHeight() / 20);
return ((float)_sheet.getDefaultRowHeight() / 20);
}
/**
@ -1434,9 +1424,9 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
* Sets a page break at the indicated column
* @param column
*/
public void setColumnBreak(short column) {
validateColumn(column);
_sheet.getPageSettings().setColumnBreak(column, (short)0, (short)65535);
public void setColumnBreak(int column) {
validateColumn((short)column);
_sheet.getPageSettings().setColumnBreak((short)column, (short)0, (short)65535);
}
/**
@ -1444,7 +1434,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
* @param column FIXME: Document this!
* @return FIXME: Document this!
*/
public boolean isColumnBroken(short column) {
public boolean isColumnBroken(int column) {
return _sheet.getPageSettings().isColumnBroken(column);
}
@ -1452,7 +1442,7 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
* Removes a page break at the indicated column
* @param column
*/
public void removeColumnBreak(short column) {
public void removeColumnBreak(int column) {
_sheet.getPageSettings().removeColumnBreak(column);
}
@ -1857,4 +1847,16 @@ public final class HSSFSheet implements org.apache.poi.ss.usermodel.Sheet {
public HSSFSheetConditionalFormatting getSheetConditionalFormatting() {
return new HSSFSheetConditionalFormatting(this);
}
/**
* Returns the name of this sheet
*
* @return the name of this sheet
*/
public String getSheetName() {
HSSFWorkbook wb = getWorkbook();
int idx = wb.getSheetIndex(this);
return wb.getSheetName(idx);
}
}

View File

@ -752,8 +752,8 @@ public class HSSFWorkbook extends POIDocument implements org.apache.poi.ss.userm
HSSFSheet sheet = new HSSFSheet(this);
workbook.setSheetName(_sheets.size(), sheetname);
_sheets.add(sheet);
workbook.setSheetName(_sheets.size() - 1, sheetname);
boolean isOnlySheet = _sheets.size() == 1;
sheet.setSelected(isOnlySheet);
sheet.setActive(isOnlySheet);
@ -788,6 +788,7 @@ public class HSSFWorkbook extends POIDocument implements org.apache.poi.ss.userm
public HSSFSheet getSheetAt(int index)
{
validateSheetIndex(index);
return (HSSFSheet) _sheets.get(index);
}

View File

@ -106,7 +106,7 @@ public enum FormulaError {
/**
* @return numeric code of the error
*/
public int getCode() {
public byte getCode() {
return type;
}
@ -118,7 +118,7 @@ public enum FormulaError {
}
private static Map<String, FormulaError> smap = new HashMap<String, FormulaError>();
private static Map<Integer, FormulaError> imap = new HashMap<Integer, FormulaError>();
private static Map<Byte, FormulaError> imap = new HashMap<Byte, FormulaError>();
static{
for (FormulaError error : values()) {
imap.put(error.getCode(), error);
@ -126,7 +126,7 @@ public enum FormulaError {
}
}
public static FormulaError forInt(int type){
public static FormulaError forInt(byte type){
FormulaError err = imap.get(type);
if(err == null) throw new IllegalArgumentException("Unknown error type: " + type);
return err;

View File

@ -224,6 +224,11 @@ public interface Sheet extends Iterable<Row> {
boolean getHorizontallyCenter();
/**
* Determine whether printed output for this sheet will be vertically centered.
*/
boolean getVerticallyCenter();
/**
* Removes a merged region of cells (hence letting them free)
*
@ -639,20 +644,20 @@ public interface Sheet extends Iterable<Row> {
* Sets a page break at the indicated column
* @param column
*/
void setColumnBreak(short column);
void setColumnBreak(int column);
/**
* Determines if there is a page break at the indicated column
* @param column FIXME: Document this!
* @return FIXME: Document this!
*/
boolean isColumnBroken(short column);
boolean isColumnBroken(int column);
/**
* Removes a page break at the indicated column
* @param column
*/
void removeColumnBreak(short column);
void removeColumnBreak(int column);
/**
* Expands or collapses a column group.
@ -761,4 +766,18 @@ public interface Sheet extends Iterable<Row> {
* @return the parent workbook
*/
Workbook getWorkbook();
/**
* Returns the name of this sheet
*
* @return the name of this sheet
*/
String getSheetName();
/**
* Note - this is not the same as whether the sheet is focused (isActive)
* @return <code>true</code> if this sheet is currently selected
*/
boolean isSelected();
}

View File

@ -97,7 +97,7 @@ public interface Workbook {
* @see Sheet#setSelected(boolean)
* @param index the index of the sheet to select (0 based)
*/
void setSelectedTab(short index);
void setSelectedTab(int index);
/**
* Set the sheet name.

View File

@ -60,8 +60,7 @@ public final class XSSFCell implements Cell {
/**
* The maximum number of columns in SpreadsheetML
*/
public static final int MAX_COLUMN_NUMBER = 16384; // 2^14
private static final int LAST_COLUMN_NUMBER = MAX_COLUMN_NUMBER-1;
public static final int LAST_COLUMN_NUMBER = 16384-1; //2^14-1
private static final String LAST_COLUMN_NAME = "XFD";
private static final String FALSE_AS_STRING = "0";
@ -194,7 +193,6 @@ public final class XSSFCell implements Cell {
switch(cellType) {
case CELL_TYPE_BLANK:
return 0.0;
case CELL_TYPE_ERROR:
case CELL_TYPE_FORMULA:
case CELL_TYPE_NUMERIC:
return cell.isSetV() ? Double.parseDouble(cell.getV()) : 0.0;
@ -708,7 +706,7 @@ public final class XSSFCell implements Cell {
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0");
cell.setF(f);
cell.unsetT();
if(cell.isSetT()) cell.unsetT();
}
break;
default:

View File

@ -18,6 +18,7 @@ package org.apache.poi.xssf.usermodel;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
import org.openxmlformats.schemas.drawingml.x2006.main.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.util.POILogger;
@ -43,6 +44,15 @@ import java.util.Iterator;
public class XSSFPicture extends XSSFShape implements Picture {
private static final POILogger logger = POILogFactory.getLogger(XSSFPicture.class);
/**
* Column width measured as the number of characters of the maximum digit width of the
* numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
* padding (two on each side), plus 1 pixel padding for the gridlines.
*
* This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)
*/
private static float DEFAULT_COLUMN_WIDTH = 9.140625f;
/**
* A default instance of CTShape used for creating new shapes.
*/
@ -230,9 +240,11 @@ public class XSSFPicture extends XSSFShape implements Picture {
private float getColumnWidthInPixels(int columnIndex){
XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();
float numChars = (float)sheet.getColumnWidth(columnIndex)/256;
return numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH;
CTCol col = sheet.getColumnHelper().getColumn(columnIndex, false);
double numChars = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth();
return (float)numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH;
}
private float getRowHeightInPixels(int rowIndex){

View File

@ -45,7 +45,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
/**
* The maximum number of rows in SpreadsheetML
*/
public static final int MAX_ROW_NUMBER = 1048576; //2 ^ 20
public static final int MAX_ROW_NUMBER = 1048575; //2 ^ 20 - 1
/**
* the xml bean containing all cell definitions for this row
@ -170,8 +170,6 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @see Cell#CELL_TYPE_STRING
*/
public XSSFCell createCell(int columnIndex, int type) {
if(columnIndex < 0) throw new IllegalArgumentException("columnIndex must be >= 0, was " + columnIndex);
CTCell ctcell = CTCell.Factory.newInstance();
XSSFCell xcell = new XSSFCell(this, ctcell);
xcell.setCellNum(columnIndex);
@ -333,10 +331,9 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @throws IllegalArgumentException if rowNum < 0 or greater than {@link #MAX_ROW_NUMBER}
*/
public void setRowNum(int rowIndex) {
if (rowIndex < 0 || rowIndex >= MAX_ROW_NUMBER) {
throw new IllegalArgumentException("Invalid row index (" + rowIndex
+ "). Allowable row range for " + FILE_FORMAT_NAME
+ " is (0.." + (MAX_ROW_NUMBER-1) + ")");
if (rowIndex < 0 || rowIndex > MAX_ROW_NUMBER) {
throw new IllegalArgumentException("Invalid row number (" + rowIndex
+ ") outside allowable range (0.." + MAX_ROW_NUMBER + ")");
}
row.setR(rowIndex + 1);
}

View File

@ -64,15 +64,6 @@ import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelations
public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
private static final POILogger logger = POILogFactory.getLogger(XSSFSheet.class);
/**
* Column width measured as the number of characters of the maximum digit width of the
* numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
* padding (two on each side), plus 1 pixel padding for the gridlines.
*
* This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)
*/
private static float DEFAULT_COLUMN_WIDTH = 9.140625f;
protected CTSheet sheet;
protected CTWorksheet worksheet;
private TreeMap<Integer, XSSFRow> rows;
@ -462,7 +453,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/
public int getColumnWidth(int columnIndex) {
CTCol col = columnHelper.getColumn(columnIndex, false);
double width = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth();
double width = col == null || !col.isSetWidth() ? getDefaultColumnWidth() : col.getWidth();
return (int)(width*256);
}
@ -512,8 +503,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* set for that column
*/
public CellStyle getColumnStyle(int column) {
// TODO
return null;
int idx = columnHelper.getColDefaultStyle(column);
return getWorkbook().getCellStyleAt((short)(idx == -1 ? 0 : idx));
}
@ -568,7 +559,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @return the number of the first logical row on the sheet, zero based
*/
public int getFirstRowNum() {
return rows.size() == 0 ? -1 : rows.firstKey();
return rows.size() == 0 ? 0 : rows.firstKey();
}
/**
@ -681,7 +672,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
}
public int getLastRowNum() {
return rows.size() == 0 ? -1 : rows.lastKey();
return rows.size() == 0 ? 0 : rows.lastKey();
}
public short getLeftCol() {
@ -720,7 +711,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
case FooterMargin:
return pageMargins.getFooter();
default :
throw new POIXMLException("Unknown margin constant: " + margin);
throw new IllegalArgumentException("Unknown margin constant: " + margin);
}
}
@ -742,16 +733,24 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
switch (margin) {
case LeftMargin:
pageMargins.setLeft(size);
break;
case RightMargin:
pageMargins.setRight(size);
break;
case TopMargin:
pageMargins.setTop(size);
break;
case BottomMargin:
pageMargins.setBottom(size);
break;
case HeaderMargin:
pageMargins.setHeader(size);
break;
case FooterMargin:
pageMargins.setFooter(size);
break;
default :
throw new IllegalArgumentException( "Unknown margin constant: " + margin );
}
}
@ -1033,7 +1032,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
/**
* Determines if there is a page break at the indicated column
*/
public boolean isColumnBroken(short column) {
public boolean isColumnBroken(int column) {
int[] colBreaks = getColumnBreaks();
for (int i = 0 ; i < colBreaks.length ; i++) {
if (colBreaks[i] == column) {
@ -1167,7 +1166,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
/**
* Removes a page break at the indicated column
*/
public void removeColumnBreak(short column) {
public void removeColumnBreak(int column) {
CTBreak[] brkArray = getSheetTypeColumnBreaks().getBrkArray();
for (int i = 0 ; i < brkArray.length ; i++) {
if (brkArray[i].getId() == column) {
@ -1202,6 +1201,10 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
* @param row the row to remove.
*/
public void removeRow(Row row) {
if (row.getSheet() != this) {
throw new IllegalArgumentException("Specified row does not belong to this sheet");
}
rows.remove(row.getRowNum());
}
@ -1263,7 +1266,7 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*
* @param column the column to break
*/
public void setColumnBreak(short column) {
public void setColumnBreak(int column) {
if (! isColumnBroken(column)) {
CTBreak brk = getSheetTypeColumnBreaks().addNewBrk();
brk.setId(column);

View File

@ -60,17 +60,7 @@ import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBookView;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBookViews;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STSheetState;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
/**
* High level representation of a SpreadsheetML workbook. This is the first object most users
@ -445,7 +435,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
* @return XSSFSheet representing the new sheet.
*/
public XSSFSheet createSheet() {
String sheetname = "Sheet" + (sheets.size() + 1);
String sheetname = "Sheet" + (sheets.size());
return createSheet(sheetname);
}
@ -777,6 +767,8 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
public void removeSheetAt(int index) {
validateSheetIndex(index);
XSSFSheet sheet = getSheetAt(index);
removeRelation(sheet);
this.sheets.remove(index);
this.workbook.getSheets().removeSheet(index);
}
@ -1009,7 +1001,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
/**
* We only set one sheet as selected for compatibility with HSSF.
*/
public void setSelectedTab(short index) {
public void setSelectedTab(int index) {
for (int i = 0 ; i < sheets.size() ; ++i) {
XSSFSheet sheet = sheets.get(i);
sheet.setSelected(i == index);
@ -1042,10 +1034,16 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<X
int idx = getSheetIndex(sheetname);
sheets.add(pos, sheets.remove(idx));
// Reorder CTSheets
XmlObject cts = workbook.getSheets().getSheetArray(idx).copy();
CTSheets ct = workbook.getSheets();
XmlObject cts = ct.getSheetArray(idx).copy();
workbook.getSheets().removeSheet(idx);
CTSheet newcts = workbook.getSheets().insertNewSheet(pos);
CTSheet newcts = ct.insertNewSheet(pos);
newcts.set(cts);
//notify sheets
for(int i=0; i < sheets.size(); i++) {
sheets.get(i).sheet = ct.getSheetArray(i);
}
}
/**

View File

@ -31,27 +31,8 @@ public final class TestXSSFCell extends BaseTestCell {
return XSSFITestDataProvider.getInstance();
}
public void testSetValues() {
baseTestSetValues();
}
public void testBoolErr() {
baseTestBoolErr();
}
public void testFormulaStyle() {
baseTestFormulaStyle();
}
public void testToString() {
baseTestToString();
}
public void testSetFormulaValue() {
baseTestSetFormulaValue();
}
public void testChangeCellType() {
//for performance reasons combine baseTestChangeType* together
Workbook wb = getTestDataProvider().createWorkbook();
Row row = wb.createSheet().createRow(0);
baseTestChangeTypeStringToBool(row.createCell(0));
@ -62,6 +43,4 @@ public final class TestXSSFCell extends BaseTestCell {
//TODO: works in HSSF but fails in XSSF
//baseTestChangeTypeFormulaToBoolean(row.createCell(4));
}
}

View File

@ -66,48 +66,7 @@ public class TestXSSFDialogSheet extends TestCase {
assertFalse(sheet.getFitToPage());
}
public void testGetSetMargin() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null);
assertEquals((double) 0, sheet.getMargin((short) 0));
sheet.setMargin((short) 0, 10);
assertEquals((double) 10, sheet.getMargin((short) 0));
assertEquals((double) 10, sheet.getMargin((short) 1));
assertEquals((double) 10, sheet.getMargin((short) 2));
assertEquals((double) 10, sheet.getMargin((short) 3));
assertEquals((double) 10, sheet.getMargin((short) 4));
assertEquals((double) 10, sheet.getMargin((short) 5));
sheet.setMargin((short) 1, 11);
assertEquals((double) 11, sheet.getMargin((short) 1));
assertEquals((double) 11, sheet.getMargin((short) 2));
assertEquals((double) 11, sheet.getMargin((short) 3));
assertEquals((double) 11, sheet.getMargin((short) 4));
assertEquals((double) 11, sheet.getMargin((short) 5));
sheet.setMargin((short) 2, 12);
assertEquals((double) 12, sheet.getMargin((short) 2));
assertEquals((double) 12, sheet.getMargin((short) 3));
assertEquals((double) 12, sheet.getMargin((short) 4));
assertEquals((double) 12, sheet.getMargin((short) 5));
sheet.setMargin((short) 3, 13);
assertEquals((double) 13, sheet.getMargin((short) 3));
assertEquals((double) 13, sheet.getMargin((short) 4));
assertEquals((double) 13, sheet.getMargin((short) 5));
sheet.setMargin((short) 4, 14);
assertEquals((double) 14, sheet.getMargin((short) 4));
assertEquals((double) 14, sheet.getMargin((short) 5));
sheet.setMargin((short) 5, 15);
assertEquals((double) 15, sheet.getMargin((short) 5));
// Test that nothing happens if another margin constant is given (E.G. 65)
sheet.setMargin((short) 65, 15);
assertEquals((double) 10, sheet.getMargin((short) 0));
assertEquals((double) 11, sheet.getMargin((short) 1));
assertEquals((double) 12, sheet.getMargin((short) 2));
assertEquals((double) 13, sheet.getMargin((short) 3));
assertEquals((double) 14, sheet.getMargin((short) 4));
assertEquals((double) 15, sheet.getMargin((short) 5));
}
public void testGetFooter() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null);

View File

@ -18,144 +18,17 @@ package org.apache.poi.xssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.ss.usermodel.BaseTestNamedRange;
/**
* @author Yegor Kozlov
*/
public class TestXSSFName extends TestCase {
public class TestXSSFName extends BaseTestNamedRange {
public void testCreate(){
// Create a new workbook
XSSFWorkbook wb = new XSSFWorkbook();
XSSFName name1 = wb.createName();
name1.setNameName("testOne");
//setting a duplicate name should throw IllegalArgumentException
XSSFName name2 = wb.createName();
try {
name2.setNameName("testOne");
fail("expected exception");
} catch (IllegalArgumentException e){
assertEquals("The workbook already contains this name: testOne", e.getMessage());
}
name2.setNameName("testTwo");
String ref1 = "Test1!$A$1:$B$1";
name1.setRefersToFormula(ref1);
assertEquals(ref1, name1.getRefersToFormula());
assertEquals("Test1", name1.getSheetName());
String ref2 = "'Testing Named Ranges'!$A$1:$B$1";
name1.setRefersToFormula(ref2);
assertEquals("'Testing Named Ranges'!$A$1:$B$1", name1.getRefersToFormula());
assertEquals("Testing Named Ranges", name1.getSheetName());
assertEquals(-1, name1.getSheetIndex());
name1.setSheetIndex(-1);
assertEquals(-1, name1.getSheetIndex());
try {
name1.setSheetIndex(1);
fail("should throw IllegalArgumentException");
} catch(IllegalArgumentException e){
assertEquals("Sheet index (1) is out of range", e.getMessage());
}
wb.createSheet();
try {
name1.setSheetIndex(1);
fail("should throw IllegalArgumentException");
} catch(IllegalArgumentException e){
assertEquals("Sheet index (1) is out of range (0..0)", e.getMessage());
}
wb.createSheet();
name1.setSheetIndex(1);
assertEquals(1, name1.getSheetIndex());
}
public void testUnicodeNamedRange() {
XSSFWorkbook workBook = new XSSFWorkbook();
workBook.createSheet("Test");
XSSFName name = workBook.createName();
name.setNameName("\u03B1");
name.setRefersToFormula("Test!$D$3:$E$8");
XSSFWorkbook workBook2 = XSSFTestDataSamples.writeOutAndReadBack(workBook);
XSSFName name2 = workBook2.getNameAt(0);
assertEquals("\u03B1", name2.getNameName());
assertEquals("Test!$D$3:$E$8", name2.getRefersToFormula());
}
public void testAddRemove() {
XSSFWorkbook wb = new XSSFWorkbook();
assertEquals(0, wb.getNumberOfNames());
XSSFName name1 = wb.createName();
name1.setNameName("name1");
assertEquals(1, wb.getNumberOfNames());
XSSFName name2 = wb.createName();
name2.setNameName("name2");
assertEquals(2, wb.getNumberOfNames());
XSSFName name3 = wb.createName();
name3.setNameName("name3");
assertEquals(3, wb.getNumberOfNames());
wb.removeName("name2");
assertEquals(2, wb.getNumberOfNames());
wb.removeName(0);
assertEquals(1, wb.getNumberOfNames());
}
public void testScope() {
XSSFWorkbook wb = new XSSFWorkbook();
wb.createSheet();
wb.createSheet();
XSSFName name;
name = wb.createName();
name.setNameName("aaa");
name = wb.createName();
try {
name.setNameName("aaa");
fail("Expected exception");
} catch(Exception e){
assertEquals("The workbook already contains this name: aaa", e.getMessage());
}
name = wb.createName();
name.setSheetIndex(0);
name.setNameName("aaa");
name = wb.createName();
name.setSheetIndex(0);
try {
name.setNameName("aaa");
fail("Expected exception");
} catch(Exception e){
assertEquals("The sheet already contains this name: aaa", e.getMessage());
}
name = wb.createName();
name.setSheetIndex(1);
name.setNameName("aaa");
name = wb.createName();
name.setSheetIndex(1);
try {
name.setNameName("aaa");
fail("Expected exception");
} catch(Exception e){
assertEquals("The sheet already contains this name: aaa", e.getMessage());
}
int cnt = 0;
for (int i = 0; i < wb.getNumberOfNames(); i++) {
if("aaa".equals(wb.getNameAt(i).getNameName())) cnt++;
}
assertEquals(3, cnt);
@Override
protected XSSFITestDataProvider getTestDataProvider(){
return XSSFITestDataProvider.getInstance();
}
}

View File

@ -23,12 +23,10 @@ import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -37,303 +35,18 @@ import org.apache.poi.hssf.usermodel.HSSFCell;
/**
* Tests for XSSFRow
*/
public final class TestXSSFRow extends TestCase {
public final class TestXSSFRow extends BaseTestRow {
/**
* Test adding cells to a row in various places and see if we can find them again.
*/
public void testAddAndIterateCells() {
XSSFSheet sheet = createParentObjects();
XSSFRow row = sheet.createRow(0);
// One cell at the beginning
Cell cell1 = row.createCell((short) 1);
Iterator<Cell> it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell1 == it.next());
assertFalse(it.hasNext());
// Add another cell at the end
Cell cell2 = row.createCell((short) 99);
it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell1 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
// Add another cell at the beginning
Cell cell3 = row.createCell((short) 0);
it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell3 == it.next());
assertTrue(it.hasNext());
assertTrue(cell1 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
// Replace cell1
Cell cell4 = row.createCell((short) 1);
it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell3 == it.next());
assertTrue(it.hasNext());
assertTrue(cell4 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
assertFalse(it.hasNext());
// Add another cell, specifying the cellType
Cell cell5 = row.createCell((short) 2, Cell.CELL_TYPE_STRING);
it = row.cellIterator();
assertNotNull(cell5);
assertTrue(it.hasNext());
assertTrue(cell3 == it.next());
assertTrue(it.hasNext());
assertTrue(cell4 == it.next());
assertTrue(it.hasNext());
assertTrue(cell5 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
assertEquals(Cell.CELL_TYPE_STRING, cell5.getCellType());
@Override
protected XSSFITestDataProvider getTestDataProvider(){
return XSSFITestDataProvider.getInstance();
}
public void testGetCell() {
XSSFRow row = getSampleRow();
assertNotNull(row.getCell((short) 2));
assertNotNull(row.getCell((short) 3));
assertNotNull(row.getCell((short) 4));
// cell3 may have been created as CELL_TYPE_NUMERIC, but since there is no numeric
// value set yet, its cell type is classified as 'blank'
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell((short) 3).getCellType());
assertNull(row.getCell((short) 5));
public void testRowBounds() {
baseTestRowBounds(XSSFRow.MAX_ROW_NUMBER);
}
public void testGetPhysicalNumberOfCells() {
XSSFRow row = getSampleRow();
assertEquals(7, row.getPhysicalNumberOfCells());
}
public void testGetFirstCellNum() {
// Test a row with some cells
XSSFRow row = getSampleRow();
assertFalse(row.getFirstCellNum() == (short) 0);
assertEquals((short) 2, row.getFirstCellNum());
// Test after removing the first cell
Cell cell = row.getCell((short) 2);
row.removeCell(cell);
assertFalse(row.getFirstCellNum() == (short) 2);
// Test a row without cells
XSSFSheet sheet = createParentObjects();
XSSFRow emptyRow = sheet.createRow(0);
assertEquals(-1, emptyRow.getFirstCellNum());
}
public void testGetSetHeight() {
XSSFRow row = getSampleRow();
// I assume that "ht" attribute value is in 'points', please verify that
// Test that no rowHeight is set
assertEquals(row.getSheet().getDefaultRowHeight(), row.getHeight());
// Set a rowHeight and test the new value
row.setHeight((short) 240);
assertEquals((short) 240.0, row.getHeight());
assertEquals(12.0f, row.getHeightInPoints());
// Set a new rowHeight in points and test the new value
row.setHeightInPoints(13);
assertEquals((float) 13.0, row.getHeightInPoints());
assertEquals((short)(13.0*20), row.getHeight());
}
public void testGetSetZeroHeight() throws Exception {
XSSFRow row = getSampleRow();
assertFalse(row.getZeroHeight());
row.setZeroHeight(true);
assertTrue(row.getZeroHeight());
}
/**
* Tests for the missing/blank cell policy stuff
*/
public void testGetCellPolicy() throws Exception {
XSSFSheet sheet = createParentObjects();
XSSFRow row = sheet.createRow(0);
// 0 -> string
// 1 -> num
// 2 missing
// 3 missing
// 4 -> blank
// 5 -> num
row.createCell((short)0).setCellValue(new XSSFRichTextString("test"));
row.createCell((short)1).setCellValue(3.2);
row.createCell((short)4, Cell.CELL_TYPE_BLANK);
row.createCell((short)5).setCellValue(4);
// First up, no policy
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1).getCellType());
assertEquals(null, row.getCell(2));
assertEquals(null, row.getCell(3));
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(4).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType());
// RETURN_NULL_AND_BLANK - same as default
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0, Row.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1, Row.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(null, row.getCell(2, Row.RETURN_NULL_AND_BLANK));
assertEquals(null, row.getCell(3, Row.RETURN_NULL_AND_BLANK));
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(4, Row.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, Row.RETURN_NULL_AND_BLANK).getCellType());
// RETURN_BLANK_AS_NULL - nearly the same
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0, XSSFRow.RETURN_BLANK_AS_NULL).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1, XSSFRow.RETURN_BLANK_AS_NULL).getCellType());
assertEquals(null, row.getCell(2, XSSFRow.RETURN_BLANK_AS_NULL));
assertEquals(null, row.getCell(3, XSSFRow.RETURN_BLANK_AS_NULL));
assertEquals(null, row.getCell(4, XSSFRow.RETURN_BLANK_AS_NULL));
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, XSSFRow.RETURN_BLANK_AS_NULL).getCellType());
// CREATE_NULL_AS_BLANK - creates as needed
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(2, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(3, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(4, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());
// Check created ones get the right column
assertEquals((short)0, row.getCell(0, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)1, row.getCell(1, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)2, row.getCell(2, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)3, row.getCell(3, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)4, row.getCell(4, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)5, row.getCell(5, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
}
/**
* Method that returns a row with some sample cells
* @return row
*/
private static XSSFRow getSampleRow() {
XSSFSheet sheet = createParentObjects();
XSSFRow row = sheet.createRow(0);
row.createCell((short) 2);
row.createCell((short) 3, Cell.CELL_TYPE_NUMERIC);
row.createCell((short) 4);
row.createCell((short) 6);
row.createCell((short) 7);
row.createCell((short) 8);
row.createCell((short) 100);
return row;
}
private static XSSFSheet createParentObjects() {
XSSFWorkbook wb = new XSSFWorkbook();
return wb.createSheet();
}
/**
* Test that XSSFRow.getLastCellNum is consistent with HSSFRow.getLastCellNum
*/
public void testLastCellNum() {
HSSFWorkbook wb1 = new HSSFWorkbook();
XSSFWorkbook wb2 = new XSSFWorkbook();
HSSFSheet sheet1 = wb1.createSheet();
XSSFSheet sheet2 = wb2.createSheet();
for (int i = 0; i < 10; i++) {
HSSFRow row1 = sheet1.createRow(i);
XSSFRow row2 = sheet2.createRow(i);
for (int j = 0; j < 5; j++) {
//before adding a cell
assertEquals(row1.getLastCellNum(), row2.getLastCellNum());
HSSFCell cell1 = row1.createCell(j);
XSSFCell cell2 = row2.createCell(j);
//after adding a cell
assertEquals(row1.getLastCellNum(), row2.getLastCellNum());
}
}
}
public void testRemoveCell() {
XSSFRow row = getSampleRow();
// Test removing the first cell
Cell firstCell = row.getCell((short) 2);
assertNotNull(firstCell);
assertEquals(7, row.getPhysicalNumberOfCells());
row.removeCell(firstCell);
assertEquals(6, row.getPhysicalNumberOfCells());
firstCell = row.getCell((short) 2);
assertNull(firstCell);
// Test removing the last cell
Cell lastCell = row.getCell((short) 100);
row.removeCell(lastCell);
}
public void testFirstLastCellNum() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
row.createCell(1);
assertEquals(2, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
row.createCell(3);
assertEquals(4, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
row.removeCell(row.getCell(3));
assertEquals(2, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
row.removeCell(row.getCell(1));
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
assertEquals(-1, sheet.getRow(0).getLastCellNum());
assertEquals(-1, sheet.getRow(0).getFirstCellNum());
}
public void testRowHeightCompatibility(){
Workbook wb1 = new HSSFWorkbook();
Workbook wb2 = new XSSFWorkbook();
Sheet sh1 = wb1.createSheet();
Sheet sh2 = wb2.createSheet();
sh2.setDefaultRowHeight(sh1.getDefaultRowHeight());
assertEquals(sh1.getDefaultRowHeight(), sh2.getDefaultRowHeight());
//junit.framework.AssertionFailedError: expected:<12.0> but was:<12.75>
//YK: there is a bug in HSSF version, it trunkates decimal part
//assertEquals(sh1.getDefaultRowHeightInPoints(), sh2.getDefaultRowHeightInPoints());
Row row1 = sh1.createRow(0);
Row row2 = sh2.createRow(0);
assertEquals(row1.getHeight(), row2.getHeight());
assertEquals(row1.getHeightInPoints(), row2.getHeightInPoints());
row1.setHeight((short)100);
row2.setHeight((short)100);
assertEquals(row1.getHeight(), row2.getHeight());
assertEquals(row1.getHeightInPoints(), row2.getHeightInPoints());
row1.setHeightInPoints(25.5f);
row2.setHeightInPoints(25.5f);
assertEquals(row1.getHeight(), row2.getHeight());
assertEquals(row1.getHeightInPoints(), row2.getHeightInPoints());
public void testCellBounds() {
baseTestCellBounds(XSSFCell.LAST_COLUMN_NUMBER);
}
}

View File

@ -20,124 +20,36 @@ package org.apache.poi.xssf.usermodel;
import java.io.File;
import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.model.CommentsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.model.CalculationChain;
import org.apache.poi.xssf.usermodel.helpers.ColumnHelper;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
public class TestXSSFSheet extends TestCase {
public class TestXSSFSheet extends BaseTestSheet {
public void testRowIterator() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
Row row1 = sheet.createRow(0);
Row row2 = sheet.createRow(1);
Iterator<Row> it = sheet.rowIterator();
assertNotNull(it);
assertTrue(it.hasNext());
assertEquals(row1, it.next());
assertTrue(it.hasNext());
assertEquals(row2, it.next());
assertFalse(it.hasNext());
@Override
protected XSSFITestDataProvider getTestDataProvider(){
return XSSFITestDataProvider.getInstance();
}
public void testGetRow() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
Row row1 = sheet.createRow(0);
Cell cell = row1.createCell((short) 0);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue((double) 1000);
// Test getting a row and check its cell's value
Row row_got = sheet.getRow(0);
Cell cell_got = row_got.getCell((short) 0);
assertEquals((double) 1000, cell_got.getNumericCellValue());
//TODO column styles are not yet supported by XSSF
public void testDefaultColumnStyle() {
//super.testDefaultColumnStyle();
}
public void testCreateRow() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
// Test row creation with consecutive indexes
Row row1 = sheet.createRow(0);
Row row2 = sheet.createRow(1);
assertEquals(0, row1.getRowNum());
assertEquals(1, row2.getRowNum());
Iterator<Row> it = sheet.rowIterator();
assertTrue(it.hasNext());
assertEquals(row1, it.next());
assertTrue(it.hasNext());
assertEquals(row2, it.next());
// Test row creation with non consecutive index
Row row101 = sheet.createRow(100);
assertNotNull(row101);
// Test overwriting an existing row
Row row2_ovrewritten = sheet.createRow(1);
Cell cell = row2_ovrewritten.createCell((short) 0);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue((double) 100);
Iterator<Row> it2 = sheet.rowIterator();
assertTrue(it2.hasNext());
assertEquals(row1, it2.next());
assertTrue(it2.hasNext());
Row row2_overwritten_copy = it2.next();
assertEquals(row2_ovrewritten, row2_overwritten_copy);
assertEquals(row2_overwritten_copy.getCell((short) 0).getNumericCellValue(), (double) 100);
}
public void testRemoveRow() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
Row row1 = sheet.createRow(1);
Row row2 = sheet.createRow(2);
assertNotNull(sheet.getRow(1));
sheet.removeRow(row2);
assertNull(sheet.getRow(0));
assertNull(sheet.getRow(2));
assertNotNull(sheet.getRow(1));
}
public void testGetSetDefaultRowHeight() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
// Test that default height set by the constructor
assertEquals((short) 300, sheet.getDefaultRowHeight());
assertEquals((float) 15, sheet.getDefaultRowHeightInPoints());
// Set a new default row height in twips and test getting the value in points
sheet.setDefaultRowHeight((short) 360);
assertEquals((float) 18, sheet.getDefaultRowHeightInPoints());
// Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18
sheet.setDefaultRowHeight((short) 361);
assertEquals((float)361/20, sheet.getDefaultRowHeightInPoints());
// Set a new default row height in points and test getting the value in twips
sheet.setDefaultRowHeightInPoints((short) 17);
assertEquals((short) 340, sheet.getDefaultRowHeight());
}
public void testGetSetDefaultColumnWidth() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
// Test that default column width set by the constructor
assertEquals((short) 8, sheet.getDefaultColumnWidth());
// Set a new default column width and get its value
sheet.setDefaultColumnWidth((short) 14);
assertEquals((short) 14, sheet.getDefaultColumnWidth());
public void testTestGetSetMargin() {
baseTestGetSetMargin(new double[]{0.7, 0.7, 0.75, 0.75, 0.3, 0.3});
}
public void testGetFirstLastRowNum() {
XSSFWorkbook workbook = new XSSFWorkbook();
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
Row row10 = sheet.createRow(9);
Row row1 = sheet.createRow(0);
@ -146,149 +58,8 @@ public class TestXSSFSheet extends TestCase {
assertEquals(9, sheet.getLastRowNum());
}
public void testGetPhysicalNumberOfRows() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
Row row10 = sheet.createRow(9);
Row row1 = sheet.createRow(0);
Row row2 = sheet.createRow(1);
assertEquals(3, sheet.getPhysicalNumberOfRows());
}
public void testGetSetRowBreaks() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertEquals(0, sheet.getRowBreaks().length);
sheet.setRowBreak(1);
sheet.setRowBreak(15);
assertNotNull(sheet.getRowBreaks());
assertEquals(1, sheet.getRowBreaks()[0]);
assertEquals(15, sheet.getRowBreaks()[1]);
sheet.setRowBreak(1);
assertEquals(2, sheet.getRowBreaks().length);
}
public void testRemoveRowBreak() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
sheet.setRowBreak(1);
assertEquals(1, sheet.getRowBreaks().length);
sheet.setRowBreak(2);
assertEquals(2, sheet.getRowBreaks().length);
sheet.removeRowBreak(1);
assertEquals(1, sheet.getRowBreaks().length);
}
public void testMaxColumnWidth() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnWidth(0, 255*256); //the limit
try {
sheet.setColumnWidth(0, 256*256); //the limit
fail("expected exception");
} catch (Exception e){
;
}
}
public void testGetSetColumnBreaks() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertEquals(0, sheet.getColumnBreaks().length);
sheet.setColumnBreak((short) 11);
assertNotNull(sheet.getColumnBreaks());
assertEquals(11, sheet.getColumnBreaks()[0]);
sheet.setColumnBreak((short) 11223);
assertEquals(2, sheet.getColumnBreaks().length);
}
public void testRemoveColumnBreak() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertEquals(0, sheet.getColumnBreaks().length);
sheet.setColumnBreak((short) 11);
assertNotNull(sheet.getColumnBreaks());
sheet.setColumnBreak((short) 12);
assertEquals(2, sheet.getColumnBreaks().length);
sheet.removeColumnBreak((short) 11);
assertEquals(1, sheet.getColumnBreaks().length);
sheet.removeColumnBreak((short) 15);
assertEquals(1, sheet.getColumnBreaks().length);
}
public void testIsRowColumnBroken() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.isRowBroken(0));
sheet.setRowBreak(3);
assertTrue(sheet.isRowBroken(3));
assertFalse(sheet.isColumnBroken((short) 0));
sheet.setColumnBreak((short) 3);
assertTrue(sheet.isColumnBroken((short) 3));
}
public void testGetSetAutoBreaks() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.getAutobreaks());
sheet.setAutobreaks(false);
assertFalse(sheet.getAutobreaks());
}
public void testIsSetFitToPage() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getFitToPage());
sheet.setFitToPage(true);
assertTrue(sheet.getFitToPage());
sheet.setFitToPage(false);
assertFalse(sheet.getFitToPage());
}
public void testGetSetMargin() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertEquals(0.7, sheet.getMargin((short) 0));
sheet.setMargin((short) 0, 10);
assertEquals((double) 10, sheet.getMargin((short) 0));
assertEquals((double) 10, sheet.getMargin((short) 1));
assertEquals((double) 10, sheet.getMargin((short) 2));
assertEquals((double) 10, sheet.getMargin((short) 3));
assertEquals((double) 10, sheet.getMargin((short) 4));
assertEquals((double) 10, sheet.getMargin((short) 5));
sheet.setMargin((short) 1, 11);
assertEquals((double) 11, sheet.getMargin((short) 1));
assertEquals((double) 11, sheet.getMargin((short) 2));
assertEquals((double) 11, sheet.getMargin((short) 3));
assertEquals((double) 11, sheet.getMargin((short) 4));
assertEquals((double) 11, sheet.getMargin((short) 5));
sheet.setMargin((short) 2, 12);
assertEquals((double) 12, sheet.getMargin((short) 2));
assertEquals((double) 12, sheet.getMargin((short) 3));
assertEquals((double) 12, sheet.getMargin((short) 4));
assertEquals((double) 12, sheet.getMargin((short) 5));
sheet.setMargin((short) 3, 13);
assertEquals((double) 13, sheet.getMargin((short) 3));
assertEquals((double) 13, sheet.getMargin((short) 4));
assertEquals((double) 13, sheet.getMargin((short) 5));
sheet.setMargin((short) 4, 14);
assertEquals((double) 14, sheet.getMargin((short) 4));
assertEquals((double) 14, sheet.getMargin((short) 5));
sheet.setMargin((short) 5, 15);
assertEquals((double) 15, sheet.getMargin((short) 5));
// Test that nothing happens if another margin constant is given (E.G. 65)
sheet.setMargin((short) 65, 15);
assertEquals((double) 10, sheet.getMargin((short) 0));
assertEquals((double) 11, sheet.getMargin((short) 1));
assertEquals((double) 12, sheet.getMargin((short) 2));
assertEquals((double) 13, sheet.getMargin((short) 3));
assertEquals((double) 14, sheet.getMargin((short) 4));
assertEquals((double) 15, sheet.getMargin((short) 5));
}
public void testGetFooter() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFWorkbook workbook = getTestDataProvider().createWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertNotNull(sheet.getFooter());
sheet.getFooter().setCenter("test center footer");
@ -364,7 +135,7 @@ public class TestXSSFSheet extends TestCase {
}
public void testGetAllHeadersFooters() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFWorkbook workbook = getTestDataProvider().createWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertNotNull(sheet.getOddFooter());
assertNotNull(sheet.getEvenFooter());
@ -402,50 +173,8 @@ public class TestXSSFSheet extends TestCase {
assertEquals("odd header center", sheet.getHeader().getCenter());
}
public void testGetSetColumnWidth() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnWidth(1, 22*256);
assertEquals(22*256, sheet.getColumnWidth(1));
// Now check the low level stuff, and check that's all
// been set correctly
XSSFSheet xs = sheet;
CTWorksheet cts = xs.getCTWorksheet();
CTCols[] cols_s = cts.getColsArray();
assertEquals(1, cols_s.length);
CTCols cols = cols_s[0];
assertEquals(1, cols.sizeOfColArray());
CTCol col = cols.getColArray(0);
// XML is 1 based, POI is 0 based
assertEquals(2, col.getMin());
assertEquals(2, col.getMax());
assertEquals(22.0, col.getWidth());
// Now set another
sheet.setColumnWidth(3, 33*256);
cols_s = cts.getColsArray();
assertEquals(1, cols_s.length);
cols = cols_s[0];
assertEquals(2, cols.sizeOfColArray());
col = cols.getColArray(0);
assertEquals(2, col.getMin()); // POI 1
assertEquals(2, col.getMax());
assertEquals(22.0, col.getWidth());
col = cols.getColArray(1);
assertEquals(4, col.getMin()); // POI 3
assertEquals(4, col.getMax());
assertEquals(33.0, col.getWidth());
}
public void testGetSetColumnHidden() {
XSSFWorkbook workbook = new XSSFWorkbook();
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnHidden((short) 2, true);
assertTrue(sheet.isColumnHidden((short) 2));
@ -463,185 +192,6 @@ public class TestXSSFSheet extends TestCase {
assertTrue(col.getBestFit());
}
public void testGetSetHorizontallyCentered() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getHorizontallyCenter());
sheet.setHorizontallyCenter(true);
assertTrue(sheet.getHorizontallyCenter());
sheet.setHorizontallyCenter(false);
assertFalse(sheet.getHorizontallyCenter());
}
public void testGetSetVerticallyCentered() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getVerticallyCenter());
sheet.setVerticallyCenter(true);
assertTrue(sheet.getVerticallyCenter());
sheet.setVerticallyCenter(false);
assertFalse(sheet.getVerticallyCenter());
}
public void testIsSetPrintGridlines() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.isPrintGridlines());
sheet.setPrintGridlines(true);
assertTrue(sheet.isPrintGridlines());
}
public void testIsSetDisplayFormulas() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.isDisplayFormulas());
sheet.setDisplayFormulas(true);
assertTrue(sheet.isDisplayFormulas());
}
public void testIsSetDisplayGridLines() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.isDisplayGridlines());
sheet.setDisplayGridlines(false);
assertFalse(sheet.isDisplayGridlines());
}
public void testIsSetDisplayGuts() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.getDisplayGuts());
sheet.setDisplayGuts(false);
assertFalse(sheet.getDisplayGuts());
}
public void testIsSetDisplayRowColHeadings() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.isDisplayRowColHeadings());
sheet.setDisplayRowColHeadings(false);
assertFalse(sheet.isDisplayRowColHeadings());
}
public void testGetScenarioProtect() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getScenarioProtect());
}
/*
public void testTopRowLeftCol() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
sheet.showInPane((short)1, (short)1);
assertEquals((short) 1, sheet.getTopRow());
assertEquals((short) 1, sheet.getLeftCol());
sheet.showInPane((short)2, (short)26);
assertEquals((short) 2, sheet.getTopRow());
assertEquals((short) 26, sheet.getLeftCol());
}
*/
public void testShiftRows() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = createSheet(workbook, "Sheet 1");
sheet.shiftRows(1, 2, 4, true, false);
assertEquals((short) 1, sheet.getRow(5).getHeight());
assertEquals((short) 2, sheet.getRow(6).getHeight());
assertNull(sheet.getRow(1));
assertNull(sheet.getRow(2));
assertEquals(8, sheet.getPhysicalNumberOfRows());
XSSFSheet sheet2 = createSheet(workbook, "Sheet 2");
sheet2.shiftRows(1, 5, 3, true, false);
assertEquals((short) 1, sheet2.getRow(4).getHeight());
assertEquals((short) 2, sheet2.getRow(5).getHeight());
assertEquals((short) 3, sheet2.getRow(6).getHeight());
assertEquals((short) 4, sheet2.getRow(7).getHeight());
assertEquals((short) 5, sheet2.getRow(8).getHeight());
assertNull(sheet2.getRow(1));
assertNull(sheet2.getRow(2));
assertNull(sheet2.getRow(3));
assertEquals(7, sheet2.getPhysicalNumberOfRows());
XSSFSheet sheet3 = createSheet(workbook, "Sheet 3");
sheet3.shiftRows(5, 7, -3, true, false);
assertEquals(5, sheet3.getRow(2).getHeight());
assertEquals(6, sheet3.getRow(3).getHeight());
assertEquals(7, sheet3.getRow(4).getHeight());
assertNull(sheet3.getRow(5));
assertNull(sheet3.getRow(6));
assertNull(sheet3.getRow(7));
assertEquals(7, sheet3.getPhysicalNumberOfRows());
XSSFSheet sheet4 = createSheet(workbook, "Sheet 4");
sheet4.shiftRows(5, 7, -2, true, false);
assertEquals(5, sheet4.getRow(3).getHeight());
assertEquals(6, sheet4.getRow(4).getHeight());
assertEquals(7, sheet4.getRow(5).getHeight());
assertNull(sheet4.getRow(6));
assertNull(sheet4.getRow(7));
assertEquals(8, sheet4.getPhysicalNumberOfRows());
// Test without copying rowHeight
XSSFSheet sheet5 = createSheet(workbook, "Sheet 5");
sheet5.shiftRows(5, 7, -2, false, false);
assertEquals(sheet5.getDefaultRowHeight(), sheet5.getRow(3).getHeight());
assertEquals(sheet5.getDefaultRowHeight(), sheet5.getRow(4).getHeight());
assertEquals(sheet5.getDefaultRowHeight(), sheet5.getRow(5).getHeight());
assertNull(sheet5.getRow(6));
assertNull(sheet5.getRow(7));
assertEquals(8, sheet5.getPhysicalNumberOfRows());
// Test without copying rowHeight and resetting to default height
XSSFSheet sheet6 = createSheet(workbook, "Sheet 6");
sheet6.setDefaultRowHeight((short) 200);
sheet6.shiftRows(5, 7, -2, false, true);
assertEquals(200, sheet6.getRow(3).getHeight());
assertEquals(200, sheet6.getRow(4).getHeight());
assertEquals(200, sheet6.getRow(5).getHeight());
assertNull(sheet6.getRow(6));
assertNull(sheet6.getRow(7));
assertEquals(8, sheet6.getPhysicalNumberOfRows());
}
/**
* When shifting rows, update formulas on that sheet to point to the new location of those rows
* (see bugzilla 46536)
*/
public void testShiftRows_46536() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("46536.xlsx");
CalculationChain calcChain = wb.getCalculationChain();
int numItems = calcChain.getCTCalcChain().getCArray().length;
assertEquals(3, numItems);
XSSFSheet sheet = wb.getSheet("Test");
XSSFRow row2 = sheet.getRow(1);
XSSFCell cell_A2 = row2.getCell(0);
assertEquals("A2", cell_A2.getReference());
XSSFRow row3 = sheet.getRow(2);
XSSFCell cell_B3 = row3.getCell(1);
assertEquals("B3", cell_B3.getReference());
XSSFCell cell_E2 = row2.getCell(4);
CTCellFormula f = cell_E2.getCTCell().getF();
assertEquals("B2+C2+D2", f.getStringValue());
assertEquals("E2:E3", f.getRef());
sheet.shiftRows(1, sheet.getLastRowNum(), 3, false, true);
assertEquals(4, row2.getRowNum());
assertEquals(5, row3.getRowNum());
assertEquals("A5", cell_A2.getReference());
assertEquals("B6", cell_B3.getReference());
assertEquals("B5+C5+D5", f.getStringValue());
assertEquals("E5:E6", f.getRef());
numItems = calcChain.getCTCalcChain().getCArray().length;
assertEquals(1, numItems);
}
public void testGetCellComment() {
XSSFWorkbook workbook = new XSSFWorkbook();
@ -758,31 +308,7 @@ public class TestXSSFSheet extends TestCase {
}
private XSSFSheet createSheet(XSSFWorkbook workbook, String name) {
XSSFSheet sheet = workbook.createSheet(name);
Row row0 = sheet.createRow(0);
row0.setHeight((short) 1);
Row row1 = sheet.createRow(1);
row1.setHeight((short) 1);
Row row2 = sheet.createRow(2);
row2.setHeight((short) 2);
Row row3 = sheet.createRow(3);
row3.setHeight((short) 3);
Row row4 = sheet.createRow(4);
row4.setHeight((short) 4);
Row row5 = sheet.createRow(5);
row5.setHeight((short) 5);
Row row6 = sheet.createRow(6);
row6.setHeight((short) 6);
Row row7 = sheet.createRow(7);
row7.setHeight((short) 7);
Row row8 = sheet.createRow(8);
row8.setHeight((short) 8);
Row row9 = sheet.createRow(9);
row9.setHeight((short) 9);
return sheet;
}
public void testGroupUngroupColumn() {
@ -881,77 +407,49 @@ public class TestXSSFSheet extends TestCase {
}
}
public void testOutlineProperties() {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
assertTrue(sheet.getRowSumsBelow());
assertTrue(sheet.getRowSumsRight());
sheet.setRowSumsBelow(false);
sheet.setRowSumsRight(false);
assertFalse(sheet.getRowSumsBelow());
assertFalse(sheet.getRowSumsRight());
}
public void testSetColumnGroupCollapsed(){
}
public void testColumnWidthCompatibility() {
Workbook wb1 = new HSSFWorkbook();
Workbook wb2 = new XSSFWorkbook();
Sheet sh1 = wb1.createSheet();
Sheet sh2 = wb2.createSheet();
assertEquals(sh1.getDefaultColumnWidth(), sh2.getDefaultColumnWidth());
//if column width is not set, HSSF returns a wrong value which does not take into account
//margins and borders, it is always less than the actual column width
assertEquals(2048, sh1.getColumnWidth(0));
assertEquals(2340, sh2.getColumnWidth(0));
sh1.setDefaultColumnWidth(1000);
sh2.setDefaultColumnWidth(1000);
assertEquals(1000, sh2.getDefaultColumnWidth());
assertEquals(sh1.getDefaultColumnWidth(), sh2.getDefaultColumnWidth());
sh1.setColumnWidth(0, 500);
sh2.setColumnWidth(0, 500);
assertEquals(500, sh2.getColumnWidth(0));
assertEquals(sh1.getColumnWidth(0), sh2.getColumnWidth(0));
}
/**
* Tests the display of gridlines, formulas, and rowcolheadings.
* @author Shawn Laubach (slaubach at apache dot org)
* Get / Set column width and check the actual values of the underlying XML beans
*/
public void testDisplayOptions() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
public void testColumnWidth_lowlevel() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnWidth(1, 22*256);
assertEquals(22*256, sheet.getColumnWidth(1));
assertEquals(sheet.isDisplayGridlines(), true);
assertEquals(sheet.isDisplayRowColHeadings(), true);
assertEquals(sheet.isDisplayFormulas(), false);
assertEquals(sheet.isDisplayZeros(), true);
// Now check the low level stuff, and check that's all
// been set correctly
XSSFSheet xs = sheet;
CTWorksheet cts = xs.getCTWorksheet();
sheet.setDisplayGridlines(false);
sheet.setDisplayRowColHeadings(false);
sheet.setDisplayFormulas(true);
sheet.setDisplayZeros(false);
CTCols[] cols_s = cts.getColsArray();
assertEquals(1, cols_s.length);
CTCols cols = cols_s[0];
assertEquals(1, cols.sizeOfColArray());
CTCol col = cols.getColArray(0);
wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
// XML is 1 based, POI is 0 based
assertEquals(2, col.getMin());
assertEquals(2, col.getMax());
assertEquals(22.0, col.getWidth());
assertEquals(sheet.isDisplayGridlines(), false);
assertEquals(sheet.isDisplayRowColHeadings(), false);
assertEquals(sheet.isDisplayFormulas(), true);
assertEquals(sheet.isDisplayZeros(), false);
// Now set another
sheet.setColumnWidth(3, 33*256);
cols_s = cts.getColsArray();
assertEquals(1, cols_s.length);
cols = cols_s[0];
assertEquals(2, cols.sizeOfColArray());
col = cols.getColArray(0);
assertEquals(2, col.getMin()); // POI 1
assertEquals(2, col.getMax());
assertEquals(22.0, col.getWidth());
col = cols.getColArray(1);
assertEquals(4, col.getMin()); // POI 3
assertEquals(4, col.getMax());
assertEquals(33.0, col.getWidth());
}
}

View File

@ -27,6 +27,7 @@ import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.OPCPackage;
@ -35,139 +36,14 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
public final class TestXSSFWorkbook extends TestCase {
@Override
protected void setUp() {
// Use system out logger
System.setProperty(
"org.apache.poi.util.POILogger",
"org.apache.poi.util.SystemOutLogger"
);
}
public void testGetSetActiveSheet(){
XSSFWorkbook workbook = new XSSFWorkbook();
assertEquals(0, workbook.getActiveSheetIndex());
workbook.createSheet("sheet1");
workbook.createSheet("sheet2");
workbook.createSheet("sheet3");
// set second sheet
workbook.setActiveSheet(1);
// test if second sheet is set up
assertEquals(1, workbook.getActiveSheetIndex());
}
public void testGetSheetIndex() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("sheet1");
Sheet sheet2 = workbook.createSheet("sheet2");
assertEquals(0, workbook.getSheetIndex(sheet1));
assertEquals(0, workbook.getSheetIndex("sheet1"));
assertEquals(1, workbook.getSheetIndex(sheet2));
assertEquals(1, workbook.getSheetIndex("sheet2"));
assertEquals(-1, workbook.getSheetIndex("noSheet"));
}
public void testSetSheetOrder() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("sheet1");
Sheet sheet2 = workbook.createSheet("sheet2");
assertSame(sheet1, workbook.getSheetAt(0));
assertSame(sheet2, workbook.getSheetAt(1));
workbook.setSheetOrder("sheet2", 0);
assertSame(sheet2, workbook.getSheetAt(0));
assertSame(sheet1, workbook.getSheetAt(1));
// Test reordering of CTSheets
CTWorkbook ctwb = workbook.getCTWorkbook();
CTSheet[] ctsheets = ctwb.getSheets().getSheetArray();
assertEquals("sheet2", ctsheets[0].getName());
assertEquals("sheet1", ctsheets[1].getName());
// Borderline case: only one sheet
workbook = new XSSFWorkbook();
sheet1 = workbook.createSheet("sheet1");
assertSame(sheet1, workbook.getSheetAt(0));
workbook.setSheetOrder("sheet1", 0);
assertSame(sheet1, workbook.getSheetAt(0));
}
public void testSetSheetName() {
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.createSheet("sheet1");
assertEquals("sheet1", workbook.getSheetName(0));
workbook.setSheetName(0, "sheet2");
assertEquals("sheet2", workbook.getSheetName(0));
}
public void testCloneSheet() {
XSSFWorkbook book = new XSSFWorkbook();
XSSFSheet sheet = book.createSheet("TEST");
sheet.createRow(0).createCell(0).setCellValue("Test");
sheet.createRow(1).createCell(0).setCellValue(36.6);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2));
sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 2));
assertTrue(sheet.isSelected());
XSSFSheet clonedSheet = book.cloneSheet(0);
assertEquals("TEST (2)", clonedSheet.getSheetName());
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
assertEquals(2, clonedSheet.getNumMergedRegions());
assertFalse(clonedSheet.isSelected());
//cloned sheet is a deep copy, adding rows in the original does not affect the clone
sheet.createRow(2).createCell(0).setCellValue(1);
sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2));
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
clonedSheet.createRow(2).createCell(0).setCellValue(1);
clonedSheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2));
assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
public final class TestXSSFWorkbook extends BaseTestWorkbook {
@Override
protected XSSFITestDataProvider getTestDataProvider(){
return XSSFITestDataProvider.getInstance();
}
public void testGetSheetByName() {
XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("sheet1");
Sheet sheet2 = workbook.createSheet("sheet2");
assertSame(sheet1, workbook.getSheet("sheet1"));
assertSame(sheet2, workbook.getSheet("sheet2"));
assertNull(workbook.getSheet("nosheet"));
}
public void testRemoveSheetAt() {
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.createSheet("sheet1");
workbook.createSheet("sheet2");
workbook.createSheet("sheet3");
workbook.removeSheetAt(1);
assertEquals(2, workbook.getNumberOfSheets());
assertEquals("sheet3", workbook.getSheetName(1));
workbook.removeSheetAt(0);
assertEquals(1, workbook.getNumberOfSheets());
assertEquals("sheet3", workbook.getSheetName(0));
workbook.removeSheetAt(0);
assertEquals(0, workbook.getNumberOfSheets());
}
public void testPrintArea(){
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0);
// String reference = sheetName+"!$A$1:$B$1";
// workbook.setPrintArea(0, reference);
workbook.setPrintArea(0,1,5,4,9);
String retrievedPrintArea = workbook.getPrintArea(0);
//assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'"+sheetName+"'!$B$5:$F$10", retrievedPrintArea);
}
public void testRepeatingRowsAndColums() {
// First test that setting RR&C for same sheet more than once only creates a
// single Print_Titles built-in record
@ -205,24 +81,9 @@ public final class TestXSSFWorkbook extends TestCase {
assertEquals(XSSFName.BUILTIN_PRINT_TITLE, nr2.getNameName());
assertEquals("'SecondSheet'!$B:$C,'SecondSheet'!$1:$1", nr2.getRefersToFormula());
nwb.setRepeatingRowsAndColumns(1, -1, -1, -1, -1);
}
/**
* Tests that we can save a new document
*/
public void testSaveNew() {
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.createSheet("sheet1");
workbook.createSheet("sheet2");
workbook.createSheet("sheet3");
XSSFTestDataSamples.writeOutAndReadBack(workbook);
}
/**
* Tests that we can save, and then re-load a new document
*/
@ -242,8 +103,8 @@ public final class TestXSSFWorkbook extends TestCase {
assertEquals(1, workbook.getSheetAt(0).getLastRowNum());
assertEquals(0, workbook.getSheetAt(1).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(1).getLastRowNum());
assertEquals(-1, workbook.getSheetAt(2).getFirstRowNum());
assertEquals(-1, workbook.getSheetAt(2).getLastRowNum());
assertEquals(0, workbook.getSheetAt(2).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(2).getLastRowNum());
File file = File.createTempFile("poi-", ".xlsx");
OutputStream out = new FileOutputStream(file);
@ -278,8 +139,8 @@ public final class TestXSSFWorkbook extends TestCase {
assertEquals(1, workbook.getSheetAt(0).getLastRowNum());
assertEquals(0, workbook.getSheetAt(1).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(1).getLastRowNum());
assertEquals(-1, workbook.getSheetAt(2).getFirstRowNum());
assertEquals(-1, workbook.getSheetAt(2).getLastRowNum());
assertEquals(0, workbook.getSheetAt(2).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(2).getLastRowNum());
sheet1 = workbook.getSheetAt(0);
assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001);
@ -379,13 +240,6 @@ public final class TestXSSFWorkbook extends TestCase {
assertNotSame(2, i);
}
public void testGetDisplayedTab(){
XSSFWorkbook workbook = new XSSFWorkbook();
short i = (short) workbook.getFirstVisibleTab();
//get default diplayedTab
assertEquals(0, i);
}
public void testSetDisplayedTab(){
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setFirstVisibleTab(1);
@ -395,8 +249,8 @@ public final class TestXSSFWorkbook extends TestCase {
//1 is the default tab
assertEquals(1, i);
}
public void testLoadSave() {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
assertEquals(3, workbook.getNumberOfSheets());
@ -458,94 +312,4 @@ public final class TestXSSFWorkbook extends TestCase {
assertEquals(1, st.getBorders().size());
}
public void testNamedRanges() {
// First up, a new file
XSSFWorkbook workbook = new XSSFWorkbook();
assertEquals(0, workbook.getNumberOfNames());
Name nameA = workbook.createName();
nameA.setRefersToFormula("A2");
nameA.setNameName("ForA2");
XSSFName nameB = workbook.createName();
nameB.setRefersToFormula("B3");
nameB.setNameName("ForB3");
nameB.setComment("B3 Comment");
// Save and re-load
workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertEquals(2, workbook.getNumberOfNames());
assertEquals("A2", workbook.getNameAt(0).getRefersToFormula());
assertEquals("ForA2", workbook.getNameAt(0).getNameName());
assertNull(workbook.getNameAt(0).getComment());
assertEquals("B3", workbook.getNameAt(1).getRefersToFormula());
assertEquals("ForB3", workbook.getNameAt(1).getNameName());
assertEquals("B3 Comment", workbook.getNameAt(1).getComment());
assertEquals("ForA2", workbook.getNameAt(0).getNameName());
assertEquals(1, workbook.getNameIndex("ForB3"));
assertEquals(-1, workbook.getNameIndex("ForB3!!"));
// Now, an existing file with named ranges
workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx");
assertEquals(2, workbook.getNumberOfNames());
assertEquals("Sheet1!$A$2:$A$7", workbook.getNameAt(0).getRefersToFormula());
assertEquals("AllANumbers", workbook.getNameAt(0).getNameName());
assertEquals("All the numbers in A", workbook.getNameAt(0).getComment());
assertEquals("Sheet1!$B$2:$B$7", workbook.getNameAt(1).getRefersToFormula());
assertEquals("AllBStrings", workbook.getNameAt(1).getNameName());
assertEquals("All the strings in B", workbook.getNameAt(1).getComment());
// Tweak, save, and re-check
workbook.getNameAt(1).setNameName("BStringsFun");
workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertEquals(2, workbook.getNumberOfNames());
assertEquals("Sheet1!$A$2:$A$7", workbook.getNameAt(0).getRefersToFormula());
assertEquals("AllANumbers", workbook.getNameAt(0).getNameName());
assertEquals("All the numbers in A", workbook.getNameAt(0).getComment());
assertEquals("Sheet1!$B$2:$B$7", workbook.getNameAt(1).getRefersToFormula());
assertEquals("BStringsFun", workbook.getNameAt(1).getNameName());
assertEquals("All the strings in B", workbook.getNameAt(1).getComment());
}
public void testDuplicateNames() {
XSSFWorkbook wb = new XSSFWorkbook();
wb.createSheet("Sheet1");
wb.createSheet();
wb.createSheet("name1");
try {
wb.createSheet("name1");
fail();
} catch (IllegalArgumentException e) {
assertEquals("The workbook already contains a sheet of this name", e.getMessage());
}
wb.createSheet();
try {
wb.setSheetName(3, "name1");
fail();
} catch (IllegalArgumentException e) {
assertEquals("The workbook already contains a sheet of this name", e.getMessage());
}
try {
wb.setSheetName(3, "Sheet1");
fail();
} catch (IllegalArgumentException e) {
assertEquals("The workbook already contains a sheet of this name", e.getMessage());
}
wb.setSheetName(3, "name2");
wb.setSheetName(3, "Sheet3");
}
}

View File

@ -57,8 +57,6 @@ public class AllUserModelTests {
result.addTestSuite(TestHSSFRichTextString.class);
result.addTestSuite(TestHSSFRow.class);
result.addTestSuite(TestHSSFSheet.class);
result.addTestSuite(TestHSSFSheetOrder.class);
result.addTestSuite(TestHSSFSheetSetOrder.class);
result.addTestSuite(TestHSSFTextbox.class);
result.addTestSuite(TestHSSFWorkbook.class);
result.addTestSuite(TestLinkTable.class);

View File

@ -624,27 +624,6 @@ public final class TestBugs extends TestCase {
}
}
/**
* Bug 40296: HSSFCell.setCellFormula throws
* ClassCastException if cell is created using HSSFRow.createCell(short column, int type)
*/
public void test40296() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet workSheet = workBook.createSheet("Sheet1");
HSSFCell cell;
HSSFRow row = workSheet.createRow(0);
cell = row.createCell(0, HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(1.0);
cell = row.createCell(1, HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(2.0);
cell = row.createCell(2, HSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula("SUM(A1:B1)");
writeOutAndReadBack(wb);
}
/**
* Test bug 38266: NPE when adding a row break
*

View File

@ -44,21 +44,6 @@ public final class TestHSSFCell extends BaseTestCell {
return HSSFITestDataProvider.getInstance();
}
public void testSetValues() {
baseTestSetValues();
}
/**
* test that Boolean and Error types (BoolErrRecord) are supported properly.
*/
public void testBoolErr() {
baseTestBoolErr();
}
public void testSetFormulaValue() {
baseTestSetFormulaValue();
}
/**
* Checks that the recognition of files using 1904 date windowing
* is working properly. Conversion of the date is also an issue,
@ -168,13 +153,6 @@ public final class TestHSSFCell extends BaseTestCell {
3, s.getActiveCellRow());
}
/**
* test that Cell Styles being applied to formulas remain intact
*/
public void testFormulaStyle() {
baseTestFormulaStyle();
}
/**
* Test reading hyperlinks
*/
@ -219,13 +197,8 @@ public final class TestHSSFCell extends BaseTestCell {
assertEquals(1, link2.getFirstColumn());
}
/**tests the toString() method of HSSFCell*/
public void testToString() {
baseTestToString();
}
public void testSetStringInFormulaCell_bug44606() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFWorkbook wb = getTestDataProvider().createWorkbook();
HSSFCell cell = wb.createSheet("Sheet1").createRow(0).createCell(0);
cell.setCellFormula("B1&C1");
try {

View File

@ -35,7 +35,7 @@ public class TestHSSFClientAnchor extends TestCase
HSSFSheet sheet = wb.createSheet("test");
HSSFClientAnchor a = new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short)0,0);
float p = a.getAnchorHeightInPoints(sheet);
assertEquals(11.953,p,0.001);
assertEquals(12.7,p,0.001);
sheet.createRow(0).setHeightInPoints(14);
a = new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short)0,0);
@ -57,7 +57,7 @@ public class TestHSSFClientAnchor extends TestCase
sheet.createRow(0).setHeightInPoints(12);
a = new HSSFClientAnchor(0,127,1023,127,(short)0,0,(short)0,1);
p = a.getAnchorHeightInPoints(sheet);
assertEquals(12.0,p,0.001);
assertEquals(12.372,p,0.001);
}
@ -96,7 +96,7 @@ public class TestHSSFClientAnchor extends TestCase
new HSSFClientAnchor( 0 , 128 , 0 , 128 ,(short)0, 1,(short)1, 3),
new HSSFClientAnchor( 0 , 0 , 0 , 128 ,(short)0, 1,(short)1, 3),
};
float[] ref = {24.0f, 18.0f, 24.0f, 30.0f};
float[] ref = {25.5f, 19.125f, 25.5f, 31.875f};
for (int i = 0; i < anchor.length; i++) {
float height = anchor[i].getAnchorHeightInPoints(sheet);
assertEquals(ref[i], height, 0);

View File

@ -1,4 +1,3 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@ -15,52 +14,35 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import java.util.Date;
import java.util.GregorianCalendar;
import junit.framework.AssertionFailedError;
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.record.DBCellRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.ss.usermodel.ErrorConstants;
import org.apache.poi.ss.usermodel.BaseTestCell;
import org.apache.poi.ss.usermodel.BaseTestNamedRange;
/**
* Tests HSSFWorkbook method setSheetOrder()
*
*
* @author Ruel Loehr (loehr1 at us.ibm.com)
*/
public class TestHSSFSheetSetOrder
extends TestCase
{
public TestHSSFSheetSetOrder(String s)
{
super(s);
}
/**
* Test the sheet set order method
*/
public void testBackupRecord()
throws Exception
{
HSSFWorkbook wb = new HSSFWorkbook();
for (int i=0; i < 10; i++)
{
HSSFSheet s = wb.createSheet("Sheet " +i);
Sheet sheet = s.getSheet();
}
wb.getWorkbook().setSheetOrder("Sheet 6", 0);
wb.getWorkbook().setSheetOrder("Sheet 3", 7);
wb.getWorkbook().setSheetOrder("Sheet 1", 9);
}
}
* Tests various functionality having to do with {@link org.apache.poi.hssf.usermodel.HSSFCell}. For instance support for
* particular datatypes, etc.
* @author Andrew C. Oliver (andy at superlinksoftware dot com)
* @author Dan Sherman (dsherman at isisph.com)
* @author Alex Jacoby (ajacoby at gmail.com)
*/
public final class TestHSSFName extends BaseTestNamedRange {
@Override
protected HSSFITestDataProvider getTestDataProvider(){
return HSSFITestDataProvider.getInstance();
}
}

View File

@ -21,36 +21,31 @@ import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.ss.usermodel.BaseTestRow;
/**
* Test HSSFRow is okay.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public final class TestHSSFRow extends TestCase {
public final class TestHSSFRow extends BaseTestRow {
public void testLastAndFirstColumns() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
assertEquals(-1, row.getFirstCellNum());
assertEquals(-1, row.getLastCellNum());
row.createCell(2);
assertEquals(2, row.getFirstCellNum());
assertEquals(3, row.getLastCellNum());
row.createCell(1);
assertEquals(1, row.getFirstCellNum());
assertEquals(3, row.getLastCellNum());
// check the exact case reported in 'bug' 43901 - notice that the cellNum is '0' based
row.createCell(3);
assertEquals(1, row.getFirstCellNum());
assertEquals(4, row.getLastCellNum());
@Override
protected HSSFITestDataProvider getTestDataProvider(){
return HSSFITestDataProvider.getInstance();
}
public void testRowBounds() {
baseTestRowBounds(RowRecord.MAX_ROW_NUMBER);
}
public void testCellBounds() {
baseTestCellBounds(HSSFCell.LAST_COLUMN_NUMBER);
}
public void testLastAndFirstColumns_bug46654() {
int ROW_IX = 10;
int COL_IX = 3;
@ -78,67 +73,6 @@ public final class TestHSSFRow extends TestCase {
assertEquals(-1, row.getLastCellNum());
}
/**
* Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum
* This test was added in response to bug report 44987.
*/
public void testBoundsInMultipleRows() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow rowA = sheet.createRow(0);
rowA.createCell(10);
rowA.createCell(5);
assertEquals(5, rowA.getFirstCellNum());
assertEquals(11, rowA.getLastCellNum());
HSSFRow rowB = sheet.createRow(1);
rowB.createCell(15);
rowB.createCell(30);
assertEquals(15, rowB.getFirstCellNum());
assertEquals(31, rowB.getLastCellNum());
assertEquals(5, rowA.getFirstCellNum());
assertEquals(11, rowA.getLastCellNum());
rowA.createCell(50);
assertEquals(51, rowA.getLastCellNum());
assertEquals(31, rowB.getLastCellNum());
}
public void testRemoveCell() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
row.createCell(1);
assertEquals(2, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
row.createCell(3);
assertEquals(4, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
row.removeCell(row.getCell(3));
assertEquals(2, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
row.removeCell(row.getCell(1));
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
// all cells on this row have been removed
// so check the row record actually writes it out as 0's
byte[] data = new byte[100];
row.getRowRecord().serialize(0, data);
assertEquals(0, data[6]);
assertEquals(0, data[8]);
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
assertEquals(-1, sheet.getRow(0).getLastCellNum());
assertEquals(-1, sheet.getRow(0).getFirstCellNum());
}
public void testMoveCell() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
@ -184,149 +118,4 @@ public final class TestHSSFRow extends TestCase {
assertEquals(2, row.getFirstCellNum());
assertEquals(6, row.getLastCellNum());
}
public void testRowBounds() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
//Test low row bound
sheet.createRow(0);
//Test low row bound exception
try {
sheet.createRow(-1);
fail("IndexOutOfBoundsException should have been thrown");
} catch (IllegalArgumentException e) {
// expected during successful test
assertEquals("Invalid row number (-1) outside allowable range (0..65535)", e.getMessage());
}
//Test high row bound
sheet.createRow(65535);
//Test high row bound exception
try {
sheet.createRow(65536);
fail("IndexOutOfBoundsException should have been thrown");
} catch (IllegalArgumentException e) {
// expected during successful test
assertEquals("Invalid row number (65536) outside allowable range (0..65535)", e.getMessage());
}
}
/**
* Prior to patch 43901, POI was producing files with the wrong last-column
* number on the row
*/
public void testLastCellNumIsCorrectAfterAddCell_bug43901(){
HSSFWorkbook book = new HSSFWorkbook();
HSSFSheet sheet = book.createSheet("test");
HSSFRow row = sheet.createRow(0);
// New row has last col -1
assertEquals(-1, row.getLastCellNum());
if(row.getLastCellNum() == 0) {
fail("Identified bug 43901");
}
// Create two cells, will return one higher
// than that for the last number
row.createCell(0);
assertEquals(1, row.getLastCellNum());
row.createCell(255);
assertEquals(256, row.getLastCellNum());
}
/**
* Tests for the missing/blank cell policy stuff
*/
public void testGetCellPolicy() {
HSSFWorkbook book = new HSSFWorkbook();
HSSFSheet sheet = book.createSheet("test");
HSSFRow row = sheet.createRow(0);
// 0 -> string
// 1 -> num
// 2 missing
// 3 missing
// 4 -> blank
// 5 -> num
row.createCell(0).setCellValue(new HSSFRichTextString("test"));
row.createCell(1).setCellValue(3.2);
row.createCell(4, HSSFCell.CELL_TYPE_BLANK);
row.createCell(5).setCellValue(4);
// First up, no policy given, uses default
assertEquals(HSSFCell.CELL_TYPE_STRING, row.getCell(0).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(1).getCellType());
assertEquals(null, row.getCell(2));
assertEquals(null, row.getCell(3));
assertEquals(HSSFCell.CELL_TYPE_BLANK, row.getCell(4).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType());
// RETURN_NULL_AND_BLANK - same as default
assertEquals(HSSFCell.CELL_TYPE_STRING, row.getCell(0, HSSFRow.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(1, HSSFRow.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(null, row.getCell(2, HSSFRow.RETURN_NULL_AND_BLANK));
assertEquals(null, row.getCell(3, HSSFRow.RETURN_NULL_AND_BLANK));
assertEquals(HSSFCell.CELL_TYPE_BLANK, row.getCell(4, HSSFRow.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(5, HSSFRow.RETURN_NULL_AND_BLANK).getCellType());
// RETURN_BLANK_AS_NULL - nearly the same
assertEquals(HSSFCell.CELL_TYPE_STRING, row.getCell(0, HSSFRow.RETURN_BLANK_AS_NULL).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(1, HSSFRow.RETURN_BLANK_AS_NULL).getCellType());
assertEquals(null, row.getCell(2, HSSFRow.RETURN_BLANK_AS_NULL));
assertEquals(null, row.getCell(3, HSSFRow.RETURN_BLANK_AS_NULL));
assertEquals(null, row.getCell(4, HSSFRow.RETURN_BLANK_AS_NULL));
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(5, HSSFRow.RETURN_BLANK_AS_NULL).getCellType());
// CREATE_NULL_AS_BLANK - creates as needed
assertEquals(HSSFCell.CELL_TYPE_STRING, row.getCell(0, HSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(1, HSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_BLANK, row.getCell(2, HSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_BLANK, row.getCell(3, HSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_BLANK, row.getCell(4, HSSFRow.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(5, HSSFRow.CREATE_NULL_AS_BLANK).getCellType());
// Check created ones get the right column
assertEquals(0, row.getCell(0, HSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(1, row.getCell(1, HSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(2, row.getCell(2, HSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(3, row.getCell(3, HSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(4, row.getCell(4, HSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(5, row.getCell(5, HSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
// Now change the cell policy on the workbook, check
// that that is now used if no policy given
book.setMissingCellPolicy(HSSFRow.RETURN_BLANK_AS_NULL);
assertEquals(HSSFCell.CELL_TYPE_STRING, row.getCell(0).getCellType());
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(1).getCellType());
assertEquals(null, row.getCell(2));
assertEquals(null, row.getCell(3));
assertEquals(null, row.getCell(4));
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType());
}
public void testRowHeight() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row1 = sheet.createRow(0);
assertEquals(0xFF, row1.getHeight());
assertEquals(sheet.getDefaultRowHeight(), row1.getHeight());
HSSFRow row2 = sheet.createRow(1);
row2.setHeight((short)400);
assertEquals(400, row2.getHeight());
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
row1 = sheet.getRow(0);
assertEquals(0xFF, row1.getHeight());
assertEquals(sheet.getDefaultRowHeight(), row1.getHeight());
row2 = sheet.getRow(1);
assertEquals(400, row2.getHeight());
}
}

View File

@ -27,11 +27,13 @@ import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.model.DrawingManager2;
import org.apache.poi.hssf.record.*;
import org.apache.poi.ss.util.Region;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.BaseTestSheet;
import org.apache.poi.ddf.EscherDgRecord;
/**
@ -41,10 +43,15 @@ import org.apache.poi.ddf.EscherDgRecord;
* @author Glen Stampoultzis (glens at apache.org)
* @author Andrew C. Oliver (acoliver apache org)
*/
public final class TestHSSFSheet extends TestCase {
public final class TestHSSFSheet extends BaseTestSheet {
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
@Override
protected HSSFITestDataProvider getTestDataProvider(){
return HSSFITestDataProvider.getInstance();
}
public void testTestGetSetMargin() {
baseTestGetSetMargin(new double[]{0.75, 0.75, 1.0, 1.0, 0.3, 0.3});
}
/**
@ -140,138 +147,11 @@ public final class TestHSSFSheet extends TestCase {
assertEquals(true, s.getRowSumsRight());
}
public void testReadBooleans() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test boolean");
HSSFRow row = sheet.createRow(2);
HSSFCell cell = row.createCell(9);
cell.setCellValue(true);
cell = row.createCell(11);
cell.setCellValue(true);
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
row = sheet.getRow(2);
assertNotNull(row);
assertEquals(2, row.getPhysicalNumberOfCells());
}
public void testRemoveRow() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test boolean");
HSSFRow row = sheet.createRow(2);
sheet.removeRow(row);
}
public void testRemoveZeroRow() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
try {
sheet.removeRow(row);
} catch (IllegalArgumentException e) {
if (e.getMessage().equals("Invalid row number (-1) outside allowable range (0..65535)")) {
throw new AssertionFailedError("Identified bug 45367");
}
throw e;
}
}
public void testCloneSheet() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Clone");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
HSSFCell cell2 = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("clone_test"));
cell2.setCellFormula("sin(1)");
HSSFSheet clonedSheet = workbook.cloneSheet(0);
HSSFRow clonedRow = clonedSheet.getRow(0);
//Check for a good clone
assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
//Check that the cells are not somehow linked
cell.setCellValue(new HSSFRichTextString("Difference Check"));
cell2.setCellFormula("cos(2)");
if ("Difference Check".equals(clonedRow.getCell(0).getRichStringCellValue().getString())) {
fail("string cell not properly cloned");
}
if ("COS(2)".equals(clonedRow.getCell(1).getCellFormula())) {
fail("formula cell not properly cloned");
}
assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)");
}
/** tests that the sheet name for multiple clones of the same sheet is unique
* BUG 37416
*/
public void testCloneSheetMultipleTimes() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Clone");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString("clone_test"));
//Clone the sheet multiple times
workbook.cloneSheet(0);
workbook.cloneSheet(0);
assertNotNull(workbook.getSheet("Test Clone"));
assertNotNull(workbook.getSheet("Test Clone (2)"));
assertEquals("Test Clone (3)", workbook.getSheetName(2));
assertNotNull(workbook.getSheet("Test Clone (3)"));
workbook.removeSheetAt(0);
workbook.removeSheetAt(0);
workbook.removeSheetAt(0);
workbook.createSheet("abc ( 123)");
workbook.cloneSheet(0);
assertEquals("abc (124)", workbook.getSheetName(1));
}
/**
* Setting landscape and portrait stuff on new sheets
*/
public void testPrintSetupLandscapeNew() throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheetL = workbook.createSheet("LandscapeS");
HSSFSheet sheetP = workbook.createSheet("LandscapeP");
// Check two aspects of the print setup
assertFalse(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(0, sheetL.getPrintSetup().getCopies());
assertEquals(0, sheetP.getPrintSetup().getCopies());
// Change one on each
sheetL.getPrintSetup().setLandscape(true);
sheetP.getPrintSetup().setCopies((short)3);
// Check taken
assertTrue(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(0, sheetL.getPrintSetup().getCopies());
assertEquals(3, sheetP.getPrintSetup().getCopies());
// Save and re-load, and check still there
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
assertTrue(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(0, sheetL.getPrintSetup().getCopies());
assertEquals(3, sheetP.getPrintSetup().getCopies());
}
/**
* Setting landscape and portrait stuff on existing sheets
*/
public void testPrintSetupLandscapeExisting() {
HSSFWorkbook workbook = openSample("SimpleWithPageBreaks.xls");
HSSFWorkbook workbook = getTestDataProvider().openSampleWorkbook("SimpleWithPageBreaks.xls");
assertEquals(3, workbook.getNumberOfSheets());
@ -352,7 +232,7 @@ public final class TestHSSFSheet extends TestCase {
}
public void testGroupRowsExisting() {
HSSFWorkbook workbook = openSample("NoGutsRecords.xls");
HSSFWorkbook workbook = getTestDataProvider().openSampleWorkbook("NoGutsRecords.xls");
HSSFSheet s = workbook.getSheetAt(0);
HSSFRow r1 = s.getRow(0);
@ -403,8 +283,8 @@ public final class TestHSSFSheet extends TestCase {
}
public void testGetDrawings() {
HSSFWorkbook wb1c = openSample("WithChart.xls");
HSSFWorkbook wb2c = openSample("WithTwoCharts.xls");
HSSFWorkbook wb1c = getTestDataProvider().openSampleWorkbook("WithChart.xls");
HSSFWorkbook wb2c = getTestDataProvider().openSampleWorkbook("WithTwoCharts.xls");
// 1 chart sheet -> data on 1st, chart on 2nd
assertNotNull(wb1c.getSheetAt(0).getDrawingPatriarch());
@ -476,94 +356,12 @@ public final class TestHSSFSheet extends TestCase {
* When removing one merged region, it would break
*
*/
public void testRemoveMerged() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
sheet.addMergedRegion(region);
region = new CellRangeAddress(1, 2, 0, 1);
sheet.addMergedRegion(region);
sheet.removeMergedRegion(0);
region = sheet.getMergedRegion(0);
assertEquals("Left over region should be starting at row 1", 1, region.getFirstRow());
sheet.removeMergedRegion(0);
assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions());
//an, add, remove, get(0) would null pointer
sheet.addMergedRegion(region);
assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
sheet.removeMergedRegion(0);
assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions());
//add it again!
region.setLastRow(4);
sheet.addMergedRegion(region);
assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
//should exist now!
assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions());
region = sheet.getMergedRegion(0);
assertEquals("the merged row to doesnt match the one we put in ", 4, region.getLastRow());
}
public void testShiftMerged() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString("first row, first cell"));
row = sheet.createRow(1);
cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("second row, second cell"));
CellRangeAddress region = new CellRangeAddress(1, 1, 0, 1);
sheet.addMergedRegion(region);
sheet.shiftRows(1, 1, 1);
region = sheet.getMergedRegion(0);
assertEquals("Merged region not moved over to row 2", 2, region.getFirstRow());
}
/**
* Tests the display of gridlines, formulas, and rowcolheadings.
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testDisplayOptions() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
assertEquals(sheet.isDisplayGridlines(), true);
assertEquals(sheet.isDisplayRowColHeadings(), true);
assertEquals(sheet.isDisplayFormulas(), false);
assertEquals(sheet.isDisplayZeros(), true);
sheet.setDisplayGridlines(false);
sheet.setDisplayRowColHeadings(false);
sheet.setDisplayFormulas(true);
sheet.setDisplayZeros(false);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
assertEquals(sheet.isDisplayGridlines(), false);
assertEquals(sheet.isDisplayRowColHeadings(), false);
assertEquals(sheet.isDisplayFormulas(), true);
assertEquals(sheet.isDisplayZeros(), false);
}
/**
* Make sure the excel file loads work
*
*/
public void testPageBreakFiles() {
HSSFWorkbook wb = openSample("SimpleWithPageBreaks.xls");
HSSFWorkbook wb = getTestDataProvider().openSampleWorkbook("SimpleWithPageBreaks.xls");
HSSFSheet sheet = wb.getSheetAt(0);
assertNotNull(sheet);
@ -591,7 +389,7 @@ public final class TestHSSFSheet extends TestCase {
}
public void testDBCSName () {
HSSFWorkbook wb = openSample("DBCSSheetName.xls");
HSSFWorkbook wb = getTestDataProvider().openSampleWorkbook("DBCSSheetName.xls");
wb.getSheetAt(1);
assertEquals ("DBCS Sheet Name 2", wb.getSheetName(1),"\u090f\u0915" );
assertEquals("DBCS Sheet Name 1", wb.getSheetName(0),"\u091c\u093e");
@ -603,7 +401,7 @@ public final class TestHSSFSheet extends TestCase {
* of the sheet when it is first opened.
*/
public void testTopRow() {
HSSFWorkbook wb = openSample("SimpleWithPageBreaks.xls");
HSSFWorkbook wb = getTestDataProvider().openSampleWorkbook("SimpleWithPageBreaks.xls");
HSSFSheet sheet = wb.getSheetAt(0);
assertNotNull(sheet);
@ -630,18 +428,6 @@ public final class TestHSSFSheet extends TestCase {
assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2");
}
/** test that new default column styles get applied */
public void testDefaultColumnStyle() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCellStyle style = wb.createCellStyle();
HSSFSheet s = wb.createSheet();
s.setDefaultColumnStyle((short) 0, style);
HSSFRow r = s.createRow(0);
HSSFCell c = r.createCell(0);
assertEquals("style should match", style.getIndex(), c.getCellStyle().getIndex());
}
/**
*
*/
@ -656,7 +442,7 @@ public final class TestHSSFSheet extends TestCase {
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
//try adding empty rows in an existing worksheet
workbook = openSample("Simple.xls");
workbook = getTestDataProvider().openSampleWorkbook("Simple.xls");
sheet = workbook.getSheetAt(0);
for (int i = 3; i < 10; i++) sheet.createRow(i);
@ -665,7 +451,7 @@ public final class TestHSSFSheet extends TestCase {
}
public void testAutoSizeColumn() {
HSSFWorkbook wb = openSample("43902.xls");
HSSFWorkbook wb = getTestDataProvider().openSampleWorkbook("43902.xls");
String sheetName = "my sheet";
HSSFSheet sheet = wb.getSheet(sheetName);
@ -709,7 +495,7 @@ public final class TestHSSFSheet extends TestCase {
* Setting ForceFormulaRecalculation on sheets
*/
public void testForceRecalculation() throws Exception {
HSSFWorkbook workbook = openSample("UncalcedRecord.xls");
HSSFWorkbook workbook = getTestDataProvider().openSampleWorkbook("UncalcedRecord.xls");
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFSheet sheet2 = workbook.getSheetAt(0);
@ -778,7 +564,7 @@ public final class TestHSSFSheet extends TestCase {
public void testColumnWidth() {
//check we can correctly read column widths from a reference workbook
HSSFWorkbook wb = openSample("colwidth.xls");
HSSFWorkbook wb = getTestDataProvider().openSampleWorkbook("colwidth.xls");
//reference values
int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657};
@ -950,4 +736,5 @@ public final class TestHSSFSheet extends TestCase {
assertFalse(cs.getFont(wbComplex).getItalic());
assertEquals(HSSFFont.BOLDWEIGHT_BOLD, cs.getFont(wbComplex).getBoldweight());
}
}

View File

@ -1,113 +0,0 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import junit.framework.TestCase;
import org.apache.poi.hssf.model.Sheet;
/**
* Tests HSSFWorkbook method setSheetOrder()
*
*
* @author Ruel Loehr (loehr1 at us.ibm.com)
*/
public class TestHSSFSheetOrder
extends TestCase
{
public TestHSSFSheetOrder(String s)
{
super(s);
}
/**
* Test the sheet set order method
*/
public void testBackupRecord()
throws Exception
{
HSSFWorkbook wb = new HSSFWorkbook();
for (int i=0; i < 10; i++)
{
HSSFSheet s = wb.createSheet("Sheet " + i);
Sheet sheet = s.getSheet();
}
// Check the initial order
assertEquals(0, wb.getSheetIndex("Sheet 0"));
assertEquals(1, wb.getSheetIndex("Sheet 1"));
assertEquals(2, wb.getSheetIndex("Sheet 2"));
assertEquals(3, wb.getSheetIndex("Sheet 3"));
assertEquals(4, wb.getSheetIndex("Sheet 4"));
assertEquals(5, wb.getSheetIndex("Sheet 5"));
assertEquals(6, wb.getSheetIndex("Sheet 6"));
assertEquals(7, wb.getSheetIndex("Sheet 7"));
assertEquals(8, wb.getSheetIndex("Sheet 8"));
assertEquals(9, wb.getSheetIndex("Sheet 9"));
// Change
wb.getWorkbook().setSheetOrder("Sheet 6", 0);
wb.getWorkbook().setSheetOrder("Sheet 3", 7);
wb.getWorkbook().setSheetOrder("Sheet 1", 9);
// Check they're currently right
assertEquals(0, wb.getSheetIndex("Sheet 6"));
assertEquals(1, wb.getSheetIndex("Sheet 0"));
assertEquals(2, wb.getSheetIndex("Sheet 2"));
assertEquals(3, wb.getSheetIndex("Sheet 4"));
assertEquals(4, wb.getSheetIndex("Sheet 5"));
assertEquals(5, wb.getSheetIndex("Sheet 7"));
assertEquals(6, wb.getSheetIndex("Sheet 3"));
assertEquals(7, wb.getSheetIndex("Sheet 8"));
assertEquals(8, wb.getSheetIndex("Sheet 9"));
assertEquals(9, wb.getSheetIndex("Sheet 1"));
// Read it in and see if it is correct.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
HSSFWorkbook wbr = new HSSFWorkbook(bais);
assertEquals(0, wbr.getSheetIndex("Sheet 6"));
assertEquals(1, wbr.getSheetIndex("Sheet 0"));
assertEquals(2, wbr.getSheetIndex("Sheet 2"));
assertEquals(3, wbr.getSheetIndex("Sheet 4"));
assertEquals(4, wbr.getSheetIndex("Sheet 5"));
assertEquals(5, wbr.getSheetIndex("Sheet 7"));
assertEquals(6, wbr.getSheetIndex("Sheet 3"));
assertEquals(7, wbr.getSheetIndex("Sheet 8"));
assertEquals(8, wbr.getSheetIndex("Sheet 9"));
assertEquals(9, wbr.getSheetIndex("Sheet 1"));
// Now get the index by the sheet, not the name
for(int i=0; i<10; i++) {
HSSFSheet s = wbr.getSheetAt(i);
assertEquals(i, wbr.getSheetIndex(s));
}
}
}

View File

@ -26,6 +26,7 @@ import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.record.NameRecord;
@ -36,12 +37,15 @@ import org.apache.poi.hssf.record.WindowOneRecord;
import org.apache.poi.hssf.record.formula.Area3DPtg;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.TempFile;
import org.apache.poi.ss.usermodel.BaseTestWorkbook;
/**
* Tests for {@link HSSFWorkbook}
*/
public final class TestHSSFWorkbook extends TestCase {
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
public final class TestHSSFWorkbook extends BaseTestWorkbook {
@Override
protected HSSFITestDataProvider getTestDataProvider(){
return HSSFITestDataProvider.getInstance();
}
public void testSetRepeatingRowsAndColumns() {
@ -72,44 +76,6 @@ public final class TestHSSFWorkbook extends TestCase {
}
}
public void testDuplicateNames() {
HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet("Sheet1");
b.createSheet();
b.createSheet("name1");
try {
b.createSheet("name1");
fail();
} catch (IllegalArgumentException pass) {
// expected during successful test
}
b.createSheet();
try {
b.setSheetName(3, "name1");
fail();
} catch (IllegalArgumentException pass) {
// expected during successful test
}
try {
b.setSheetName(3, "name1");
fail();
} catch (IllegalArgumentException pass) {
// expected during successful test
}
b.setSheetName( 3, "name2" );
b.setSheetName( 3, "name2" );
b.setSheetName( 3, "name2" );
HSSFWorkbook c = new HSSFWorkbook( );
c.createSheet("Sheet1");
c.createSheet("Sheet2");
c.createSheet("Sheet3");
c.createSheet("Sheet4");
}
public void testWindowOneDefaults() {
HSSFWorkbook b = new HSSFWorkbook( );
try {
@ -147,17 +113,6 @@ public final class TestHSSFWorkbook extends TestCase {
assertEquals(false, w1.getHidden());
}
public void testSheetSelection() {
HSSFWorkbook b = new HSSFWorkbook();
b.createSheet("Sheet One");
b.createSheet("Sheet Two");
b.setActiveSheet(1);
b.setSelectedTab(1);
b.setFirstVisibleTab(1);
assertEquals(1, b.getActiveSheetIndex());
assertEquals(1, b.getFirstVisibleTab());
}
public void testSheetClone() {
// First up, try a simple file
HSSFWorkbook b = new HSSFWorkbook();
@ -170,7 +125,7 @@ public final class TestHSSFWorkbook extends TestCase {
assertEquals(3, b.getNumberOfSheets());
// Now try a problem one with drawing records in it
b = openSample("SheetWithDrawing.xls");
b = getTestDataProvider().openSampleWorkbook("SheetWithDrawing.xls");
assertEquals(1, b.getNumberOfSheets());
b.cloneSheet(0);
assertEquals(2, b.getNumberOfSheets());
@ -181,7 +136,7 @@ public final class TestHSSFWorkbook extends TestCase {
HSSFSheet s;
// Single chart, two sheets
b = openSample("44010-SingleChart.xls");
b = getTestDataProvider().openSampleWorkbook("44010-SingleChart.xls");
assertEquals(2, b.getNumberOfSheets());
assertEquals("Graph2", b.getSheetName(1));
s = b.getSheetAt(1);
@ -197,7 +152,7 @@ public final class TestHSSFWorkbook extends TestCase {
// We've now called getDrawingPatriarch() so
// everything will be all screwy
// So, start again
b = openSample("44010-SingleChart.xls");
b = getTestDataProvider().openSampleWorkbook("44010-SingleChart.xls");
b = writeRead(b);
assertEquals(2, b.getNumberOfSheets());
@ -207,7 +162,7 @@ public final class TestHSSFWorkbook extends TestCase {
// Two charts, three sheets
b = openSample("44010-TwoCharts.xls");
b = getTestDataProvider().openSampleWorkbook("44010-TwoCharts.xls");
assertEquals(3, b.getNumberOfSheets());
s = b.getSheetAt(1);
@ -227,7 +182,7 @@ public final class TestHSSFWorkbook extends TestCase {
// We've now called getDrawingPatriarch() so
// everything will be all screwy
// So, start again
b = openSample("44010-TwoCharts.xls");
b = getTestDataProvider().openSampleWorkbook("44010-TwoCharts.xls");
b = writeRead(b);
assertEquals(3, b.getNumberOfSheets());
@ -434,7 +389,7 @@ public final class TestHSSFWorkbook extends TestCase {
* that point to deleted sheets
*/
public void testNamesToDeleteSheets() {
HSSFWorkbook b = openSample("30978-deleted.xls");
HSSFWorkbook b = getTestDataProvider().openSampleWorkbook("30978-deleted.xls");
assertEquals(3, b.getNumberOfNames());
// Sheet 2 is deleted

View File

@ -546,29 +546,4 @@ public final class TestWorkbook extends TestCase {
assertTrue("file exists",file.exists());
}
public void testParentReferences(){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
assertSame(workbook, sheet.getWorkbook());
HSSFRow row = sheet.createRow(0);
assertSame(sheet, row.getSheet());
HSSFCell cell = row.createCell(1);
assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow());
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
assertSame(workbook, sheet.getWorkbook());
row = sheet.getRow(0);
assertSame(sheet, row.getSheet());
cell = row.getCell(1);
assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow());
}
}

View File

@ -21,9 +21,12 @@ import junit.framework.TestCase;
import junit.framework.AssertionFailedError;
import org.apache.poi.ss.ITestDataProvider;
import java.util.Date;
import java.util.Calendar;
/**
* Common superclass for testing {@link org.apache.poi.xssf.usermodel.XSSFCell} and
* {@link org.apache.poi.hssf.usermodel.HSSFCell}
* Common superclass for testing implementatiosn of
* {@link org.apache.poi.ss.usermodel.Cell}
*/
public abstract class BaseTestCell extends TestCase {
@ -32,7 +35,7 @@ public abstract class BaseTestCell extends TestCase {
*/
protected abstract ITestDataProvider getTestDataProvider();
public void baseTestSetValues() {
public void testSetValues() {
Workbook book = getTestDataProvider().createWorkbook();
Sheet sheet = book.createSheet("test");
Row row = sheet.createRow(0);
@ -43,24 +46,87 @@ public abstract class BaseTestCell extends TestCase {
cell.setCellValue(1.2);
assertEquals(1.2, cell.getNumericCellValue(), 0.0001);
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_BOOLEAN, Cell.CELL_TYPE_STRING,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR);
cell.setCellValue(false);
assertEquals(false, cell.getBooleanCellValue());
assertEquals(Cell.CELL_TYPE_BOOLEAN, cell.getCellType());
cell.setCellValue(true);
assertEquals(true, cell.getBooleanCellValue());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_STRING,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR);
cell.setCellValue(factory.createRichTextString("Foo"));
assertEquals("Foo", cell.getRichStringCellValue().getString());
assertEquals("Foo", cell.getStringCellValue());
assertEquals(Cell.CELL_TYPE_STRING, cell.getCellType());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_BOOLEAN,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR);
cell.setCellValue(factory.createRichTextString("345"));
cell.setCellValue("345");
assertEquals("345", cell.getRichStringCellValue().getString());
assertEquals("345", cell.getStringCellValue());
assertEquals(Cell.CELL_TYPE_STRING, cell.getCellType());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_BOOLEAN,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(123456789);
cell.setCellValue(c.getTime());
assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime());
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_BOOLEAN, Cell.CELL_TYPE_STRING,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR);
cell.setCellValue(c);
assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime());
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_BOOLEAN, Cell.CELL_TYPE_STRING,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_ERROR);
cell.setCellErrorValue(FormulaError.NA.getCode());
assertEquals(FormulaError.NA.getCode(), cell.getErrorCellValue());
assertEquals(Cell.CELL_TYPE_ERROR, cell.getCellType());
assertProhibitedValueAccess(cell, Cell.CELL_TYPE_NUMERIC, Cell.CELL_TYPE_BOOLEAN,
Cell.CELL_TYPE_FORMULA, Cell.CELL_TYPE_STRING);
}
private void assertProhibitedValueAccess(Cell cell, int ... types){
for(int type : types){
try {
switch (type) {
case Cell.CELL_TYPE_NUMERIC:
cell.getNumericCellValue();
fail();
break;
case Cell.CELL_TYPE_STRING:
cell.getStringCellValue();
fail();
break;
case Cell.CELL_TYPE_BOOLEAN:
cell.getBooleanCellValue();
fail();
break;
case Cell.CELL_TYPE_FORMULA:
cell.getCellFormula();
fail();
break;
case Cell.CELL_TYPE_ERROR:
cell.getErrorCellValue();
fail();
break;
}
} catch (IllegalStateException e){
;
}
}
}
/**
* test that Boolean and Error types (BoolErrRecord) are supported properly.
*/
public void baseTestBoolErr() {
public void testBoolErr() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet s = wb.createSheet("testSheet1");
@ -101,7 +167,7 @@ public abstract class BaseTestCell extends TestCase {
/**
* test that Cell Styles being applied to formulas remain intact
*/
public void baseTestFormulaStyle() {
public void testFormulaStyle() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet s = wb.createSheet("testSheet1");
@ -142,7 +208,7 @@ public abstract class BaseTestCell extends TestCase {
}
/**tests the toString() method of HSSFCell*/
public void baseTestToString() {
public void testToString() {
Workbook wb = getTestDataProvider().createWorkbook();
Row r = wb.createSheet("Sheet1").createRow(0);
CreationHelper factory = wb.getCreationHelper();
@ -173,7 +239,7 @@ public abstract class BaseTestCell extends TestCase {
/**
* Test that setting cached formula result keeps the cell type
*/
public void baseTestSetFormulaValue() {
public void testSetFormulaValue() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet s = wb.createSheet();
Row r = s.createRow(0);
@ -274,4 +340,46 @@ public abstract class BaseTestCell extends TestCase {
assertEquals(true, cell.getBooleanCellValue());
}
/**
* Bug 40296: HSSFCell.setCellFormula throws
* ClassCastException if cell is created using HSSFRow.createCell(short column, int type)
*/
public void test40296() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet workSheet = wb.createSheet("Sheet1");
Cell cell;
Row row = workSheet.createRow(0);
cell = row.createCell(0, Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(1.0);
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertEquals(1.0, cell.getNumericCellValue());
cell = row.createCell(1, Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(2.0);
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertEquals(2.0, cell.getNumericCellValue());
cell = row.createCell(2, Cell.CELL_TYPE_FORMULA);
cell.setCellFormula("SUM(A1:B1)");
assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
assertEquals("SUM(A1:B1)", cell.getCellFormula());
//serialize and check again
wb = getTestDataProvider().writeOutAndReadBack(wb);
row = wb.getSheetAt(0).getRow(0);
cell = row.getCell(0);
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertEquals(1.0, cell.getNumericCellValue());
cell = row.getCell(1);
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
assertEquals(2.0, cell.getNumericCellValue());
cell = row.getCell(2);
assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
assertEquals("SUM(A1:B1)", cell.getCellFormula());
}
}

View File

@ -23,7 +23,7 @@ import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider;
/**
* Tests for {@link org.apache.poi.xssf.usermodel.XSSFDataFormat}
* Tests of implementation of {@link DataFormat}
*
*/
public abstract class BaseTestDataFormat extends TestCase {

View File

@ -0,0 +1,173 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider;
/**
* Tests of implementation of {@link org.apache.poi.ss.usermodel.Name}
*
*/
public abstract class BaseTestNamedRange extends TestCase {
/**
* @return an object that provides test data in HSSF / XSSF specific way
*/
protected abstract ITestDataProvider getTestDataProvider();
public void testCreate(){
// Create a new workbook
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet1 = wb.createSheet("Test1");
Sheet sheet2 = wb.createSheet("Testing Named Ranges");
Name name1 = wb.createName();
name1.setNameName("testOne");
//setting a duplicate name should throw IllegalArgumentException
Name name2 = wb.createName();
try {
name2.setNameName("testOne");
fail("expected exception");
} catch (IllegalArgumentException e){
assertEquals("The workbook already contains this name: testOne", e.getMessage());
}
//the check for duplicates is case-insensitive
try {
name2.setNameName("TESTone");
fail("expected exception");
} catch (IllegalArgumentException e){
assertEquals("The workbook already contains this name: TESTone", e.getMessage());
}
name2.setNameName("testTwo");
String ref1 = "Test1!$A$1:$B$1";
name1.setRefersToFormula(ref1);
assertEquals(ref1, name1.getRefersToFormula());
assertEquals("Test1", name1.getSheetName());
String ref2 = "'Testing Named Ranges'!$A$1:$B$1";
name1.setRefersToFormula(ref2);
assertEquals("'Testing Named Ranges'!$A$1:$B$1", name1.getRefersToFormula());
assertEquals("Testing Named Ranges", name1.getSheetName());
assertEquals(-1, name1.getSheetIndex());
name1.setSheetIndex(-1);
assertEquals(-1, name1.getSheetIndex());
try {
name1.setSheetIndex(2);
fail("should throw IllegalArgumentException");
} catch(IllegalArgumentException e){
assertEquals("Sheet index (2) is out of range (0..1)", e.getMessage());
}
name1.setSheetIndex(1);
assertEquals(1, name1.getSheetIndex());
//-1 means the name applies to the entire workbook
name1.setSheetIndex(-1);
assertEquals(-1, name1.getSheetIndex());
}
public void testUnicodeNamedRange() {
Workbook workBook = getTestDataProvider().createWorkbook();
workBook.createSheet("Test");
Name name = workBook.createName();
name.setNameName("\u03B1");
name.setRefersToFormula("Test!$D$3:$E$8");
Workbook workBook2 = getTestDataProvider().writeOutAndReadBack(workBook);
Name name2 = workBook2.getNameAt(0);
assertEquals("\u03B1", name2.getNameName());
assertEquals("Test!$D$3:$E$8", name2.getRefersToFormula());
}
public void testAddRemove() {
Workbook wb = getTestDataProvider().createWorkbook();
assertEquals(0, wb.getNumberOfNames());
Name name1 = wb.createName();
name1.setNameName("name1");
assertEquals(1, wb.getNumberOfNames());
Name name2 = wb.createName();
name2.setNameName("name2");
assertEquals(2, wb.getNumberOfNames());
Name name3 = wb.createName();
name3.setNameName("name3");
assertEquals(3, wb.getNumberOfNames());
wb.removeName("name2");
assertEquals(2, wb.getNumberOfNames());
wb.removeName(0);
assertEquals(1, wb.getNumberOfNames());
}
public void testScope() {
Workbook wb = getTestDataProvider().createWorkbook();
wb.createSheet();
wb.createSheet();
Name name;
name = wb.createName();
name.setNameName("aaa");
name = wb.createName();
try {
name.setNameName("aaa");
fail("Expected exception");
} catch(Exception e){
assertEquals("The workbook already contains this name: aaa", e.getMessage());
}
name = wb.createName();
name.setSheetIndex(0);
name.setNameName("aaa");
name = wb.createName();
name.setSheetIndex(0);
try {
name.setNameName("aaa");
fail("Expected exception");
} catch(Exception e){
assertEquals("The sheet already contains this name: aaa", e.getMessage());
}
name = wb.createName();
name.setSheetIndex(1);
name.setNameName("aaa");
name = wb.createName();
name.setSheetIndex(1);
try {
name.setNameName("aaa");
fail("Expected exception");
} catch(Exception e){
assertEquals("The sheet already contains this name: aaa", e.getMessage());
}
int cnt = 0;
for (int i = 0; i < wb.getNumberOfNames(); i++) {
if("aaa".equals(wb.getNameAt(i).getNameName())) cnt++;
}
assertEquals(3, cnt);
}
}

View File

@ -0,0 +1,376 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider;
import java.util.Iterator;
/**
* A base class for testing implementations of
* {@link org.apache.poi.ss.usermodel.Row}
*/
public abstract class BaseTestRow extends TestCase {
/**
* @return an object that provides test data in / XSSF specific way
*/
protected abstract ITestDataProvider getTestDataProvider();
public void testLastAndFirstColumns() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
assertEquals(-1, row.getFirstCellNum());
assertEquals(-1, row.getLastCellNum());
row.createCell(2);
assertEquals(2, row.getFirstCellNum());
assertEquals(3, row.getLastCellNum());
row.createCell(1);
assertEquals(1, row.getFirstCellNum());
assertEquals(3, row.getLastCellNum());
// check the exact case reported in 'bug' 43901 - notice that the cellNum is '0' based
row.createCell(3);
assertEquals(1, row.getFirstCellNum());
assertEquals(4, row.getLastCellNum());
}
/**
* Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum
* This test was added in response to bug report 44987.
*/
public void testBoundsInMultipleRows() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
Row rowA = sheet.createRow(0);
rowA.createCell(10);
rowA.createCell(5);
assertEquals(5, rowA.getFirstCellNum());
assertEquals(11, rowA.getLastCellNum());
Row rowB = sheet.createRow(1);
rowB.createCell(15);
rowB.createCell(30);
assertEquals(15, rowB.getFirstCellNum());
assertEquals(31, rowB.getLastCellNum());
assertEquals(5, rowA.getFirstCellNum());
assertEquals(11, rowA.getLastCellNum());
rowA.createCell(50);
assertEquals(51, rowA.getLastCellNum());
assertEquals(31, rowB.getLastCellNum());
}
public void testRemoveCell() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
assertEquals(0, row.getPhysicalNumberOfCells());
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
row.createCell(1);
assertEquals(2, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
assertEquals(1, row.getPhysicalNumberOfCells());
row.createCell(3);
assertEquals(4, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
assertEquals(2, row.getPhysicalNumberOfCells());
row.removeCell(row.getCell(3));
assertEquals(2, row.getLastCellNum());
assertEquals(1, row.getFirstCellNum());
assertEquals(1, row.getPhysicalNumberOfCells());
row.removeCell(row.getCell(1));
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
assertEquals(0, row.getPhysicalNumberOfCells());
workbook = getTestDataProvider().writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
row = sheet.getRow(0);
assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum());
assertEquals(0, row.getPhysicalNumberOfCells());
}
public void baseTestRowBounds(int maxRowNum) {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
//Test low row bound
sheet.createRow(0);
//Test low row bound exception
try {
sheet.createRow(-1);
fail("expected exception");
} catch (IllegalArgumentException e) {
// expected during successful test
assertTrue(e.getMessage().startsWith("Invalid row number (-1)"));
}
//Test high row bound
sheet.createRow(maxRowNum);
//Test high row bound exception
try {
sheet.createRow(maxRowNum + 1);
fail("expected exception");
} catch (IllegalArgumentException e) {
// expected during successful test
assertEquals("Invalid row number ("+(maxRowNum + 1)+") outside allowable range (0.."+maxRowNum+")", e.getMessage());
}
}
public void baseTestCellBounds(int maxCellNum) {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
//Test low cell bound
try {
Cell cell = row.createCell(-1);
fail("expected exception");
} catch (IllegalArgumentException e) {
// expected during successful test
assertTrue(e.getMessage().startsWith("Invalid column index (-1)"));
}
row.createCell(maxCellNum);
//Test high cell bound
try {
Cell cell = row.createCell(maxCellNum + 1);
fail("expected exception");
} catch (IllegalArgumentException e) {
// expected during successful test
assertTrue(e.getMessage().startsWith("Invalid column index ("+(maxCellNum+1)+")"));
}
}
/**
* Prior to patch 43901, POI was producing files with the wrong last-column
* number on the row
*/
public void testLastCellNumIsCorrectAfterAddCell_bug43901(){
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet("test");
Row row = sheet.createRow(0);
// New row has last col -1
assertEquals(-1, row.getLastCellNum());
if(row.getLastCellNum() == 0) {
fail("Identified bug 43901");
}
// Create two cells, will return one higher
// than that for the last number
row.createCell(0);
assertEquals(1, row.getLastCellNum());
row.createCell(255);
assertEquals(256, row.getLastCellNum());
}
/**
* Tests for the missing/blank cell policy stuff
*/
public void testGetCellPolicy() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet("test");
Row row = sheet.createRow(0);
// 0 -> string
// 1 -> num
// 2 missing
// 3 missing
// 4 -> blank
// 5 -> num
row.createCell(0).setCellValue("test");
row.createCell(1).setCellValue(3.2);
row.createCell(4, Cell.CELL_TYPE_BLANK);
row.createCell(5).setCellValue(4);
// First up, no policy given, uses default
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1).getCellType());
assertEquals(null, row.getCell(2));
assertEquals(null, row.getCell(3));
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(4).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType());
// RETURN_NULL_AND_BLANK - same as default
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0, Row.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1, Row.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(null, row.getCell(2, Row.RETURN_NULL_AND_BLANK));
assertEquals(null, row.getCell(3, Row.RETURN_NULL_AND_BLANK));
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(4, Row.RETURN_NULL_AND_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, Row.RETURN_NULL_AND_BLANK).getCellType());
// RETURN_BLANK_AS_NULL - nearly the same
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0, Row.RETURN_BLANK_AS_NULL).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1, Row.RETURN_BLANK_AS_NULL).getCellType());
assertEquals(null, row.getCell(2, Row.RETURN_BLANK_AS_NULL));
assertEquals(null, row.getCell(3, Row.RETURN_BLANK_AS_NULL));
assertEquals(null, row.getCell(4, Row.RETURN_BLANK_AS_NULL));
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, Row.RETURN_BLANK_AS_NULL).getCellType());
// CREATE_NULL_AS_BLANK - creates as needed
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0, Row.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1, Row.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(2, Row.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(3, Row.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_BLANK, row.getCell(4, Row.CREATE_NULL_AS_BLANK).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, Row.CREATE_NULL_AS_BLANK).getCellType());
// Check created ones get the right column
assertEquals(0, row.getCell(0, Row.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(1, row.getCell(1, Row.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(2, row.getCell(2, Row.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(3, row.getCell(3, Row.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(4, row.getCell(4, Row.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals(5, row.getCell(5, Row.CREATE_NULL_AS_BLANK).getColumnIndex());
// Now change the cell policy on the workbook, check
// that that is now used if no policy given
workbook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);
assertEquals(Cell.CELL_TYPE_STRING, row.getCell(0).getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(1).getCellType());
assertEquals(null, row.getCell(2));
assertEquals(null, row.getCell(3));
assertEquals(null, row.getCell(4));
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType());
}
public void testRowHeight() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
Row row1 = sheet.createRow(0);
assertEquals(sheet.getDefaultRowHeight(), row1.getHeight());
sheet.setDefaultRowHeightInPoints(20);
row1.setHeight((short)-1); //reset the row height
assertEquals(20.0f, row1.getHeightInPoints());
assertEquals(20*20, row1.getHeight());
Row row2 = sheet.createRow(1);
row2.setHeight((short)310);
assertEquals(310, row2.getHeight());
assertEquals((float)310/20, row2.getHeightInPoints());
Row row3 = sheet.createRow(2);
row3.setHeightInPoints(25.5f);
assertEquals((short)(25.5f*20), row3.getHeight());
assertEquals(25.5f, row3.getHeightInPoints());
Row row4 = sheet.createRow(3);
assertFalse(row4.getZeroHeight());
row4.setZeroHeight(true);
assertTrue(row4.getZeroHeight());
workbook = getTestDataProvider().writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
row1 = sheet.getRow(0);
row2 = sheet.getRow(1);
row3 = sheet.getRow(2);
row4 = sheet.getRow(3);
assertEquals(20.0f, row1.getHeightInPoints());
assertEquals(20*20, row1.getHeight());
assertEquals(310, row2.getHeight());
assertEquals((float)310/20, row2.getHeightInPoints());
assertEquals((short)(25.5f*20), row3.getHeight());
assertEquals(25.5f, row3.getHeightInPoints());
assertFalse(row1.getZeroHeight());
assertFalse(row2.getZeroHeight());
assertFalse(row3.getZeroHeight());
assertTrue(row4.getZeroHeight());
}
/**
* Test adding cells to a row in various places and see if we can find them again.
*/
public void testCellIterator() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
// One cell at the beginning
Cell cell1 = row.createCell(1);
Iterator<Cell> it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell1 == it.next());
assertFalse(it.hasNext());
// Add another cell at the end
Cell cell2 = row.createCell(99);
it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell1 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
// Add another cell at the beginning
Cell cell3 = row.createCell(0);
it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell3 == it.next());
assertTrue(it.hasNext());
assertTrue(cell1 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
// Replace cell1
Cell cell4 = row.createCell(1);
it = row.cellIterator();
assertTrue(it.hasNext());
assertTrue(cell3 == it.next());
assertTrue(it.hasNext());
assertTrue(cell4 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
assertFalse(it.hasNext());
// Add another cell, specifying the cellType
Cell cell5 = row.createCell(2, Cell.CELL_TYPE_STRING);
it = row.cellIterator();
assertNotNull(cell5);
assertTrue(it.hasNext());
assertTrue(cell3 == it.next());
assertTrue(it.hasNext());
assertTrue(cell4 == it.next());
assertTrue(it.hasNext());
assertTrue(cell5 == it.next());
assertTrue(it.hasNext());
assertTrue(cell2 == it.next());
assertEquals(Cell.CELL_TYPE_STRING, cell5.getCellType());
}
}

View File

@ -0,0 +1,565 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.Iterator;
/**
* Common superclass for testing {@link org.apache.poi.xssf.usermodel.XSSFCell} and
* {@link org.apache.poi.hssf.usermodel.HSSFCell}
*/
public abstract class BaseTestSheet extends TestCase {
/**
* @return an object that provides test data in HSSF / XSSF specific way
*/
protected abstract ITestDataProvider getTestDataProvider();
public void testCreateRow() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
assertEquals(0, sheet.getPhysicalNumberOfRows());
//Test that we get null for undefined rownumber
assertNull(sheet.getRow(1));
// Test row creation with consecutive indexes
Row row1 = sheet.createRow(0);
Row row2 = sheet.createRow(1);
assertEquals(0, row1.getRowNum());
assertEquals(1, row2.getRowNum());
Iterator<Row> it = sheet.rowIterator();
assertTrue(it.hasNext());
assertSame(row1, it.next());
assertTrue(it.hasNext());
assertSame(row2, it.next());
assertEquals(1, sheet.getLastRowNum());
// Test row creation with non consecutive index
Row row101 = sheet.createRow(100);
assertNotNull(row101);
assertEquals(100, sheet.getLastRowNum());
assertEquals(3, sheet.getPhysicalNumberOfRows());
// Test overwriting an existing row
Row row2_ovrewritten = sheet.createRow(1);
Cell cell = row2_ovrewritten.createCell(0);
cell.setCellValue(100);
Iterator<Row> it2 = sheet.rowIterator();
assertTrue(it2.hasNext());
assertSame(row1, it2.next());
assertTrue(it2.hasNext());
Row row2_ovrewritten_ref = it2.next();
assertSame(row2_ovrewritten, row2_ovrewritten_ref);
assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue());
}
public void testRemoveRow() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet1 = workbook.createSheet();
assertEquals(0, sheet1.getPhysicalNumberOfRows());
Row row0 = sheet1.createRow(0);
assertEquals(1, sheet1.getPhysicalNumberOfRows());
sheet1.removeRow(row0);
assertEquals(0, sheet1.getPhysicalNumberOfRows());
Row row1 = sheet1.createRow(1);
Row row2 = sheet1.createRow(2);
assertEquals(2, sheet1.getPhysicalNumberOfRows());
assertNotNull(sheet1.getRow(1));
assertNotNull(sheet1.getRow(2));
sheet1.removeRow(row2);
assertNotNull(sheet1.getRow(1));
assertNull(sheet1.getRow(2));
Row row3 = sheet1.createRow(3);
Sheet sheet2 = workbook.createSheet();
try {
sheet2.removeRow(row3);
fail("Expected exception");
} catch (IllegalArgumentException e){
assertEquals("Specified row does not belong to this sheet", e.getMessage());
}
}
public void testCloneSheet() {
Workbook workbook = getTestDataProvider().createWorkbook();
CreationHelper factory = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Test Clone");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
Cell cell2 = row.createCell(1);
cell.setCellValue(factory.createRichTextString("clone_test"));
cell2.setCellFormula("SIN(1)");
Sheet clonedSheet = workbook.cloneSheet(0);
Row clonedRow = clonedSheet.getRow(0);
//Check for a good clone
assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
//Check that the cells are not somehow linked
cell.setCellValue(factory.createRichTextString("Difference Check"));
cell2.setCellFormula("cos(2)");
if ("Difference Check".equals(clonedRow.getCell(0).getRichStringCellValue().getString())) {
fail("string cell not properly cloned");
}
if ("COS(2)".equals(clonedRow.getCell(1).getCellFormula())) {
fail("formula cell not properly cloned");
}
assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)");
}
/** tests that the sheet name for multiple clones of the same sheet is unique
* BUG 37416
*/
public void testCloneSheetMultipleTimes() {
Workbook workbook = getTestDataProvider().createWorkbook();
CreationHelper factory = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Test Clone");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(factory.createRichTextString("clone_test"));
//Clone the sheet multiple times
workbook.cloneSheet(0);
workbook.cloneSheet(0);
assertNotNull(workbook.getSheet("Test Clone"));
assertNotNull(workbook.getSheet("Test Clone (2)"));
assertEquals("Test Clone (3)", workbook.getSheetName(2));
assertNotNull(workbook.getSheet("Test Clone (3)"));
workbook.removeSheetAt(0);
workbook.removeSheetAt(0);
workbook.removeSheetAt(0);
workbook.createSheet("abc ( 123)");
workbook.cloneSheet(0);
assertEquals("abc (124)", workbook.getSheetName(1));
}
/**
* Setting landscape and portrait stuff on new sheets
*/
public void testPrintSetupLandscapeNew() throws Exception {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheetL = workbook.createSheet("LandscapeS");
Sheet sheetP = workbook.createSheet("LandscapeP");
// Check two aspects of the print setup
assertFalse(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(1, sheetL.getPrintSetup().getCopies());
assertEquals(1, sheetP.getPrintSetup().getCopies());
// Change one on each
sheetL.getPrintSetup().setLandscape(true);
sheetP.getPrintSetup().setCopies((short)3);
// Check taken
assertTrue(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(1, sheetL.getPrintSetup().getCopies());
assertEquals(3, sheetP.getPrintSetup().getCopies());
// Save and re-load, and check still there
workbook = getTestDataProvider().writeOutAndReadBack(workbook);
sheetL = workbook.getSheet("LandscapeS");
sheetP = workbook.getSheet("LandscapeP");
assertTrue(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(1, sheetL.getPrintSetup().getCopies());
assertEquals(3, sheetP.getPrintSetup().getCopies());
}
/**
* When removing one merged region, it would break
*
*/
public void testRemoveMerged() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet();
CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
sheet.addMergedRegion(region);
region = new CellRangeAddress(1, 2, 0, 1);
sheet.addMergedRegion(region);
sheet.removeMergedRegion(0);
region = sheet.getMergedRegion(0);
assertEquals("Left over region should be starting at row 1", 1, region.getFirstRow());
sheet.removeMergedRegion(0);
assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions());
//an, add, remove, get(0) would null pointer
sheet.addMergedRegion(region);
assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
sheet.removeMergedRegion(0);
assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions());
//add it again!
region.setLastRow(4);
sheet.addMergedRegion(region);
assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
//should exist now!
assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions());
region = sheet.getMergedRegion(0);
assertEquals("the merged row to doesnt match the one we put in ", 4, region.getLastRow());
}
public void testShiftMerged() {
Workbook wb = getTestDataProvider().createWorkbook();
CreationHelper factory = wb.getCreationHelper();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(factory.createRichTextString("first row, first cell"));
row = sheet.createRow(1);
cell = row.createCell(1);
cell.setCellValue(factory.createRichTextString("second row, second cell"));
CellRangeAddress region = new CellRangeAddress(1, 1, 0, 1);
sheet.addMergedRegion(region);
sheet.shiftRows(1, 1, 1);
region = sheet.getMergedRegion(0);
assertEquals("Merged region not moved over to row 2", 2, region.getFirstRow());
}
/**
* Tests the display of gridlines, formulas, and rowcolheadings.
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testDisplayOptions() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet();
assertEquals(sheet.isDisplayGridlines(), true);
assertEquals(sheet.isDisplayRowColHeadings(), true);
assertEquals(sheet.isDisplayFormulas(), false);
assertEquals(sheet.isDisplayZeros(), true);
sheet.setDisplayGridlines(false);
sheet.setDisplayRowColHeadings(false);
sheet.setDisplayFormulas(true);
sheet.setDisplayZeros(false);
wb = getTestDataProvider().writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
assertEquals(sheet.isDisplayGridlines(), false);
assertEquals(sheet.isDisplayRowColHeadings(), false);
assertEquals(sheet.isDisplayFormulas(), true);
assertEquals(sheet.isDisplayZeros(), false);
}
public void testColumnWidth() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet();
//default column width measured in characters
sheet.setDefaultColumnWidth(10);
assertEquals(10, sheet.getDefaultColumnWidth());
//columns A-C have default width
assertEquals(256*10, sheet.getColumnWidth(0));
assertEquals(256*10, sheet.getColumnWidth(1));
assertEquals(256*10, sheet.getColumnWidth(2));
//set custom width for D-F
for (char i = 'D'; i <= 'F'; i++) {
//Sheet#setColumnWidth accepts the width in units of 1/256th of a character width
int w = 256*12;
sheet.setColumnWidth(i, w);
assertEquals(w, sheet.getColumnWidth(i));
}
//reset the default column width, columns A-C change, D-F still have custom width
sheet.setDefaultColumnWidth(20);
assertEquals(20, sheet.getDefaultColumnWidth());
assertEquals(256*20, sheet.getColumnWidth(0));
assertEquals(256*20, sheet.getColumnWidth(1));
assertEquals(256*20, sheet.getColumnWidth(2));
for (char i = 'D'; i <= 'F'; i++) {
int w = 256*12;
assertEquals(w, sheet.getColumnWidth(i));
}
// check for 16-bit signed/unsigned error:
sheet.setColumnWidth(10, 40000);
assertEquals(40000, sheet.getColumnWidth(10));
//The maximum column width for an individual cell is 255 characters
try {
sheet.setColumnWidth(9, 256*256);
fail("expected exception");
} catch(IllegalArgumentException e){
assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage());
}
//serialize and read again
wb = getTestDataProvider().writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
assertEquals(20, sheet.getDefaultColumnWidth());
//columns A-C have default width
assertEquals(256*20, sheet.getColumnWidth(0));
assertEquals(256*20, sheet.getColumnWidth(1));
assertEquals(256*20, sheet.getColumnWidth(2));
//columns D-F have custom width
for (char i = 'D'; i <= 'F'; i++) {
short w = (256*12);
assertEquals(w, sheet.getColumnWidth(i));
}
assertEquals(40000, sheet.getColumnWidth(10));
}
public void testDefaultRowHeight() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
sheet.setDefaultRowHeightInPoints(15);
assertEquals((short) 300, sheet.getDefaultRowHeight());
assertEquals((float) 15, sheet.getDefaultRowHeightInPoints());
// Set a new default row height in twips and test getting the value in points
sheet.setDefaultRowHeight((short) 360);
assertEquals(18.0f, sheet.getDefaultRowHeightInPoints());
assertEquals((short) 360, sheet.getDefaultRowHeight());
// Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18
sheet.setDefaultRowHeight((short) 361);
assertEquals((float)361/20, sheet.getDefaultRowHeightInPoints());
assertEquals((short) 361, sheet.getDefaultRowHeight());
// Set a new default row height in points and test getting the value in twips
sheet.setDefaultRowHeightInPoints(17.5f);
assertEquals(17.5f, sheet.getDefaultRowHeightInPoints());
assertEquals((short)(17.5f*20), sheet.getDefaultRowHeight());
}
/** cell with formula becomes null on cloning a sheet*/
public void test35084() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet s = wb.createSheet("Sheet1");
Row r = s.createRow(0);
r.createCell(0).setCellValue(1);
r.createCell(1).setCellFormula("A1*2");
Sheet s1 = wb.cloneSheet(0);
r = s1.getRow(0);
assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check
assertNotNull(r.getCell(1));
assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2");
}
/** test that new default column styles get applied */
public void testDefaultColumnStyle() {
Workbook wb = getTestDataProvider().createWorkbook();
CellStyle style = wb.createCellStyle();
Sheet sheet = wb.createSheet();
sheet.setDefaultColumnStyle(0, style);
assertNotNull(sheet.getColumnStyle(0));
assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex());
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
CellStyle style2 = cell.getCellStyle();
assertNotNull(style2);
assertEquals("style should match", style.getIndex(), style2.getIndex());
}
public void testOutlineProperties() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet();
//TODO defaults are different in HSSF and XSSF
//assertTrue(sheet.getRowSumsBelow());
//assertTrue(sheet.getRowSumsRight());
sheet.setRowSumsBelow(false);
sheet.setRowSumsRight(false);
assertFalse(sheet.getRowSumsBelow());
assertFalse(sheet.getRowSumsRight());
sheet.setRowSumsBelow(true);
sheet.setRowSumsRight(true);
assertTrue(sheet.getRowSumsBelow());
assertTrue(sheet.getRowSumsRight());
wb = getTestDataProvider().writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
assertTrue(sheet.getRowSumsBelow());
assertTrue(sheet.getRowSumsRight());
}
/**
* Test basic display properties
*/
public void testSheetProperties() {
Workbook wb = getTestDataProvider().createWorkbook();
Sheet sheet = wb.createSheet();
assertFalse(sheet.getHorizontallyCenter());
sheet.setHorizontallyCenter(true);
assertTrue(sheet.getHorizontallyCenter());
sheet.setHorizontallyCenter(false);
assertFalse(sheet.getHorizontallyCenter());
assertFalse(sheet.getVerticallyCenter());
sheet.setVerticallyCenter(true);
assertTrue(sheet.getVerticallyCenter());
sheet.setVerticallyCenter(false);
assertFalse(sheet.getVerticallyCenter());
assertFalse(sheet.isPrintGridlines());
sheet.setPrintGridlines(true);
assertTrue(sheet.isPrintGridlines());
assertFalse(sheet.isDisplayFormulas());
sheet.setDisplayFormulas(true);
assertTrue(sheet.isDisplayFormulas());
assertTrue(sheet.isDisplayGridlines());
sheet.setDisplayGridlines(false);
assertFalse(sheet.isDisplayGridlines());
//TODO: default "guts" is different in HSSF and XSSF
//assertTrue(sheet.getDisplayGuts());
sheet.setDisplayGuts(false);
assertFalse(sheet.getDisplayGuts());
assertTrue(sheet.isDisplayRowColHeadings());
sheet.setDisplayRowColHeadings(false);
assertFalse(sheet.isDisplayRowColHeadings());
//TODO: default "autobreaks" is different in HSSF and XSSF
//assertTrue(sheet.getAutobreaks());
sheet.setAutobreaks(false);
assertFalse(sheet.getAutobreaks());
assertFalse(sheet.getScenarioProtect());
//TODO: default "fit-to-page" is different in HSSF and XSSF
//assertFalse(sheet.getFitToPage());
sheet.setFitToPage(true);
assertTrue(sheet.getFitToPage());
sheet.setFitToPage(false);
assertFalse(sheet.getFitToPage());
}
public void baseTestGetSetMargin(double[] defaultMargins) {
double marginLeft = defaultMargins[0];
double marginRight = defaultMargins[1];
double marginTop = defaultMargins[2];
double marginBottom = defaultMargins[3];
double marginHeader = defaultMargins[4];
double marginFooter = defaultMargins[5];
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1");
assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin));
sheet.setMargin(Sheet.LeftMargin, 10.0);
//left margin is custom, all others are default
assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin));
assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin));
assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin));
assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin));
sheet.setMargin(Sheet.RightMargin, 11.0);
assertEquals(11.0, sheet.getMargin(Sheet.RightMargin));
sheet.setMargin(Sheet.TopMargin, 12.0);
assertEquals(12.0, sheet.getMargin(Sheet.TopMargin));
sheet.setMargin(Sheet.BottomMargin, 13.0);
assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin));
// incorrect margin constant
try {
sheet.setMargin((short) 65, 15);
fail("Expected exception");
} catch (IllegalArgumentException e){
assertEquals("Unknown margin constant: 65", e.getMessage());
}
}
public void testRowBreaks() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
//Sheet#getRowBreaks() returns an empty array if no row breaks are defined
assertNotNull(sheet.getRowBreaks());
assertEquals(0, sheet.getRowBreaks().length);
sheet.setRowBreak(1);
assertEquals(1, sheet.getRowBreaks().length);
sheet.setRowBreak(15);
assertEquals(2, sheet.getRowBreaks().length);
assertEquals(1, sheet.getRowBreaks()[0]);
assertEquals(15, sheet.getRowBreaks()[1]);
sheet.setRowBreak(1);
assertEquals(2, sheet.getRowBreaks().length);
assertTrue(sheet.isRowBroken(1));
assertTrue(sheet.isRowBroken(15));
//now remove the created breaks
sheet.removeRowBreak(1);
assertEquals(1, sheet.getRowBreaks().length);
sheet.removeRowBreak(15);
assertEquals(0, sheet.getRowBreaks().length);
assertFalse(sheet.isRowBroken(1));
assertFalse(sheet.isRowBroken(15));
}
public void testColumnBreaks() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
assertNotNull(sheet.getColumnBreaks());
assertEquals(0, sheet.getColumnBreaks().length);
assertFalse(sheet.isColumnBroken(0));
sheet.setColumnBreak(11);
assertNotNull(sheet.getColumnBreaks());
assertEquals(11, sheet.getColumnBreaks()[0]);
sheet.setColumnBreak(12);
assertEquals(2, sheet.getColumnBreaks().length);
assertTrue(sheet.isColumnBroken(11));
assertTrue(sheet.isColumnBroken(12));
sheet.removeColumnBreak((short) 11);
assertEquals(1, sheet.getColumnBreaks().length);
sheet.removeColumnBreak((short) 15); //remove non-existing
assertEquals(1, sheet.getColumnBreaks().length);
sheet.removeColumnBreak((short) 12);
assertEquals(0, sheet.getColumnBreaks().length);
assertFalse(sheet.isColumnBroken(11));
assertFalse(sheet.isColumnBroken(12));
}
}

View File

@ -0,0 +1,276 @@
package org.apache.poi.ss.usermodel;
import junit.framework.TestCase;
import junit.framework.AssertionFailedError;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* @author Yegor Kozlov
*/
public abstract class BaseTestWorkbook extends TestCase {
protected abstract ITestDataProvider getTestDataProvider();
public void testCreateSheet() {
Workbook wb = getTestDataProvider().createWorkbook();
assertEquals(0, wb.getNumberOfSheets());
//getting a sheet by invalid index or non-existing name
assertNull(wb.getSheet("Sheet1"));
try {
wb.getSheetAt(0);
fail("should have thrown exceptiuon due to invalid sheet index");
} catch (IllegalArgumentException e) {
// expected during successful test
;
}
Sheet sheet0 = wb.createSheet();
Sheet sheet1 = wb.createSheet();
assertEquals("Sheet0", sheet0.getSheetName());
assertEquals("Sheet1", sheet1.getSheetName());
assertEquals(2, wb.getNumberOfSheets());
//fetching sheets by name is case-insensitive
Sheet originalSheet = wb.createSheet("Sheet3");
Sheet fetchedSheet = wb.getSheet("sheet3");
if (fetchedSheet == null) {
throw new AssertionFailedError("Identified bug 44892");
}
assertEquals("Sheet3", fetchedSheet.getSheetName());
assertEquals(3, wb.getNumberOfSheets());
assertSame(originalSheet, fetchedSheet);
try {
wb.createSheet("sHeeT3");
fail("should have thrown exceptiuon due to duplicate sheet name");
} catch (IllegalArgumentException e) {
// expected during successful test
assertEquals("The workbook already contains a sheet of this name", e.getMessage());
}
//names cannot be blank or contain any of /\*?[]
String[] invalidNames = {"", "Sheet/", "Sheet\\",
"Sheet?", "Sheet*", "Sheet[", "Sheet]"};
for (String sheetName : invalidNames) {
try {
wb.createSheet(sheetName);
fail("should have thrown exceptiuon due to invalid sheet name: " + sheetName);
} catch (IllegalArgumentException e) {
// expected during successful test
;
}
}
//still have 3 sheets
assertEquals(3, wb.getNumberOfSheets());
//change the name of the 3rd sheet
wb.setSheetName(2, "I changed!");
//try to assign an invalid name to the 2nd sheet
try {
wb.setSheetName(1, "[I'm invalid]");
fail("should have thrown exceptiuon due to invalid sheet name");
} catch (IllegalArgumentException e) {
; // expected during successful test
}
//check
assertEquals(0, wb.getSheetIndex("sheet0"));
assertEquals(1, wb.getSheetIndex("sheet1"));
assertEquals(2, wb.getSheetIndex("I changed!"));
assertSame(sheet0, wb.getSheet("sheet0"));
assertSame(sheet1, wb.getSheet("sheet1"));
assertSame(originalSheet, wb.getSheet("I changed!"));
assertNull(wb.getSheet("unknown"));
//serialize and read again
wb = getTestDataProvider().writeOutAndReadBack(wb);
assertEquals(3, wb.getNumberOfSheets());
assertEquals(0, wb.getSheetIndex("sheet0"));
assertEquals(1, wb.getSheetIndex("sheet1"));
assertEquals(2, wb.getSheetIndex("I changed!"));
}
public void testRemoveSheetAt() {
Workbook workbook = getTestDataProvider().createWorkbook();
workbook.createSheet("sheet1");
workbook.createSheet("sheet2");
workbook.createSheet("sheet3");
assertEquals(3, workbook.getNumberOfSheets());
workbook.removeSheetAt(1);
assertEquals(2, workbook.getNumberOfSheets());
assertEquals("sheet3", workbook.getSheetName(1));
workbook.removeSheetAt(0);
assertEquals(1, workbook.getNumberOfSheets());
assertEquals("sheet3", workbook.getSheetName(0));
workbook.removeSheetAt(0);
assertEquals(0, workbook.getNumberOfSheets());
}
public void testDefaultValues() {
Workbook b = getTestDataProvider().createWorkbook();
assertEquals(0, b.getActiveSheetIndex());
assertEquals(0, b.getFirstVisibleTab());
assertEquals(0, b.getNumberOfNames());
assertEquals(0, b.getNumberOfSheets());
}
public void testSheetSelection() {
Workbook b = getTestDataProvider().createWorkbook();
b.createSheet("Sheet One");
b.createSheet("Sheet Two");
b.setActiveSheet(1);
b.setSelectedTab(1);
b.setFirstVisibleTab(1);
assertEquals(1, b.getActiveSheetIndex());
assertEquals(1, b.getFirstVisibleTab());
}
public void testPrintArea() {
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet1 = workbook.createSheet("Test Print Area");
String sheetName1 = sheet1.getSheetName();
// workbook.setPrintArea(0, reference);
workbook.setPrintArea(0, 1, 5, 4, 9);
String retrievedPrintArea = workbook.getPrintArea(0);
assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea);
String reference = "$A$1:$B$1";
workbook.setPrintArea(0, reference);
retrievedPrintArea = workbook.getPrintArea(0);
assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea);
workbook.removePrintArea(0);
assertNull(workbook.getPrintArea(0));
}
public void testGetSetActiveSheet(){
Workbook workbook = getTestDataProvider().createWorkbook();
assertEquals(0, workbook.getActiveSheetIndex());
workbook.createSheet("sheet1");
workbook.createSheet("sheet2");
workbook.createSheet("sheet3");
// set second sheet
workbook.setActiveSheet(1);
// test if second sheet is set up
assertEquals(1, workbook.getActiveSheetIndex());
workbook.setActiveSheet(0);
// test if second sheet is set up
assertEquals(0, workbook.getActiveSheetIndex());
}
public void testSetSheetOrder() {
Workbook wb = getTestDataProvider().createWorkbook();
for (int i=0; i < 10; i++) {
Sheet sh = wb.createSheet("Sheet " + i);
}
// Check the initial order
assertEquals(0, wb.getSheetIndex("Sheet 0"));
assertEquals(1, wb.getSheetIndex("Sheet 1"));
assertEquals(2, wb.getSheetIndex("Sheet 2"));
assertEquals(3, wb.getSheetIndex("Sheet 3"));
assertEquals(4, wb.getSheetIndex("Sheet 4"));
assertEquals(5, wb.getSheetIndex("Sheet 5"));
assertEquals(6, wb.getSheetIndex("Sheet 6"));
assertEquals(7, wb.getSheetIndex("Sheet 7"));
assertEquals(8, wb.getSheetIndex("Sheet 8"));
assertEquals(9, wb.getSheetIndex("Sheet 9"));
// Change
wb.setSheetOrder("Sheet 6", 0);
wb.setSheetOrder("Sheet 3", 7);
wb.setSheetOrder("Sheet 1", 9);
// Check they're currently right
assertEquals(0, wb.getSheetIndex("Sheet 6"));
assertEquals(1, wb.getSheetIndex("Sheet 0"));
assertEquals(2, wb.getSheetIndex("Sheet 2"));
assertEquals(3, wb.getSheetIndex("Sheet 4"));
assertEquals(4, wb.getSheetIndex("Sheet 5"));
assertEquals(5, wb.getSheetIndex("Sheet 7"));
assertEquals(6, wb.getSheetIndex("Sheet 3"));
assertEquals(7, wb.getSheetIndex("Sheet 8"));
assertEquals(8, wb.getSheetIndex("Sheet 9"));
assertEquals(9, wb.getSheetIndex("Sheet 1"));
Workbook wbr = getTestDataProvider().writeOutAndReadBack(wb);
assertEquals(0, wbr.getSheetIndex("Sheet 6"));
assertEquals(1, wbr.getSheetIndex("Sheet 0"));
assertEquals(2, wbr.getSheetIndex("Sheet 2"));
assertEquals(3, wbr.getSheetIndex("Sheet 4"));
assertEquals(4, wbr.getSheetIndex("Sheet 5"));
assertEquals(5, wbr.getSheetIndex("Sheet 7"));
assertEquals(6, wbr.getSheetIndex("Sheet 3"));
assertEquals(7, wbr.getSheetIndex("Sheet 8"));
assertEquals(8, wbr.getSheetIndex("Sheet 9"));
assertEquals(9, wbr.getSheetIndex("Sheet 1"));
// Now get the index by the sheet, not the name
for(int i=0; i<10; i++) {
Sheet s = wbr.getSheetAt(i);
assertEquals(i, wbr.getSheetIndex(s));
}
}
public void testCloneSheet() {
Workbook book = getTestDataProvider().createWorkbook();
Sheet sheet = book.createSheet("TEST");
sheet.createRow(0).createCell(0).setCellValue("Test");
sheet.createRow(1).createCell(0).setCellValue(36.6);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2));
sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 2));
assertTrue(sheet.isSelected());
Sheet clonedSheet = book.cloneSheet(0);
assertEquals("TEST (2)", clonedSheet.getSheetName());
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
assertEquals(2, clonedSheet.getNumMergedRegions());
assertFalse(clonedSheet.isSelected());
//cloned sheet is a deep copy, adding rows in the original does not affect the clone
sheet.createRow(2).createCell(0).setCellValue(1);
sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2));
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
assertEquals(2, clonedSheet.getPhysicalNumberOfRows());
clonedSheet.createRow(2).createCell(0).setCellValue(1);
clonedSheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 2));
assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
}
public void testParentReferences(){
Workbook workbook = getTestDataProvider().createWorkbook();
Sheet sheet = workbook.createSheet();
assertSame(workbook, sheet.getWorkbook());
Row row = sheet.createRow(0);
assertSame(sheet, row.getSheet());
Cell cell = row.createCell(1);
assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow());
workbook = getTestDataProvider().writeOutAndReadBack(workbook);
sheet = workbook.getSheetAt(0);
assertSame(workbook, sheet.getWorkbook());
row = sheet.getRow(0);
assertSame(sheet, row.getSheet());
cell = row.getCell(1);
assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow());
}
}