Merged revisions 638786-638802,638805-638811,638813-638814,638816-639230,639233-639241,639243-639253,639255-639486,639488-639601,639603-639835,639837-639917,639919-640056,640058-640710,640712-641156,641158-641184,641186-641795,641797-641798,641800-641933,641935-641963,641965-641966,641968-641995,641997-642230,642232-642562,642564-642565,642568-642570,642572-642573,642576-642736,642739-642877,642879,642881-642890,642892-642903,642905-642945,642947-643624,643626-643653,643655-643669,643671,643673-643830,643832-643833,643835-644342,644344-644472,644474-644508,644510-645478 via svnmerge from

https://svn.apache.org:443/repos/asf/poi/trunk

........
  r645348 | josh | 2008-04-07 04:02:03 +0100 (Mon, 07 Apr 2008) | 1 line
  
  refactored all hssf junits to get test sample data in the in one place
........
  r645352 | josh | 2008-04-07 04:23:04 +0100 (Mon, 07 Apr 2008) | 2 lines
  
  30311 - More work on Conditional Formatting - patch from Dmitriy
........


git-svn-id: https://svn.apache.org/repos/asf/poi/branches/ooxml@645483 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Nick Burch 2008-04-07 12:51:50 +00:00
parent 559508b7e0
commit cbecd918ab
57 changed files with 3379 additions and 4394 deletions

View File

@ -37,6 +37,8 @@
<!-- Don't forget to update status.xml too! --> <!-- Don't forget to update status.xml too! -->
<release version="3.0.3-beta1" date="2008-04-??"> <release version="3.0.3-beta1" date="2008-04-??">
<action dev="POI-DEVELOPERS" type="add">30311 - More work on Conditional Formatting</action>
<action dev="POI-DEVELOPERS" type="fix">refactored all junits' usage of HSSF.testdata.path to one place</action>
<action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action> <action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action>
<action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action> <action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action>
<action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action> <action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action>

View File

@ -34,6 +34,8 @@
<!-- Don't forget to update changes.xml too! --> <!-- Don't forget to update changes.xml too! -->
<changes> <changes>
<release version="3.0.3-beta1" date="2008-04-??"> <release version="3.0.3-beta1" date="2008-04-??">
<action dev="POI-DEVELOPERS" type="add">30311 - More work on Conditional Formatting</action>
<action dev="POI-DEVELOPERS" type="fix">refactored all junits' usage of HSSF.testdata.path to one place</action>
<action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action> <action dev="POI-DEVELOPERS" type="fix">44739 - Small fixes for conditional formatting (regions with max row/col index)</action>
<action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action> <action dev="RK" type="add">44694 - HPSF: Support for property sets without sections</action>
<action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action> <action dev="POI-DEVELOPERS" type="add">Implement Sheet.removeShape(Shape shape) in HSLF</action>

View File

@ -238,6 +238,17 @@ public final class CFRuleRecord extends Record
this.fontFormatting = fontFormatting; this.fontFormatting = fontFormatting;
setOptionFlag(fontFormatting != null, font); setOptionFlag(fontFormatting != null, font);
} }
public FontFormatting getFontFormatting()
{
if( containsFontFormattingBlock())
{
return fontFormatting;
}
else
{
return null;
}
}
public boolean containsAlignFormattingBlock() public boolean containsAlignFormattingBlock()
{ {
@ -257,6 +268,17 @@ public final class CFRuleRecord extends Record
this.borderFormatting = borderFormatting; this.borderFormatting = borderFormatting;
setOptionFlag(borderFormatting != null, bord); setOptionFlag(borderFormatting != null, bord);
} }
public BorderFormatting getBorderFormatting()
{
if( containsBorderFormattingBlock())
{
return borderFormatting;
}
else
{
return null;
}
}
public boolean containsPatternFormattingBlock() public boolean containsPatternFormattingBlock()
{ {
@ -267,7 +289,17 @@ public final class CFRuleRecord extends Record
this.patternFormatting = patternFormatting; this.patternFormatting = patternFormatting;
setOptionFlag(patternFormatting!=null, patt); setOptionFlag(patternFormatting!=null, patt);
} }
public PatternFormatting getPatternFormatting()
{
if( containsPatternFormattingBlock())
{
return patternFormatting;
}
else
{
return null;
}
}
public boolean containsProtectionFormattingBlock() public boolean containsProtectionFormattingBlock()
{ {
@ -616,12 +648,6 @@ public final class CFRuleRecord extends Record
return rec; return rec;
} }
public FontFormatting getFontFormatting()
{
return fontFormatting;
}
/** /**
* @return <code>null</code> if <tt>formula</tt> was null. * @return <code>null</code> if <tt>formula</tt> was null.
*/ */

View File

@ -45,8 +45,8 @@ public class FontFormatting
private static final int OFFSET_OPTION_FLAGS = 88; private static final int OFFSET_OPTION_FLAGS = 88;
private static final int OFFSET_ESCAPEMENT_TYPE_MODIFIED = 92; private static final int OFFSET_ESCAPEMENT_TYPE_MODIFIED = 92;
private static final int OFFSET_UNDERLINE_TYPE_MODIFIED = 96; private static final int OFFSET_UNDERLINE_TYPE_MODIFIED = 96;
private static final int OFFSET_NOT_USED1 = 100; private static final int OFFSET_FONT_WEIGHT_MODIFIED = 100;
private static final int OFFSET_NOT_USED2 = 104; private static final int OFFSET_NOT_USED = 104;
private static final int OFFSET_FONT_FORMATING_END = 116; private static final int OFFSET_FONT_FORMATING_END = 116;
@ -56,7 +56,6 @@ public class FontFormatting
private static final BitField posture = BitFieldFactory.getInstance(0x00000002); private static final BitField posture = BitFieldFactory.getInstance(0x00000002);
private static final BitField outline = BitFieldFactory.getInstance(0x00000008); private static final BitField outline = BitFieldFactory.getInstance(0x00000008);
private static final BitField shadow = BitFieldFactory.getInstance(0x00000010); private static final BitField shadow = BitFieldFactory.getInstance(0x00000010);
private static final BitField condense = BitFieldFactory.getInstance(0x00000020);
private static final BitField cancellation = BitFieldFactory.getInstance(0x00000080); private static final BitField cancellation = BitFieldFactory.getInstance(0x00000080);
// OPTION FLAGS MASKS // OPTION FLAGS MASKS
@ -64,7 +63,6 @@ public class FontFormatting
private static final BitField styleModified = BitFieldFactory.getInstance(0x00000002); private static final BitField styleModified = BitFieldFactory.getInstance(0x00000002);
private static final BitField outlineModified = BitFieldFactory.getInstance(0x00000008); private static final BitField outlineModified = BitFieldFactory.getInstance(0x00000008);
private static final BitField shadowModified = BitFieldFactory.getInstance(0x00000010); private static final BitField shadowModified = BitFieldFactory.getInstance(0x00000010);
private static final BitField condenseModified = BitFieldFactory.getInstance(0x00000020);
private static final BitField cancellationModified = BitFieldFactory.getInstance(0x00000080); private static final BitField cancellationModified = BitFieldFactory.getInstance(0x00000080);
/** /**
@ -125,10 +123,9 @@ public class FontFormatting
this.setFontHeight((short)-1); this.setFontHeight((short)-1);
this.setItalic(false); this.setItalic(false);
this.setBold(false); this.setFontWieghtModified(false);
this.setOutline(false); this.setOutline(false);
this.setShadow(false); this.setShadow(false);
this.setCondense(false);
this.setStrikeout(false); this.setStrikeout(false);
this.setEscapementType((short)0); this.setEscapementType((short)0);
this.setUnderlineType((byte)0); this.setUnderlineType((byte)0);
@ -137,15 +134,13 @@ public class FontFormatting
this.setFontStyleModified(false); this.setFontStyleModified(false);
this.setFontOutlineModified(false); this.setFontOutlineModified(false);
this.setFontShadowModified(false); this.setFontShadowModified(false);
this.setFontCondenseModified(false);
this.setFontCancellationModified(false); this.setFontCancellationModified(false);
this.setEscapementTypeModified(false); this.setEscapementTypeModified(false);
this.setUnderlineTypeModified(false); this.setUnderlineTypeModified(false);
LittleEndian.putShort(record, OFFSET_FONT_NAME, (short)0); LittleEndian.putShort(record, OFFSET_FONT_NAME, (short)0);
LittleEndian.putInt(record, OFFSET_NOT_USED1, 0x00000001); LittleEndian.putInt(record, OFFSET_NOT_USED, 0x00000001);
LittleEndian.putInt(record, OFFSET_NOT_USED2, 0x00000001);
LittleEndian.putShort(record, OFFSET_FONT_FORMATING_END, (short)0x0001); LittleEndian.putShort(record, OFFSET_FONT_FORMATING_END, (short)0x0001);
} }
@ -249,16 +244,6 @@ public class FontFormatting
return getFontOption(shadow); return getFontOption(shadow);
} }
public void setCondense(boolean on)
{
setFontOption(on, condense);
}
public boolean isCondenseOn()
{
return getFontOption(condense);
}
/** /**
* set the font to be stricken out or not * set the font to be stricken out or not
* *
@ -420,6 +405,7 @@ public class FontFormatting
return getOptionFlag(styleModified); return getOptionFlag(styleModified);
} }
public void setFontStyleModified(boolean modified) public void setFontStyleModified(boolean modified)
{ {
setOptionFlag(modified, styleModified); setOptionFlag(modified, styleModified);
@ -444,16 +430,6 @@ public class FontFormatting
{ {
setOptionFlag(modified, shadowModified); setOptionFlag(modified, shadowModified);
} }
public boolean isFontCondenseModified()
{
return getOptionFlag(condenseModified);
}
public void setFontCondenseModified(boolean modified)
{
setOptionFlag(modified, condenseModified);
}
public void setFontCancellationModified(boolean modified) public void setFontCancellationModified(boolean modified)
{ {
setOptionFlag(modified, cancellationModified); setOptionFlag(modified, cancellationModified);
@ -469,7 +445,6 @@ public class FontFormatting
int value = modified? 0 : 1; int value = modified? 0 : 1;
LittleEndian.putInt(record,OFFSET_ESCAPEMENT_TYPE_MODIFIED, value); LittleEndian.putInt(record,OFFSET_ESCAPEMENT_TYPE_MODIFIED, value);
} }
public boolean isEscapementTypeModified() public boolean isEscapementTypeModified()
{ {
int escapementModified = LittleEndian.getInt(record,OFFSET_ESCAPEMENT_TYPE_MODIFIED); int escapementModified = LittleEndian.getInt(record,OFFSET_ESCAPEMENT_TYPE_MODIFIED);
@ -488,6 +463,18 @@ public class FontFormatting
return underlineModified == 0; return underlineModified == 0;
} }
public void setFontWieghtModified(boolean modified)
{
int value = modified? 0 : 1;
LittleEndian.putInt(record,OFFSET_FONT_WEIGHT_MODIFIED, value);
}
public boolean isFontWeightModified()
{
int fontStyleModified = LittleEndian.getInt(record,OFFSET_FONT_WEIGHT_MODIFIED);
return fontStyleModified == 0;
}
public String toString() public String toString()
{ {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
@ -521,14 +508,6 @@ public class FontFormatting
{ {
buffer.append(" .font shadow is not modified\n"); buffer.append(" .font shadow is not modified\n");
} }
if( isFontCondenseModified() )
{
buffer.append(" .font condense = ").append(isCondenseOn()).append("\n");
}
else
{
buffer.append(" .font condense is not modified\n");
}
if( isFontCancellationModified() ) if( isFontCancellationModified() )
{ {
@ -573,6 +552,27 @@ public class FontFormatting
buffer.append(" .color index = ").append("0x"+Integer.toHexString(getFontColorIndex()).toUpperCase()).append("\n"); buffer.append(" .color index = ").append("0x"+Integer.toHexString(getFontColorIndex()).toUpperCase()).append("\n");
buffer.append(" ====\n");
buffer.append(" ["+OFFSET_FONT_HEIGHT+"] FONT HEIGHT: "+intToHex(OFFSET_FONT_HEIGHT)+"\n");
buffer.append(" ["+OFFSET_FONT_OPTIONS+"] FONT OPTIONS: "+intToHex(OFFSET_FONT_OPTIONS)+"\n");
buffer.append(" ["+OFFSET_FONT_WEIGHT+"] FONT WEIGHT: "+shortToHex(OFFSET_FONT_WEIGHT)+"\n");
buffer.append(" ["+OFFSET_ESCAPEMENT_TYPE+"] FONT ESCAPEMENT: "+shortToHex(OFFSET_ESCAPEMENT_TYPE)+"\n");
buffer.append(" ["+OFFSET_UNDERLINE_TYPE+"] FONT UNDERLINE: "+byteToHex(OFFSET_UNDERLINE_TYPE)+"\n");
buffer.append(" ["+(OFFSET_UNDERLINE_TYPE+1)+"] FONT NOT USED: "+byteToHex(OFFSET_UNDERLINE_TYPE+1)+"\n");
buffer.append(" ["+(OFFSET_UNDERLINE_TYPE+2)+"] FONT NOT USED: "+byteToHex(OFFSET_UNDERLINE_TYPE+2)+"\n");
buffer.append(" ["+(OFFSET_UNDERLINE_TYPE+3)+"] FONT NOT USED: "+byteToHex(OFFSET_UNDERLINE_TYPE+3)+"\n");
buffer.append(" ["+OFFSET_FONT_COLOR_INDEX+"] FONT COLIDX: "+intToHex(OFFSET_FONT_COLOR_INDEX)+"\n");
buffer.append(" ["+(OFFSET_FONT_COLOR_INDEX+4)+"] FONT NOT USED: "+intToHex(OFFSET_FONT_COLOR_INDEX+4)+"\n");
buffer.append(" ["+OFFSET_OPTION_FLAGS+"] FONT OPTIONS: "+intToHex(OFFSET_OPTION_FLAGS)+"\n");
buffer.append(" ["+OFFSET_ESCAPEMENT_TYPE_MODIFIED+"] FONT ESC MOD: "+intToHex(OFFSET_ESCAPEMENT_TYPE_MODIFIED)+"\n");
buffer.append(" ["+OFFSET_UNDERLINE_TYPE_MODIFIED+"] FONT UND MOD: "+intToHex(OFFSET_UNDERLINE_TYPE_MODIFIED)+"\n");
buffer.append(" ["+OFFSET_FONT_WEIGHT+"] FONT WGH MOD: "+intToHex(OFFSET_FONT_WEIGHT)+"\n");
buffer.append(" ["+OFFSET_NOT_USED+"] FONT NOT USED: "+intToHex(OFFSET_NOT_USED)+"\n");
buffer.append(" ["+(OFFSET_NOT_USED+4)+"] FONT NOT USED: "+intToHex(OFFSET_NOT_USED+4)+"\n");
buffer.append(" ["+(OFFSET_NOT_USED+8)+"] FONT NOT USED: "+intToHex(OFFSET_NOT_USED+8)+"\n");
buffer.append(" ["+OFFSET_FONT_FORMATING_END+"] FONT FORMATTING END: "+shortToHex(OFFSET_FONT_FORMATING_END)+"\n");
buffer.append(" ====\n");
buffer.append(" [/Font Formatting]\n"); buffer.append(" [/Font Formatting]\n");
return buffer.toString(); return buffer.toString();
} }
@ -588,4 +588,18 @@ public class FontFormatting
} }
return rec; return rec;
} }
private String intToHex(int offset)
{
return Integer.toHexString(LittleEndian.getInt(record, offset));
}
private String shortToHex(int offset)
{
return Integer.toHexString(LittleEndian.getShort(record, offset)&0xFFFF);
}
private String byteToHex(int offset)
{
return Integer.toHexString(record[offset]&0xFF);
}
} }

View File

@ -65,6 +65,11 @@ public final class HSSFBorderFormatting
borderFormatting = new BorderFormatting(); borderFormatting = new BorderFormatting();
} }
protected HSSFBorderFormatting(BorderFormatting borderFormatting)
{
this.borderFormatting = borderFormatting;
}
protected BorderFormatting getBorderFormattingBlock() protected BorderFormatting getBorderFormattingBlock()
{ {
return borderFormatting; return borderFormatting;

View File

@ -17,8 +17,6 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.util.List;
import org.apache.poi.hssf.model.FormulaParser; import org.apache.poi.hssf.model.FormulaParser;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.CFRuleRecord; import org.apache.poi.hssf.record.CFRuleRecord;
@ -41,9 +39,6 @@ public final class HSSFConditionalFormattingRule
{ {
private static final byte CELL_COMPARISON = CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS; private static final byte CELL_COMPARISON = CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS;
private final CFRuleRecord cfRuleRecord; private final CFRuleRecord cfRuleRecord;
private final Workbook workbook; private final Workbook workbook;
@ -73,6 +68,19 @@ public final class HSSFConditionalFormattingRule
FontFormatting block = fontFmt==null ? null : fontFmt.getFontFormattingBlock(); FontFormatting block = fontFmt==null ? null : fontFmt.getFontFormattingBlock();
cfRuleRecord.setFontFormatting(block); cfRuleRecord.setFontFormatting(block);
} }
/**
* @return - font formatting object if defined, <code>null</code> otherwise
*/
public HSSFFontFormatting getFontFormatting()
{
FontFormatting ff = cfRuleRecord.getFontFormatting();
if ( ff == null ) {
return null;
}
return new HSSFFontFormatting(ff);
}
/** /**
* @param borderFmt pass <code>null</code> to signify 'border unchanged' * @param borderFmt pass <code>null</code> to signify 'border unchanged'
*/ */
@ -81,6 +89,17 @@ public final class HSSFConditionalFormattingRule
BorderFormatting block = borderFmt==null ? null : borderFmt.getBorderFormattingBlock(); BorderFormatting block = borderFmt==null ? null : borderFmt.getBorderFormattingBlock();
cfRuleRecord.setBorderFormatting(block); cfRuleRecord.setBorderFormatting(block);
} }
/**
* @return - border formatting object if defined, <code>null</code> otherwise
*/
public HSSFBorderFormatting getBorderFormatting()
{
BorderFormatting bf = cfRuleRecord.getBorderFormatting();
if ( bf == null ) {
return null;
}
return new HSSFBorderFormatting(bf);
}
/** /**
* @param patternFmt pass <code>null</code> to signify 'pattern unchanged' * @param patternFmt pass <code>null</code> to signify 'pattern unchanged'
*/ */
@ -89,6 +108,17 @@ public final class HSSFConditionalFormattingRule
PatternFormatting block = patternFmt==null ? null : patternFmt.getPatternFormattingBlock(); PatternFormatting block = patternFmt==null ? null : patternFmt.getPatternFormattingBlock();
cfRuleRecord.setPatternFormatting(block); cfRuleRecord.setPatternFormatting(block);
} }
/**
* @return - pattern formatting object if defined, <code>null</code> otherwise
*/
public HSSFPatternFormatting getPatternFormatting()
{
PatternFormatting pf = cfRuleRecord.getPatternFormatting();
if ( pf == null ) {
return null;
}
return new HSSFPatternFormatting(pf);
}
public String getFormula1() public String getFormula1()
{ {
@ -112,11 +142,9 @@ public final class HSSFConditionalFormattingRule
private String toFormulaString(Ptg[] parsedExpression) private String toFormulaString(Ptg[] parsedExpression)
{ {
String formula = null; if(parsedExpression ==null) {
if(parsedExpression!=null) return null;
{
formula = FormulaParser.toFormulaString(workbook, parsedExpression);
} }
return formula; return FormulaParser.toFormulaString(workbook, parsedExpression);
} }
} }

View File

@ -25,64 +25,51 @@ import org.apache.poi.hssf.record.cf.FontFormatting;
* @author Dmitriy Kumshayev * @author Dmitriy Kumshayev
* *
*/ */
public class HSSFFontFormatting public final class HSSFFontFormatting
{ {
/** /** Escapement type - None */
* Escapement type - None public final static short SS_NONE = FontFormatting.SS_NONE;
*/ /** Escapement type - Superscript */
public final static short SS_NONE = FontFormatting.SS_NONE; public final static short SS_SUPER = FontFormatting.SS_SUPER;
/** Escapement type - Subscript */
public final static short SS_SUB = FontFormatting.SS_SUB;
/** /** Underline type - None */
* Escapement type - Superscript public final static byte U_NONE = FontFormatting.U_NONE;
*/ /** Underline type - Single */
public final static short SS_SUPER = FontFormatting.SS_SUPER; public final static byte U_SINGLE = FontFormatting.U_SINGLE;
/** Underline type - Double */
public final static byte U_DOUBLE = FontFormatting.U_DOUBLE;
/** Underline type - Single Accounting */
public final static byte U_SINGLE_ACCOUNTING = FontFormatting.U_SINGLE_ACCOUNTING;
/** Underline type - Double Accounting */
public final static byte U_DOUBLE_ACCOUNTING = FontFormatting.U_DOUBLE_ACCOUNTING;
/** private final FontFormatting fontFormatting;
* Escapement type - Subscript
*/
public final static short SS_SUB = FontFormatting.SS_SUB;
/**
* Underline type - None
*/
public final static byte U_NONE = FontFormatting.U_NONE;
/**
* Underline type - Single
*/
public final static byte U_SINGLE = FontFormatting.U_SINGLE;
/**
* Underline type - Double
*/
public final static byte U_DOUBLE = FontFormatting.U_DOUBLE;
/**
* Underline type - Single Accounting
*/
public final static byte U_SINGLE_ACCOUNTING = FontFormatting.U_SINGLE_ACCOUNTING;
/**
* Underline type - Double Accounting
*/
public final static byte U_DOUBLE_ACCOUNTING = FontFormatting.U_DOUBLE_ACCOUNTING;
private FontFormatting fontFormatting;
public HSSFFontFormatting() public HSSFFontFormatting()
{ {
fontFormatting = new FontFormatting(); fontFormatting = new FontFormatting();
} }
protected HSSFFontFormatting(FontFormatting ff)
{
fontFormatting = ff;
}
protected FontFormatting getFontFormattingBlock() protected FontFormatting getFontFormattingBlock()
{ {
return fontFormatting; return fontFormatting;
} }
/** /**
* get the type of super or subscript for the font * get the type of super or subscript for the font
* *
* @return super or subscript option * @return super or subscript option
* @see #SS_NONE * @see #SS_NONE
* @see #SS_SUPER * @see #SS_SUPER
* @see #SS_SUB * @see #SS_SUB
*/ */
public short getEscapementType() public short getEscapementType()
{ {
return fontFormatting.getEscapementType(); return fontFormatting.getEscapementType();
@ -96,22 +83,22 @@ public class HSSFFontFormatting
return fontFormatting.getFontColorIndex(); return fontFormatting.getFontColorIndex();
} }
/** /**
* gets the height of the font in 1/20th point units * gets the height of the font in 1/20th point units
* *
* @return fontheight (in points/20); or -1 if not modified * @return fontheight (in points/20); or -1 if not modified
*/ */
public short getFontHeight() public short getFontHeight()
{ {
return fontFormatting.getFontHeight(); return fontFormatting.getFontHeight();
} }
/** /**
* get the font weight for this font (100-1000dec or 0x64-0x3e8). Default is * get the font weight for this font (100-1000dec or 0x64-0x3e8). Default is
* 0x190 for normal and 0x2bc for bold * 0x190 for normal and 0x2bc for bold
* *
* @return bw - a number between 100-1000 for the fonts "boldness" * @return bw - a number between 100-1000 for the fonts "boldness"
*/ */
public short getFontWeight() public short getFontWeight()
{ {
@ -127,38 +114,30 @@ public class HSSFFontFormatting
return fontFormatting.getRawRecord(); return fontFormatting.getRawRecord();
} }
/** /**
* get the type of underlining for the font * get the type of underlining for the font
* *
* @return font underlining type * @return font underlining type
* *
* @see #U_NONE * @see #U_NONE
* @see #U_SINGLE * @see #U_SINGLE
* @see #U_DOUBLE * @see #U_DOUBLE
* @see #U_SINGLE_ACCOUNTING * @see #U_SINGLE_ACCOUNTING
* @see #U_DOUBLE_ACCOUNTING * @see #U_DOUBLE_ACCOUNTING
*/ */
public short getUnderlineType() public short getUnderlineType()
{ {
return fontFormatting.getUnderlineType(); return fontFormatting.getUnderlineType();
} }
/** /**
* get whether the font weight is set to bold or not * get whether the font weight is set to bold or not
* *
* @return bold - whether the font is bold or not * @return bold - whether the font is bold or not
*/ */
public boolean isBold() public boolean isBold()
{ {
return fontFormatting.isBold(); return fontFormatting.isFontWeightModified() && fontFormatting.isBold();
}
/**
* @return whether the font is condense or not
*/
public boolean isCondenseOn()
{
return fontFormatting.isFontOutlineModified() && fontFormatting.isCondenseOn();
} }
/** /**
@ -177,14 +156,6 @@ public class HSSFFontFormatting
return fontFormatting.isFontCancellationModified(); return fontFormatting.isFontCancellationModified();
} }
/**
* @return true if font condense type was modified from default
*/
public boolean isFontCondenseModified()
{
return fontFormatting.isFontCondenseModified();
}
/** /**
* @return true if font outline type was modified from default * @return true if font outline type was modified from default
*/ */
@ -249,66 +220,61 @@ public class HSSFFontFormatting
return fontFormatting.isUnderlineTypeModified(); return fontFormatting.isUnderlineTypeModified();
} }
/** /**
* set font style options. * @return true if font weight was modified from default
* */
* @param italic - if true, set posture style to italic, otherwise to normal public boolean isFontWeightModified()
* @param bold- if true, set font weight to bold, otherwise to normal {
*/ return fontFormatting.isFontWeightModified();
}
/**
* set font style options.
*
* @param italic - if true, set posture style to italic, otherwise to normal
* @param bold- if true, set font weight to bold, otherwise to normal
*/
public void setFontStyle(boolean italic, boolean bold) public void setFontStyle(boolean italic, boolean bold)
{ {
boolean modified = italic || bold; boolean modified = italic || bold;
fontFormatting.setItalic(italic); fontFormatting.setItalic(italic);
fontFormatting.setBold(bold); fontFormatting.setBold(bold);
fontFormatting.setFontStyleModified(modified); fontFormatting.setFontStyleModified(modified);
fontFormatting.setFontWieghtModified(modified);
} }
/** /**
* set font style options to default values (non-italic, non-bold) * set font style options to default values (non-italic, non-bold)
*/ */
public void resetFontStyle() public void resetFontStyle()
{ {
setFontStyle(false,false); setFontStyle(false,false);
} }
/** /**
* set the escapement type for the font * set the escapement type for the font
* *
* @param escapementType super or subscript option * @param escapementType super or subscript option
* @see #SS_NONE * @see #SS_NONE
* @see #SS_SUPER * @see #SS_SUPER
* @see #SS_SUB * @see #SS_SUB
*/ */
public void setCondense(boolean on)
{
fontFormatting.setCondense(on);
fontFormatting.setFontCondenseModified(on);
}
/**
* set the escapement type for the font
*
* @param escapementType super or subscript option
* @see #SS_NONE
* @see #SS_SUPER
* @see #SS_SUB
*/
public void setEscapementType(short escapementType) public void setEscapementType(short escapementType)
{ {
switch(escapementType) switch(escapementType)
{ {
case HSSFFontFormatting.SS_SUB: case HSSFFontFormatting.SS_SUB:
case HSSFFontFormatting.SS_SUPER: case HSSFFontFormatting.SS_SUPER:
fontFormatting.setEscapementType(escapementType); fontFormatting.setEscapementType(escapementType);
fontFormatting.setEscapementTypeModified(true); fontFormatting.setEscapementTypeModified(true);
break; break;
case HSSFFontFormatting.SS_NONE: case HSSFFontFormatting.SS_NONE:
fontFormatting.setEscapementType(escapementType); fontFormatting.setEscapementType(escapementType);
fontFormatting.setEscapementTypeModified(false); fontFormatting.setEscapementTypeModified(false);
break; break;
default: default:
} }
} }
/** /**
@ -338,15 +304,6 @@ public class HSSFFontFormatting
fontFormatting.setFontColorIndex(fci); fontFormatting.setFontColorIndex(fci);
} }
/**
* @param modified
* @see org.apache.poi.hssf.record.cf.FontFormatting#setFontCondenseModified(boolean)
*/
public void setFontCondenseModified(boolean modified)
{
fontFormatting.setFontCondenseModified(modified);
}
/** /**
* @param height * @param height
* @see org.apache.poi.hssf.record.cf.FontFormatting#setFontHeight(short) * @see org.apache.poi.hssf.record.cf.FontFormatting#setFontHeight(short)
@ -413,35 +370,35 @@ public class HSSFFontFormatting
fontFormatting.setFontCancellationModified(strike); fontFormatting.setFontCancellationModified(strike);
} }
/** /**
* set the type of underlining type for the font * set the type of underlining type for the font
* *
* @param u super or subscript option * @param u super or subscript option
* *
* @see #U_NONE * @see #U_NONE
* @see #U_SINGLE * @see #U_SINGLE
* @see #U_DOUBLE * @see #U_DOUBLE
* @see #U_SINGLE_ACCOUNTING * @see #U_SINGLE_ACCOUNTING
* @see #U_DOUBLE_ACCOUNTING * @see #U_DOUBLE_ACCOUNTING
*/ */
public void setUnderlineType(short underlineType) public void setUnderlineType(short underlineType)
{ {
switch(underlineType) switch(underlineType)
{ {
case HSSFFontFormatting.U_SINGLE: case HSSFFontFormatting.U_SINGLE:
case HSSFFontFormatting.U_DOUBLE: case HSSFFontFormatting.U_DOUBLE:
case HSSFFontFormatting.U_SINGLE_ACCOUNTING: case HSSFFontFormatting.U_SINGLE_ACCOUNTING:
case HSSFFontFormatting.U_DOUBLE_ACCOUNTING: case HSSFFontFormatting.U_DOUBLE_ACCOUNTING:
fontFormatting.setUnderlineType(underlineType); fontFormatting.setUnderlineType(underlineType);
setUnderlineTypeModified(true); setUnderlineTypeModified(true);
break; break;
case HSSFFontFormatting.U_NONE: case HSSFFontFormatting.U_NONE:
fontFormatting.setUnderlineType(underlineType); fontFormatting.setUnderlineType(underlineType);
setUnderlineTypeModified(false); setUnderlineTypeModified(false);
break; break;
default: default:
} }
} }
/** /**
@ -452,5 +409,4 @@ public class HSSFFontFormatting
{ {
fontFormatting.setUnderlineTypeModified(modified); fontFormatting.setUnderlineTypeModified(modified);
} }
} }

View File

@ -27,44 +27,44 @@ import org.apache.poi.hssf.record.cf.PatternFormatting;
*/ */
public class HSSFPatternFormatting public class HSSFPatternFormatting
{ {
/** No background */ /** No background */
public final static short NO_FILL = PatternFormatting.NO_FILL; public final static short NO_FILL = PatternFormatting.NO_FILL;
/** Solidly filled */ /** Solidly filled */
public final static short SOLID_FOREGROUND = PatternFormatting.SOLID_FOREGROUND; public final static short SOLID_FOREGROUND = PatternFormatting.SOLID_FOREGROUND;
/** Small fine dots */ /** Small fine dots */
public final static short FINE_DOTS = PatternFormatting.FINE_DOTS; public final static short FINE_DOTS = PatternFormatting.FINE_DOTS;
/** Wide dots */ /** Wide dots */
public final static short ALT_BARS = PatternFormatting.ALT_BARS; public final static short ALT_BARS = PatternFormatting.ALT_BARS;
/** Sparse dots */ /** Sparse dots */
public final static short SPARSE_DOTS = PatternFormatting.SPARSE_DOTS; public final static short SPARSE_DOTS = PatternFormatting.SPARSE_DOTS;
/** Thick horizontal bands */ /** Thick horizontal bands */
public final static short THICK_HORZ_BANDS = PatternFormatting.THICK_HORZ_BANDS; public final static short THICK_HORZ_BANDS = PatternFormatting.THICK_HORZ_BANDS;
/** Thick vertical bands */ /** Thick vertical bands */
public final static short THICK_VERT_BANDS = PatternFormatting.THICK_VERT_BANDS; public final static short THICK_VERT_BANDS = PatternFormatting.THICK_VERT_BANDS;
/** Thick backward facing diagonals */ /** Thick backward facing diagonals */
public final static short THICK_BACKWARD_DIAG = PatternFormatting.THICK_BACKWARD_DIAG; public final static short THICK_BACKWARD_DIAG = PatternFormatting.THICK_BACKWARD_DIAG;
/** Thick forward facing diagonals */ /** Thick forward facing diagonals */
public final static short THICK_FORWARD_DIAG = PatternFormatting.THICK_FORWARD_DIAG; public final static short THICK_FORWARD_DIAG = PatternFormatting.THICK_FORWARD_DIAG;
/** Large spots */ /** Large spots */
public final static short BIG_SPOTS = PatternFormatting.BIG_SPOTS; public final static short BIG_SPOTS = PatternFormatting.BIG_SPOTS;
/** Brick-like layout */ /** Brick-like layout */
public final static short BRICKS = PatternFormatting.BRICKS; public final static short BRICKS = PatternFormatting.BRICKS;
/** Thin horizontal bands */ /** Thin horizontal bands */
public final static short THIN_HORZ_BANDS = PatternFormatting.THIN_HORZ_BANDS; public final static short THIN_HORZ_BANDS = PatternFormatting.THIN_HORZ_BANDS;
/** Thin vertical bands */ /** Thin vertical bands */
public final static short THIN_VERT_BANDS = PatternFormatting.THIN_VERT_BANDS; public final static short THIN_VERT_BANDS = PatternFormatting.THIN_VERT_BANDS;
/** Thin backward diagonal */ /** Thin backward diagonal */
public final static short THIN_BACKWARD_DIAG = PatternFormatting.THIN_BACKWARD_DIAG; public final static short THIN_BACKWARD_DIAG = PatternFormatting.THIN_BACKWARD_DIAG;
/** Thin forward diagonal */ /** Thin forward diagonal */
public final static short THIN_FORWARD_DIAG = PatternFormatting.THIN_FORWARD_DIAG; public final static short THIN_FORWARD_DIAG = PatternFormatting.THIN_FORWARD_DIAG;
/** Squares */ /** Squares */
public final static short SQUARES = PatternFormatting.SQUARES; public final static short SQUARES = PatternFormatting.SQUARES;
/** Diamonds */ /** Diamonds */
public final static short DIAMONDS = PatternFormatting.DIAMONDS; public final static short DIAMONDS = PatternFormatting.DIAMONDS;
/** Less Dots */ /** Less Dots */
public final static short LESS_DOTS = PatternFormatting.LESS_DOTS; public final static short LESS_DOTS = PatternFormatting.LESS_DOTS;
/** Least Dots */ /** Least Dots */
public final static short LEAST_DOTS = PatternFormatting.LEAST_DOTS; public final static short LEAST_DOTS = PatternFormatting.LEAST_DOTS;
private PatternFormatting patternFormatting; private PatternFormatting patternFormatting;
@ -72,6 +72,10 @@ public class HSSFPatternFormatting
{ {
patternFormatting = new PatternFormatting(); patternFormatting = new PatternFormatting();
} }
protected HSSFPatternFormatting(PatternFormatting patternFormatting)
{
this.patternFormatting = patternFormatting;
}
protected PatternFormatting getPatternFormattingBlock() protected PatternFormatting getPatternFormattingBlock()
{ {

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,7 +15,6 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.util; package org.apache.poi.util;
import java.io.*; import java.io.*;
@ -25,6 +23,7 @@ import java.util.ArrayList;
/** /**
* Utilities to read hex from files. * Utilities to read hex from files.
* TODO - move to test packages
* *
* @author Marc Johnson * @author Marc Johnson
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
@ -62,10 +61,8 @@ public class HexRead
* *
* @see #readData(String) * @see #readData(String)
*/ */
public static byte[] readData( String filename, String section ) throws IOException public static byte[] readData(InputStream stream, String section ) throws IOException {
{
File file = new File( filename );
FileInputStream stream = new FileInputStream( file );
try try
{ {
StringBuffer sectionText = new StringBuffer(); StringBuffer sectionText = new StringBuffer();
@ -100,6 +97,12 @@ public class HexRead
} }
throw new IOException( "Section '" + section + "' not found" ); throw new IOException( "Section '" + section + "' not found" );
} }
public static byte[] readData( String filename, String section ) throws IOException
{
File file = new File( filename );
FileInputStream stream = new FileInputStream( file );
return readData(stream, section);
}
static public byte[] readData( InputStream stream, int eofChar ) static public byte[] readData( InputStream stream, int eofChar )
throws IOException throws IOException

View File

@ -16,16 +16,16 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi; package org.apache.poi;
import junit.framework.TestCase; import java.io.ByteArrayInputStream;
import java.io.*; import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import junit.framework.TestCase;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Tests that POIDocument correctly loads and saves the common * Tests that POIDocument correctly loads and saves the common
@ -36,85 +36,73 @@ import org.apache.poi.poifs.filesystem.*;
* *
* @author Nick Burch (nick at torchbox dot com) * @author Nick Burch (nick at torchbox dot com)
*/ */
public class TestPOIDocumentMain extends TestCase { public final class TestPOIDocumentMain extends TestCase {
// The POI Documents to work on // The POI Documents to work on
private POIDocument doc; private POIDocument doc;
private POIDocument doc2; private POIDocument doc2;
// POIFS primed on the test (two different hssf) data
private POIFSFileSystem pfs;
private POIFSFileSystem pfs2;
/** /**
* Set things up, using a PowerPoint document and * Set things up, two spreadsheets for our testing
* a Word Document for our testing
*/ */
public void setUp() throws Exception { public void setUp() {
String dirnameHSSF = System.getProperty("HSSF.testdata.path");
String filenameHSSF = dirnameHSSF + "/DateFormats.xls";
String filenameHSSF2 = dirnameHSSF + "/StringFormulas.xls";
FileInputStream fisHSSF = new FileInputStream(filenameHSSF); doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
pfs = new POIFSFileSystem(fisHSSF); doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls");
doc = new HSSFWorkbook(pfs);
FileInputStream fisHSSF2 = new FileInputStream(filenameHSSF2);
pfs2 = new POIFSFileSystem(fisHSSF2);
doc2 = new HSSFWorkbook(pfs2);
} }
public void testReadProperties() throws Exception { public void testReadProperties() throws Exception {
// We should have both sets // We should have both sets
assertNotNull(doc.getDocumentSummaryInformation()); assertNotNull(doc.getDocumentSummaryInformation());
assertNotNull(doc.getSummaryInformation()); assertNotNull(doc.getSummaryInformation());
// Check they are as expected for the test doc // Check they are as expected for the test doc
assertEquals("Administrator", doc.getSummaryInformation().getAuthor()); assertEquals("Administrator", doc.getSummaryInformation().getAuthor());
assertEquals(0, doc.getDocumentSummaryInformation().getByteCount()); assertEquals(0, doc.getDocumentSummaryInformation().getByteCount());
} }
public void testReadProperties2() throws Exception { public void testReadProperties2() throws Exception {
// Check again on the word one // Check again on the word one
assertNotNull(doc2.getDocumentSummaryInformation()); assertNotNull(doc2.getDocumentSummaryInformation());
assertNotNull(doc2.getSummaryInformation()); assertNotNull(doc2.getSummaryInformation());
assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor()); assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
assertEquals(null, doc2.getSummaryInformation().getKeywords()); assertEquals(null, doc2.getSummaryInformation().getKeywords());
assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
} }
public void testWriteProperties() throws Exception { public void testWriteProperties() throws Exception {
// Just check we can write them back out into a filesystem // Just check we can write them back out into a filesystem
POIFSFileSystem outFS = new POIFSFileSystem(); POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties(); doc.readProperties();
doc.writeProperties(outFS); doc.writeProperties(outFS);
// Should now hold them // Should now hold them
assertNotNull( assertNotNull(
outFS.createDocumentInputStream("\005SummaryInformation") outFS.createDocumentInputStream("\005SummaryInformation")
); );
assertNotNull( assertNotNull(
outFS.createDocumentInputStream("\005DocumentSummaryInformation") outFS.createDocumentInputStream("\005DocumentSummaryInformation")
); );
} }
public void testWriteReadProperties() throws Exception { public void testWriteReadProperties() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Write them out // Write them out
POIFSFileSystem outFS = new POIFSFileSystem(); POIFSFileSystem outFS = new POIFSFileSystem();
doc.readProperties(); doc.readProperties();
doc.writeProperties(outFS); doc.writeProperties(outFS);
outFS.writeFilesystem(baos); outFS.writeFilesystem(baos);
// Create a new version // Create a new version
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
POIFSFileSystem inFS = new POIFSFileSystem(bais); POIFSFileSystem inFS = new POIFSFileSystem(bais);
// Check they're still there // Check they're still there
doc.filesystem = inFS; doc.filesystem = inFS;
doc.readProperties(); doc.readProperties();
// Delegate test // Delegate test
testReadProperties(); testReadProperties();
} }
} }

View File

@ -0,0 +1,175 @@
/* ====================================================================
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;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder.
*
* @author Josh Micich
*/
public final class HSSFTestDataSamples {
private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path";
private static boolean _isInitialised;
private static File _resolvedDataDir;
/** <code>true</code> if standard system propery is not set,
* but the data is available on the test runtime classpath */
private static boolean _sampleDataIsAvaliableOnClassPath;
/**
* Opens a sample file from the standard HSSF test data directory
*
* @return an open <tt>InputStream</tt> for the specified sample file
*/
public static InputStream openSampleFileStream(String sampleFileName) {
if(!_isInitialised) {
try {
initialise();
} finally {
_isInitialised = true;
}
}
if (_sampleDataIsAvaliableOnClassPath) {
InputStream result = openClasspathResource(sampleFileName);
if(result == null) {
throw new RuntimeException("specified test sample file '" + sampleFileName
+ "' not found on the classpath");
}
// System.out.println("opening cp: " + sampleFileName);
// wrap to avoid temp warning method about auto-closing input stream
return new NonSeekableInputStream(result);
}
if (_resolvedDataDir == null) {
throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' properly before running tests");
}
File f = new File(_resolvedDataDir, sampleFileName);
if (!f.exists()) {
throw new RuntimeException("Sample file '" + sampleFileName
+ "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'");
}
// System.out.println("opening " + f.getAbsolutePath());
try {
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private static void initialise() {
String dataDirName = System.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME);
if (dataDirName == null) {
// check to see if we can just get the resources from the classpath
InputStream is = openClasspathResource("SampleSS.xls");
if(is != null) {
try {
is.close(); // be nice
} catch (IOException e) {
throw new RuntimeException(e);
}
_sampleDataIsAvaliableOnClassPath = true;
return;
}
throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' before running tests");
}
File dataDir = new File(dataDirName);
if (!dataDir.exists()) {
throw new RuntimeException("Data dir '" + dataDirName
+ "' specified by system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist");
}
// convert to canonical file, to make any subsequent error messages clearer.
try {
_resolvedDataDir = dataDir.getCanonicalFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Opens a test sample file from the 'data' sub-package of this class's package.
* @return <code>null</code> if the sample file is not deployed on the classpath.
*/
private static InputStream openClasspathResource(String sampleFileName) {
return HSSFTestDataSamples.class.getResourceAsStream("data/" + sampleFileName);
}
private static final class NonSeekableInputStream extends InputStream {
private final InputStream _is;
public NonSeekableInputStream(InputStream is) {
_is = is;
}
public int read() throws IOException {
return _is.read();
}
public int read(byte[] b, int off, int len) throws IOException {
return _is.read(b, off, len);
}
public boolean markSupported() {
return false;
}
public void close() throws IOException {
_is.close();
}
}
public static HSSFWorkbook openSampleWorkbook(String sampleFileName) {
try {
return new HSSFWorkbook(openSampleFileStream(sampleFileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Writes a spreadsheet to a <tt>ByteArrayOutputStream</tt> and reads it back
* from a <tt>ByteArrayInputStream</tt>.<p/>
* Useful for verifying that the serialisation round trip
*/
public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
original.write(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new HSSFWorkbook(bais);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -16,109 +16,108 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.eventusermodel; package org.apache.poi.hssf.eventusermodel;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; import java.io.InputStream;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.DVALRecord; import org.apache.poi.hssf.record.DVALRecord;
import org.apache.poi.hssf.record.DVRecord; import org.apache.poi.hssf.record.DVRecord;
import org.apache.poi.hssf.record.EOFRecord; import org.apache.poi.hssf.record.EOFRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.SelectionRecord; import org.apache.poi.hssf.record.SelectionRecord;
import org.apache.poi.hssf.record.WindowTwoRecord; import org.apache.poi.hssf.record.WindowTwoRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
*/
public final class TestHSSFEventFactory extends TestCase {
import junit.framework.TestCase; private static final InputStream openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
public class TestHSSFEventFactory extends TestCase {
private String dirname;
public TestHSSFEventFactory() {
dirname = System.getProperty("HSSF.testdata.path");
} }
public void testWithMissingRecords() throws Exception { public void testWithMissingRecords() throws Exception {
File f = new File(dirname + "/SimpleWithSkip.xls");
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen); req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); POIFSFileSystem fs = new POIFSFileSystem(openSample("SimpleWithSkip.xls"));
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
Record[] recs = mockListen.getRecords();
// Check we got the records // Check we got the records
System.out.println("Processed, found " + mockListen.records.size() + " records"); assertTrue( recs.length > 100 );
assertTrue( mockListen.records.size() > 100 );
// Check that the last few records are as we expect // Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones) // (Makes sure we don't accidently skip the end ones)
int numRec = mockListen.records.size(); int numRec = recs.length;
assertEquals(WindowTwoRecord.class, mockListen.records.get(numRec-3).getClass()); assertEquals(WindowTwoRecord.class, recs[numRec-3].getClass());
assertEquals(SelectionRecord.class, mockListen.records.get(numRec-2).getClass()); assertEquals(SelectionRecord.class, recs[numRec-2].getClass());
assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass()); assertEquals(EOFRecord.class, recs[numRec-1].getClass());
} }
public void testWithCrazyContinueRecords() throws Exception { public void testWithCrazyContinueRecords() throws Exception {
// Some files have crazy ordering of their continue records // Some files have crazy ordering of their continue records
// Check that we don't break on them (bug #42844) // Check that we don't break on them (bug #42844)
File f = new File(dirname + "/ContinueRecordProblem.xls"); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(openSample("ContinueRecordProblem.xls"));
HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs);
Record[] recs = mockListen.getRecords();
// Check we got the records
assertTrue( recs.length > 100 );
// And none of them are continue ones
for(int i=0; i<recs.length; i++) {
assertFalse( recs[i] instanceof ContinueRecord );
}
// Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones)
int numRec = recs.length;
assertEquals(DVALRecord.class, recs[numRec-3].getClass());
assertEquals(DVRecord.class, recs[numRec-2].getClass());
assertEquals(EOFRecord.class, recs[numRec-1].getClass());
}
/**
* Unknown records can be continued.
* Check that HSSFEventFactory doesn't break on them.
* (the test file was provided in a reopen of bug #42844)
*/
public void testUnknownContinueRecords() throws Exception {
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen); req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); POIFSFileSystem fs = new POIFSFileSystem(openSample("42844.xls"));
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
// Check we got the records assertTrue("no errors while processing the file", true);
System.out.println("Processed, found " + mockListen.records.size() + " records");
assertTrue( mockListen.records.size() > 100 );
// And none of them are continue ones
Record[] r = (Record[])mockListen.records.toArray(
new Record[mockListen.records.size()] );
for(int i=0; i<r.length; i++) {
assertFalse( r[i] instanceof ContinueRecord );
}
// Check that the last few records are as we expect
// (Makes sure we don't accidently skip the end ones)
int numRec = mockListen.records.size();
assertEquals(DVALRecord.class, mockListen.records.get(numRec-3).getClass());
assertEquals(DVRecord.class, mockListen.records.get(numRec-2).getClass());
assertEquals(EOFRecord.class, mockListen.records.get(numRec-1).getClass());
} }
/**
* Unknown records can be continued.
* Check that HSSFEventFactory doesn't break on them.
* (the test file was provided in a reopen of bug #42844)
*/
public void testUnknownContinueRecords() throws Exception {
File f = new File(dirname + "/42844.xls");
HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener();
req.addListenerForAllRecords(mockListen);
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f));
HSSFEventFactory factory = new HSSFEventFactory();
factory.processWorkbookEvents(req, fs);
assertTrue("no errors while processing the file", true);
}
private static class MockHSSFListener implements HSSFListener { private static class MockHSSFListener implements HSSFListener {
private MockHSSFListener() {} private final List records = new ArrayList();
private ArrayList records = new ArrayList();
public MockHSSFListener() {}
public Record[] getRecords() {
Record[] result = new Record[records.size()];
records.toArray(result);
return result;
}
public void processRecord(Record record) { public void processRecord(Record record) {
records.add(record); records.add(record);

View File

@ -19,11 +19,13 @@ package org.apache.poi.hssf.eventusermodel;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord;
@ -39,8 +41,6 @@ public final class TestMissingRecordAwareHSSFListener extends TestCase {
private Record[] r; private Record[] r;
public void setUp() { public void setUp() {
String dirname = System.getProperty("HSSF.testdata.path");
File f = new File(dirname + "/MissingBits.xls");
HSSFRequest req = new HSSFRequest(); HSSFRequest req = new HSSFRequest();
MockHSSFListener mockListen = new MockHSSFListener(); MockHSSFListener mockListen = new MockHSSFListener();
@ -49,7 +49,8 @@ public final class TestMissingRecordAwareHSSFListener extends TestCase {
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
try { try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(f)); InputStream is = HSSFTestDataSamples.openSampleFileStream("MissingBits.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
factory.processWorkbookEvents(req, fs); factory.processWorkbookEvents(req, fs);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -14,21 +14,36 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.extractor; package org.apache.poi.hssf.extractor;
import java.io.File; import java.io.IOException;
import java.io.FileInputStream; import java.io.InputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestExcelExtractor extends TestCase { import org.apache.poi.hssf.HSSFTestDataSamples;
public void testSimple() throws Exception { import org.apache.poi.poifs.filesystem.POIFSFileSystem;
String path = System.getProperty("HSSF.testdata.path"); /**
FileInputStream fin = new FileInputStream(path + File.separator + "Simple.xls"); *
*/
public final class TestExcelExtractor extends TestCase {
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); private static final ExcelExtractor createExtractor(String sampleFileName) {
InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
try {
return new ExcelExtractor(new POIFSFileSystem(is));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void testSimple() {
ExcelExtractor extractor = createExtractor("Simple.xls");
assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText()); assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText());
@ -37,11 +52,9 @@ public class TestExcelExtractor extends TestCase {
assertEquals("replaceMe\n", extractor.getText()); assertEquals("replaceMe\n", extractor.getText());
} }
public void testNumericFormula() throws Exception { public void testNumericFormula() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "sumifformula.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("sumifformula.xls");
assertEquals( assertEquals(
"Sheet1\n" + "Sheet1\n" +
@ -68,11 +81,9 @@ public class TestExcelExtractor extends TestCase {
); );
} }
public void testwithContinueRecords() throws Exception { public void testwithContinueRecords() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "StringContinueRecords.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("StringContinueRecords.xls");
extractor.getText(); extractor.getText();
@ -82,11 +93,9 @@ public class TestExcelExtractor extends TestCase {
assertTrue(extractor.getText().length() > 40960); assertTrue(extractor.getText().length() > 40960);
} }
public void testStringConcat() throws Exception { public void testStringConcat() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "SimpleWithFormula.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls");
// Comes out as NaN if treated as a number // Comes out as NaN if treated as a number
// And as XYZ if treated as a string // And as XYZ if treated as a string
@ -97,11 +106,9 @@ public class TestExcelExtractor extends TestCase {
assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText()); assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText());
} }
public void testStringFormula() throws Exception { public void testStringFormula() {
String path = System.getProperty("HSSF.testdata.path");
FileInputStream fin = new FileInputStream(path + File.separator + "StringFormulas.xls");
ExcelExtractor extractor = new ExcelExtractor(new POIFSFileSystem(fin)); ExcelExtractor extractor = createExtractor("StringFormulas.xls");
// Comes out as NaN if treated as a number // Comes out as NaN if treated as a number
// And as XYZ if treated as a string // And as XYZ if treated as a string

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,35 +15,27 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.File; import java.io.InputStream;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestBOFRecord extends TestCase import org.apache.poi.hssf.HSSFTestDataSamples;
{ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
private String _test_file_path; /**
private static final String _test_file_path_property = "HSSF.testdata.path"; *
*/
public TestBOFRecord() public final class TestBOFRecord extends TestCase {
{
super();
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "bug_42794.xls";
}
public void testBOFRecord() throws Exception { public void testBOFRecord() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem( InputStream is = HSSFTestDataSamples.openSampleFileStream("bug_42794.xls");
new FileInputStream(_test_file_path)
);
// This used to throw an error before // This used to throw an error before
HSSFWorkbook hssf = new HSSFWorkbook(fs); try {
new HSSFWorkbook(is);
} catch (ArrayIndexOutOfBoundsException e) {
throw new AssertionFailedError("Identified bug 42794");
}
} }
} }

View File

@ -182,14 +182,13 @@ public final class TestCFRuleRecord extends TestCase
// Check for defaults // Check for defaults
assertFalse(fontFormatting.isEscapementTypeModified()); assertFalse(fontFormatting.isEscapementTypeModified());
assertFalse(fontFormatting.isFontCancellationModified()); assertFalse(fontFormatting.isFontCancellationModified());
assertFalse(fontFormatting.isFontCondenseModified());
assertFalse(fontFormatting.isFontOutlineModified()); assertFalse(fontFormatting.isFontOutlineModified());
assertFalse(fontFormatting.isFontShadowModified()); assertFalse(fontFormatting.isFontShadowModified());
assertFalse(fontFormatting.isFontStyleModified()); assertFalse(fontFormatting.isFontStyleModified());
assertFalse(fontFormatting.isUnderlineTypeModified()); assertFalse(fontFormatting.isUnderlineTypeModified());
assertFalse(fontFormatting.isFontWeightModified());
assertFalse(fontFormatting.isBold()); assertFalse(fontFormatting.isBold());
assertFalse(fontFormatting.isCondenseOn());
assertFalse(fontFormatting.isItalic()); assertFalse(fontFormatting.isItalic());
assertFalse(fontFormatting.isOutlineOn()); assertFalse(fontFormatting.isOutlineOn());
assertFalse(fontFormatting.isShadowOn()); assertFalse(fontFormatting.isShadowOn());
@ -198,7 +197,7 @@ public final class TestCFRuleRecord extends TestCase
assertEquals(0, fontFormatting.getEscapementType()); assertEquals(0, fontFormatting.getEscapementType());
assertEquals(-1, fontFormatting.getFontColorIndex()); assertEquals(-1, fontFormatting.getFontColorIndex());
assertEquals(-1, fontFormatting.getFontHeight()); assertEquals(-1, fontFormatting.getFontHeight());
assertEquals(400, fontFormatting.getFontWeight()); assertEquals(0, fontFormatting.getFontWeight());
assertEquals(0, fontFormatting.getUnderlineType()); assertEquals(0, fontFormatting.getUnderlineType());
fontFormatting.setBold(true); fontFormatting.setBold(true);
@ -206,11 +205,6 @@ public final class TestCFRuleRecord extends TestCase
fontFormatting.setBold(false); fontFormatting.setBold(false);
assertFalse(fontFormatting.isBold()); assertFalse(fontFormatting.isBold());
fontFormatting.setCondense(true);
assertTrue(fontFormatting.isCondenseOn());
fontFormatting.setCondense(false);
assertFalse(fontFormatting.isCondenseOn());
fontFormatting.setEscapementType(FontFormatting.SS_SUB); fontFormatting.setEscapementType(FontFormatting.SS_SUB);
assertEquals(FontFormatting.SS_SUB, fontFormatting.getEscapementType()); assertEquals(FontFormatting.SS_SUB, fontFormatting.getEscapementType());
fontFormatting.setEscapementType(FontFormatting.SS_SUPER); fontFormatting.setEscapementType(FontFormatting.SS_SUPER);
@ -223,6 +217,11 @@ public final class TestCFRuleRecord extends TestCase
fontFormatting.setEscapementTypeModified(true); fontFormatting.setEscapementTypeModified(true);
assertTrue(fontFormatting.isEscapementTypeModified()); assertTrue(fontFormatting.isEscapementTypeModified());
fontFormatting.setFontWieghtModified(false);
assertFalse(fontFormatting.isFontWeightModified());
fontFormatting.setFontWieghtModified(true);
assertTrue(fontFormatting.isFontWeightModified());
fontFormatting.setFontCancellationModified(false); fontFormatting.setFontCancellationModified(false);
assertFalse(fontFormatting.isFontCancellationModified()); assertFalse(fontFormatting.isFontCancellationModified());
fontFormatting.setFontCancellationModified(true); fontFormatting.setFontCancellationModified(true);
@ -231,11 +230,6 @@ public final class TestCFRuleRecord extends TestCase
fontFormatting.setFontColorIndex((short)10); fontFormatting.setFontColorIndex((short)10);
assertEquals(10,fontFormatting.getFontColorIndex()); assertEquals(10,fontFormatting.getFontColorIndex());
fontFormatting.setFontCondenseModified(false);
assertFalse(fontFormatting.isFontCondenseModified());
fontFormatting.setFontCondenseModified(true);
assertTrue(fontFormatting.isFontCondenseModified());
fontFormatting.setFontHeight((short)100); fontFormatting.setFontHeight((short)100);
assertEquals(100,fontFormatting.getFontHeight()); assertEquals(100,fontFormatting.getFontHeight());

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,64 +15,56 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestChartTitleFormatRecord extends TestCase import org.apache.poi.hssf.HSSFTestDataSamples;
{ import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
private String _test_file_path; import org.apache.poi.hssf.eventusermodel.HSSFListener;
private static final String _test_file_path_property = "HSSF.testdata.path"; import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
*/
public final class TestChartTitleFormatRecord extends TestCase {
public TestChartTitleFormatRecord() public void testRecord() throws Exception {
{ POIFSFileSystem fs = new POIFSFileSystem(
super(); HSSFTestDataSamples.openSampleFileStream("WithFormattedGraphTitle.xls"));
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "WithFormattedGraphTitle.xls";
}
public void testRecord() throws Exception { // Check we can open the file via usermodel
POIFSFileSystem fs = new POIFSFileSystem( HSSFWorkbook hssf = new HSSFWorkbook(fs);
new FileInputStream(_test_file_path)
);
// Check we can open the file via usermodel // Now process it through eventusermodel, and
HSSFWorkbook hssf = new HSSFWorkbook(fs); // look out for the title records
ChartTitleFormatRecordGrabber grabber = new ChartTitleFormatRecordGrabber();
InputStream din = fs.createDocumentInputStream("Workbook");
HSSFRequest req = new HSSFRequest();
req.addListenerForAllRecords(grabber);
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
din.close();
// Now process it through eventusermodel, and // Should've found one
// look out for the title records assertEquals(1, grabber.chartTitleFormatRecords.size());
ChartTitleFormatRecordGrabber grabber = // And it should be of something interesting
new ChartTitleFormatRecordGrabber(); ChartTitleFormatRecord r =
InputStream din = fs.createDocumentInputStream("Workbook"); (ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0);
HSSFRequest req = new HSSFRequest(); assertEquals(3, r.getFormatCount());
req.addListenerForAllRecords(grabber); }
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
din.close();
// Should've found one private static final class ChartTitleFormatRecordGrabber implements HSSFListener {
assertEquals(1, grabber.chartTitleFormatRecords.size()); private final List chartTitleFormatRecords;
// And it should be of something interesting
ChartTitleFormatRecord r =
(ChartTitleFormatRecord)grabber.chartTitleFormatRecords.get(0);
assertEquals(3, r.getFormatCount());
}
public static class ChartTitleFormatRecordGrabber implements HSSFListener { public ChartTitleFormatRecordGrabber() {
private ArrayList chartTitleFormatRecords = new ArrayList(); chartTitleFormatRecords = new ArrayList();
}
public void processRecord(Record record) { public void processRecord(Record record) {
if(record instanceof ChartTitleFormatRecord) { if(record instanceof ChartTitleFormatRecord) {
@ -83,5 +74,5 @@ public class TestChartTitleFormatRecord extends TestCase
} }
} }
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,8 +15,6 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
@ -39,36 +36,29 @@ import junit.framework.TestCase;
* *
* @author Andrew C. Oliver * @author Andrew C. Oliver
*/ */
public class TestFormulaRecord public final class TestFormulaRecord extends TestCase {
extends TestCase
{
public TestFormulaRecord(String name) public void testCreateFormulaRecord () {
{ FormulaRecord record = new FormulaRecord();
super(name); record.setColumn((short)0);
} //record.setRow((short)1);
record.setRow(1);
record.setXFIndex((short)4);
public void testCreateFormulaRecord () { assertEquals(record.getColumn(),(short)0);
FormulaRecord record = new FormulaRecord(); //assertEquals(record.getRow(),(short)1);
record.setColumn((short)0); assertEquals((short)record.getRow(),(short)1);
//record.setRow((short)1); assertEquals(record.getXFIndex(),(short)4);
record.setRow(1); }
record.setXFIndex((short)4);
assertEquals(record.getColumn(),(short)0); /**
//assertEquals(record.getRow(),(short)1); * Make sure a NAN value is preserved
assertEquals((short)record.getRow(),(short)1); * This formula record is a representation of =1/0 at row 0, column 0
assertEquals(record.getXFIndex(),(short)4); */
} public void testCheckNanPreserve() {
byte[] formulaByte = new byte[29];
/** for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
* Make sure a NAN value is preserved formulaByte[4] = (byte)0x0F;
* This formula record is a representation of =1/0 at row 0, column 0
*/
public void testCheckNanPreserve() {
byte[] formulaByte = new byte[29];
for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
formulaByte[4] = (byte)0x0F;
formulaByte[6] = (byte)0x02; formulaByte[6] = (byte)0x02;
formulaByte[8] = (byte)0x07; formulaByte[8] = (byte)0x07;
formulaByte[12] = (byte)0xFF; formulaByte[12] = (byte)0xFF;
@ -92,19 +82,18 @@ public class TestFormulaRecord
for (int i = 5; i < 13;i++) { for (int i = 5; i < 13;i++) {
assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]); assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]);
} }
}
} /**
* Tests to see if the shared formula cells properly reserialize the expPtg
/** *
* Tests to see if the shared formula cells properly reserialize the expPtg */
* public void testExpFormula() {
*/ byte[] formulaByte = new byte[27];
public void testExpFormula() {
byte[] formulaByte = new byte[27];
for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0; for (int i = 0; i < formulaByte.length; i++) formulaByte[i] = (byte)0;
formulaByte[4] =(byte)0x0F; formulaByte[4] =(byte)0x0F;
formulaByte[14]=(byte)0x08; formulaByte[14]=(byte)0x08;
formulaByte[18]=(byte)0xE0; formulaByte[18]=(byte)0xE0;
formulaByte[19]=(byte)0xFD; formulaByte[19]=(byte)0xFD;
@ -115,19 +104,19 @@ public class TestFormulaRecord
assertEquals("Column", 0, record.getColumn()); assertEquals("Column", 0, record.getColumn());
byte[] output = record.serialize(); byte[] output = record.serialize();
assertEquals("Output size", 31, output.length); //includes sid+recordlength assertEquals("Output size", 31, output.length); //includes sid+recordlength
assertEquals("Offset 22", 1, output[26]); assertEquals("Offset 22", 1, output[26]);
} }
public void testWithConcat() throws Exception { public void testWithConcat() throws Exception {
// =CHOOSE(2,A2,A3,A4) // =CHOOSE(2,A2,A3,A4)
byte[] data = new byte[] { byte[] data = new byte[] {
6, 0, 68, 0, 6, 0, 68, 0,
1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57, 1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57,
64, 0, 0, 12, 0, 12, -4, 46, 0, 64, 0, 0, 12, 0, 12, -4, 46, 0,
30, 2, 0, // Int - 2 30, 2, 0, // Int - 2
25, 4, 3, 0, // Attr 25, 4, 3, 0, // Attr
8, 0, // Concat 8, 0, // Concat
17, 0, // Range 17, 0, // Range
26, 0, 35, 0, // Bit like an attr 26, 0, 35, 0, // Bit like an attr
36, 1, 0, 0, -64, // Ref - A2 36, 1, 0, 0, -64, // Ref - A2
25, 8, 21, 0, // Attr 25, 8, 21, 0, // Attr
@ -136,43 +125,35 @@ public class TestFormulaRecord
36, 3, 0, 0, -64, // Ref - A4 36, 3, 0, 0, -64, // Ref - A4
25, 8, 3, 0, // Attr 25, 8, 3, 0, // Attr
66, 4, 100, 0 // CHOOSE 66, 4, 100, 0 // CHOOSE
}; };
RecordInputStream inp = new RecordInputStream( RecordInputStream inp = new RecordInputStream(
new ByteArrayInputStream(data) new ByteArrayInputStream(data)
); );
inp.nextRecord(); inp.nextRecord();
FormulaRecord fr = new FormulaRecord(inp); FormulaRecord fr = new FormulaRecord(inp);
assertEquals(14, fr.getNumberOfExpressionTokens()); assertEquals(14, fr.getNumberOfExpressionTokens());
assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass()); assertEquals(IntPtg.class, fr.getParsedExpression().get(0).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(1).getClass());
assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass()); assertEquals(ConcatPtg.class, fr.getParsedExpression().get(2).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass()); assertEquals(UnknownPtg.class, fr.getParsedExpression().get(3).getClass());
assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass()); assertEquals(RangePtg.class, fr.getParsedExpression().get(4).getClass());
assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass()); assertEquals(UnknownPtg.class, fr.getParsedExpression().get(5).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(6).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass()); assertEquals(ReferencePtg.class, fr.getParsedExpression().get(7).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(8).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass()); assertEquals(ReferencePtg.class, fr.getParsedExpression().get(9).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(10).getClass());
assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass()); assertEquals(ReferencePtg.class, fr.getParsedExpression().get(11).getClass());
assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass()); assertEquals(AttrPtg.class, fr.getParsedExpression().get(12).getClass());
assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass()); assertEquals(FuncVarPtg.class, fr.getParsedExpression().get(13).getClass());
FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13);
assertEquals("CHOOSE", choose.getName());
}
public static void main(String [] ignored_args)
{
String filename = System.getProperty("HSSF.testdata.path");
System.out
.println("Testing org.apache.poi.hssf.record.FormulaRecord");
junit.textui.TestRunner.run(TestFormulaRecord.class);
}
FuncVarPtg choose = (FuncVarPtg)fr.getParsedExpression().get(13);
assertEquals("CHOOSE", choose.getName());
}
public static void main(String [] ignored_args) {
junit.textui.TestRunner.run(TestFormulaRecord.class);
}
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,7 +15,6 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -34,20 +32,8 @@ import org.apache.poi.util.HexRead;
* @author Andrew C. Oliver (acoliver at apache dot org) * @author Andrew C. Oliver (acoliver at apache dot org)
* @author Csaba Nagy (ncsaba at yahoo dot com) * @author Csaba Nagy (ncsaba at yahoo dot com)
*/ */
public final class TestRecordFactory extends TestCase {
public class TestRecordFactory
extends TestCase
{
/**
* Creates new TestRecordFactory
* @param testCaseName
*/
public TestRecordFactory(String testCaseName)
{
super(testCaseName);
}
/** /**
* TEST NAME: Test Basic Record Construction <P> * TEST NAME: Test Basic Record Construction <P>
@ -57,13 +43,9 @@ public class TestRecordFactory
* FAILURE: The wrong records are creates or contain the wrong values <P> * FAILURE: The wrong records are creates or contain the wrong values <P>
* *
*/ */
public void testBasicRecordConstruction() {
public void testBasicRecordConstruction()
throws Exception
{
short recType = BOFRecord.sid; short recType = BOFRecord.sid;
byte[] data = new byte[] byte[] data = {
{
0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0 0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0
}; };
short size = 16; short size = 16;
@ -106,13 +88,9 @@ public class TestRecordFactory
* FAILURE: The wrong records are created or contain the wrong values <P> * FAILURE: The wrong records are created or contain the wrong values <P>
* *
*/ */
public void testSpecial() {
public void testSpecial()
throws Exception
{
short recType = RKRecord.sid; short recType = RKRecord.sid;
byte[] data = new byte[] byte[] data = {
{
0, 0, 0, 0, 21, 0, 0, 0, 0, 0 0, 0, 0, 0, 21, 0, 0, 0, 0, 0
}; };
short size = 10; short size = 10;
@ -138,10 +116,8 @@ public class TestRecordFactory
* FAILURE: The wrong records are created or contain the wrong values <P> * FAILURE: The wrong records are created or contain the wrong values <P>
* *
*/ */
public void testContinuedUnknownRecord() public void testContinuedUnknownRecord() {
{ byte[] data = {
byte[] data = new byte[]
{
0, -1, 0, 0, // an unknown record with 0 length 0, -1, 0, 0, // an unknown record with 0 length
0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data 0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data
0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data 0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data
@ -178,7 +154,7 @@ public class TestRecordFactory
*/ */
public void testMixedContinue() throws Exception { public void testMixedContinue() throws Exception {
/** /**
* Taken from a real file $HSSF.testdata.path/39512.xls. See Bug 39512 for details. * Taken from a real test sample file 39512.xls. See Bug 39512 for details.
*/ */
String dump = String dump =
//OBJ //OBJ
@ -228,10 +204,7 @@ public class TestRecordFactory
assertTrue(Arrays.equals(data, ser)); assertTrue(Arrays.equals(data, ser));
} }
public static void main(String [] ignored_args) public static void main(String [] ignored_args) {
{
System.out
.println("Testing org.apache.poi.hssf.record.TestRecordFactory");
junit.textui.TestRunner.run(TestRecordFactory.class); junit.textui.TestRunner.run(TestRecordFactory.class);
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,50 +15,46 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import org.apache.poi.util.HexRead; import java.io.IOException;
import org.apache.poi.util.IntMapper; import java.io.InputStream;
import org.apache.poi.hssf.record.TestcaseRecordInputStream;
import java.io.File;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.IntMapper;
/** /**
* Exercise the SSTDeserializer class. * Exercise the SSTDeserializer class.
* *
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public class TestSSTDeserializer public final class TestSSTDeserializer extends TestCase {
extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
public TestSSTDeserializer( String s )
{
super( s );
}
protected void setUp() throws Exception
{
_test_file_path = System.getProperty( _test_file_path_property );
}
private byte[] joinArray(byte[] array1, byte[] array2) { private byte[] joinArray(byte[] array1, byte[] array2) {
byte[] bigArray = new byte[array1.length+array2.length]; byte[] bigArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, bigArray, 0, array1.length); System.arraycopy(array1, 0, bigArray, 0, array1.length);
System.arraycopy(array2, 0, bigArray, array1.length, array2.length); System.arraycopy(array2, 0, bigArray, array1.length, array2.length);
return bigArray; return bigArray;
}
private static byte[] readSampleHexData(String sampleFileName, String sectionName) {
InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
try {
return HexRead.readData(is, sectionName);
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
public void testSpanRichTextToPlainText() public void testSpanRichTextToPlainText()
throws Exception throws Exception
{ {
byte[] header = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "header" ); byte[] header = readSampleHexData("richtextdata.txt", "header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "richtextdata.txt", "continue1" ); byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -74,8 +69,8 @@ public class TestSSTDeserializer
public void testContinuationWithNoOverlap() public void testContinuationWithNoOverlap()
throws Exception throws Exception
{ {
byte[] header = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "header" ); byte[] header = readSampleHexData("evencontinuation.txt", "header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "evencontinuation.txt", "continue1" ); byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -93,10 +88,10 @@ public class TestSSTDeserializer
public void testStringAcross2Continuations() public void testStringAcross2Continuations()
throws Exception throws Exception
{ {
byte[] header = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "header" ); byte[] header = readSampleHexData("stringacross2continuations.txt", "header" );
byte[] continue1 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue1" ); byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "continue1" );
continue1 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue1.length, continue1); continue1 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue1.length, continue1);
byte[] continue2 = HexRead.readData( _test_file_path + File.separator + "stringacross2continuations.txt", "continue2" ); byte[] continue2 = readSampleHexData("stringacross2continuations.txt", "continue2" );
continue2 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue2.length, continue2); continue2 = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continue2.length, continue2);
byte[] bytes = joinArray(header, continue1); byte[] bytes = joinArray(header, continue1);
@ -111,11 +106,9 @@ public class TestSSTDeserializer
assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" ); assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" );
} }
public void testExtendedStrings() public void testExtendedStrings() {
throws Exception byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header" );
{ byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1" );
byte[] header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "rich-header" );
byte[] continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "rich-continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); TestcaseRecordInputStream in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -126,8 +119,8 @@ public class TestSSTDeserializer
assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
header = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-header" ); header = readSampleHexData("extendedtextstrings.txt", "norich-header" );
continueBytes = HexRead.readData( _test_file_path + File.separator + "extendedtextstrings.txt", "norich-continue1" ); continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1" );
continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes); continueBytes = TestcaseRecordInputStream.mergeDataAndSid(ContinueRecord.sid, (short)continueBytes.length, continueBytes);
in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes)); in = new TestcaseRecordInputStream((short)0, (short)header.length, joinArray(header, continueBytes));
@ -136,7 +129,5 @@ public class TestSSTDeserializer
deserializer.manufactureStrings( 1, in); deserializer.manufactureStrings( 1, in);
assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,53 +15,32 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import junit.framework.TestCase; import java.io.ByteArrayInputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet; import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.IOException;
import org.apache.poi.util.HexRead;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.TempFile;
import java.io.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.LittleEndian;
/** /**
* @author Marc Johnson (mjohnson at apache dot org) * @author Marc Johnson (mjohnson at apache dot org)
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public class TestSSTRecord public final class TestSSTRecord extends TestCase {
extends TestCase
{
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
/**
* Creates new TestSSTRecord
*
* @param name
*/
public TestSSTRecord( String name )
{
super( name );
_test_file_path = System.getProperty( _test_file_path_property );
}
/** /**
* test processContinueRecord * test processContinueRecord
*
* @exception IOException
*/ */
public void testProcessContinueRecord() {
public void testProcessContinueRecord()
throws IOException
{
//jmh byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" ); //jmh byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" );
//jmh byte[] input = new byte[testdata.length - 4]; //jmh byte[] input = new byte[testdata.length - 4];
//jmh //jmh
@ -182,9 +160,7 @@ public class TestSSTRecord
* @exception IOException * @exception IOException
*/ */
public void testHugeStrings() public void testHugeStrings() {
throws IOException
{
SSTRecord record = new SSTRecord(); SSTRecord record = new SSTRecord();
byte[][] bstrings = byte[][] bstrings =
{ {
@ -265,12 +241,8 @@ public class TestSSTRecord
/** /**
* test SSTRecord boundary conditions * test SSTRecord boundary conditions
*
* @exception IOException
*/ */
public void testSSTRecordBug() public void testSSTRecordBug() {
throws IOException
{
// create an SSTRecord and write a certain pattern of strings // create an SSTRecord and write a certain pattern of strings
// to it ... then serialize it and verify the content // to it ... then serialize it and verify the content
SSTRecord record = new SSTRecord(); SSTRecord record = new SSTRecord();
@ -349,38 +321,6 @@ public class TestSSTRecord
} }
} }
/**
* test reader constructor
*
* @exception IOException
*/
public void testReaderConstructor()
throws IOException
{
/* JMH this test case data is crap because it does not contain a full record. Ie the last string
is missing a record
byte[] testdata = HexRead.readData( _test_file_path + File.separator + "BigSSTRecord" );
// byte[] input = new byte[testdata.length - 4];
System.arraycopy( testdata, 4, input, 0, input.length );
SSTRecord record = new SSTRecord( new TestcaseRecordInputStream(LittleEndian.getShort( testdata, 0 ),
LittleEndian.getShort( testdata, 2 ),
input) );
assertEquals( 1464, record.getNumStrings() );
assertEquals( 688, record.getNumUniqueStrings() );
assertEquals( 492, record.countStrings() );
assertEquals( 1, record.getDeserializer().getContinuationExpectedChars() );
assertEquals( "Consolidated B-24J Liberator The Dragon & His Tai",
record.getDeserializer().getUnfinishedString() );
// assertEquals( 52, record.getDeserializer().getTotalLength() );
// assertEquals( 3, record.getDeserializer().getStringDataOffset() );
assertTrue( !record.getDeserializer().isWideChar() );
*/
}
/** /**
* test simple constructor * test simple constructor
*/ */
@ -413,9 +353,7 @@ public class TestSSTRecord
* @param ignored_args * @param ignored_args
*/ */
public static void main( String[] ignored_args ) public static void main( String[] ignored_args ) {
{
System.out.println( "Testing hssf.record.SSTRecord functionality" );
junit.textui.TestRunner.run( TestSSTRecord.class ); junit.textui.TestRunner.run( TestSSTRecord.class );
} }
@ -425,25 +363,16 @@ public class TestSSTRecord
public void testReadWriteDuplicatedRichText1() public void testReadWriteDuplicatedRichText1()
throws Exception throws Exception
{ {
File file = new File( _test_file_path + File.separator + "duprich1.xls" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls");
InputStream stream = new FileInputStream( file );
HSSFWorkbook wb = new HSSFWorkbook( stream );
stream.close();
HSSFSheet sheet = wb.getSheetAt( 1 ); HSSFSheet sheet = wb.getSheetAt( 1 );
assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell( (short) 8 ).getStringCellValue() ); assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell( (short) 8 ).getStringCellValue() );
assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell( (short) 8 ).getStringCellValue() ); assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell( (short) 8 ).getStringCellValue() );
file = TempFile.createTempFile( "testout", "xls" ); ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream outStream = new FileOutputStream( file ); wb.write( baos );
wb.write( outStream );
outStream.close();
file.delete();
// test the second file. // test the second file.
file = new File( _test_file_path + File.separator + "duprich2.xls" ); wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls");
stream = new FileInputStream( file );
wb = new HSSFWorkbook( stream );
stream.close();
sheet = wb.getSheetAt( 0 ); sheet = wb.getSheetAt( 0 );
int row = 0; int row = 0;
assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() );
@ -453,12 +382,6 @@ public class TestSSTRecord
assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() );
assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() ); assertEquals( "Testing", sheet.getRow( row++ ).getCell( (short) 0 ).getStringCellValue() );
// file = new File("/tryme.xls"); wb.write( baos );
file = TempFile.createTempFile( "testout", ".xls" );
outStream = new FileOutputStream( file );
wb.write( outStream );
outStream.close();
file.delete();
} }
} }

View File

@ -15,38 +15,22 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.record; package org.apache.poi.hssf.record;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; /**
*
*/
public final class TestUnicodeNameRecord extends TestCase {
public class TestUnicodeNameRecord extends TestCase { public void testReadBook() {
private String _test_file_path;
private static final String _test_file_path_property = "HSSF.testdata.path";
public TestUnicodeNameRecord()
{
super();
_test_file_path = System.getProperty( _test_file_path_property ) +
File.separator + "unicodeNameRecord.xls";
}
public void testReadBook() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream(_test_file_path)
);
// This bit used to crash // This bit used to crash
HSSFWorkbook book = new HSSFWorkbook(fs); HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls");
HSSFSheet sheet = book.getSheetAt(0); book.getSheetAt(0);
} }
} }

View File

@ -29,6 +29,7 @@ import java.util.zip.CRC32;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.BlankRecord; import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
@ -250,22 +251,14 @@ public class TestValueRecordsAggregate extends TestCase
* *
*/ */
public void testSpuriousSharedFormulaFlag() { public void testSpuriousSharedFormulaFlag() {
File dataDir = new File(System.getProperty("HSSF.testdata.path"));
File testFile = new File(dataDir, ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
long actualCRC = getFileCRC(testFile); long actualCRC = getFileCRC(HSSFTestDataSamples.openSampleFileStream(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE));
long expectedCRC = 2277445406L; long expectedCRC = 2277445406L;
if(actualCRC != expectedCRC) { if(actualCRC != expectedCRC) {
System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC); System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC);
throw failUnexpectedTestFileChange(); throw failUnexpectedTestFileChange();
} }
HSSFWorkbook wb; HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
try {
FileInputStream in = new FileInputStream(testFile);
wb = new HSSFWorkbook(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
HSSFSheet s = wb.getSheetAt(0); // Sheet1 HSSFSheet s = wb.getSheetAt(0); // Sheet1
@ -311,11 +304,10 @@ public class TestValueRecordsAggregate extends TestCase
/** /**
* gets a CRC checksum for the content of a file * gets a CRC checksum for the content of a file
*/ */
private static long getFileCRC(File f) { private static long getFileCRC(InputStream is) {
CRC32 crc = new CRC32(); CRC32 crc = new CRC32();
byte[] buf = new byte[2048]; byte[] buf = new byte[2048];
try { try {
InputStream is = new FileInputStream(f);
while(true) { while(true) {
int bytesRead = is.read(buf); int bytesRead = is.read(buf);
if(bytesRead < 1) { if(bytesRead < 1) {

View File

@ -25,6 +25,7 @@ import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@ -36,28 +37,15 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* @author Daniel Noll (daniel at nuix dot com dot au) * @author Daniel Noll (daniel at nuix dot com dot au)
*/ */
public abstract class AbstractPtgTestCase extends TestCase { public abstract class AbstractPtgTestCase extends TestCase {
/** Directory containing the test data. */
private static String dataDir = System.getProperty("HSSF.testdata.path");
/** /**
* Loads a workbook from the given filename in the test data dir. * Loads a workbook from the given filename in the test data dir.
* *
* @param filename the filename. * @param sampleFileName the filename.
* @return the loaded workbook. * @return the loaded workbook.
* @throws IOException if an error occurs loading the workbook.
*/ */
protected static final HSSFWorkbook loadWorkbook(String filename) protected static final HSSFWorkbook loadWorkbook(String sampleFileName) {
throws IOException { return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
File file = new File(dataDir, filename);
InputStream stream = new BufferedInputStream(new FileInputStream(file));
// TODO - temp workaround to keep stdout quiet due to warning msg in POIFS
// When that warning msg is disabled, remove this wrapper and the close() call,
InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(stream);
try {
return new HSSFWorkbook(wrappedStream);
} finally {
stream.close();
}
} }
/** /**
@ -65,11 +53,11 @@ public abstract class AbstractPtgTestCase extends TestCase {
*/ */
protected static final Workbook createWorkbookWithSheet(String sheetName) { protected static final Workbook createWorkbookWithSheet(String sheetName) {
Workbook book = Workbook.createWorkbook(); Workbook book = Workbook.createWorkbook();
// this creates sheet if it doesn't exist // this creates sheet if it doesn't exist
book.checkExternSheet(0); book.checkExternSheet(0);
// TODO - this call alone does not create the sheet even though the javadoc says it does // TODO - this call alone does not create the sheet even though the javadoc says it does
book.setSheetName(0, sheetName); book.setSheetName(0, sheetName);
return book; return book;
} }
} }

View File

@ -17,11 +17,9 @@
package org.apache.poi.hssf.record.formula; package org.apache.poi.hssf.record.formula;
import java.io.FileInputStream;
import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/** /**
@ -37,15 +35,7 @@ public final class TestExternalFunctionFormulas extends TestCase {
* tests <tt>NameXPtg.toFormulaString(Workbook)</tt> and logic in Workbook below that * tests <tt>NameXPtg.toFormulaString(Workbook)</tt> and logic in Workbook below that
*/ */
public void testReadFormulaContainingExternalFunction() { public void testReadFormulaContainingExternalFunction() {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls");
+ "externalFunctionExample.xls";
HSSFWorkbook wb;
try {
FileInputStream fin = new FileInputStream(filePath);
wb = new HSSFWorkbook( fin );
} catch (IOException e) {
throw new RuntimeException(e);
}
String expectedFormula = "YEARFRAC(B1,C1)"; String expectedFormula = "YEARFRAC(B1,C1)";
HSSFSheet sht = wb.getSheetAt(0); HSSFSheet sht = wb.getSheetAt(0);

View File

@ -17,9 +17,6 @@
package org.apache.poi.hssf.record.formula.eval; package org.apache.poi.hssf.record.formula.eval;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -27,6 +24,7 @@ import java.io.InputStream;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFRow;
@ -43,49 +41,13 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator.CellValue;
*/ */
public final class TestFormulaBugs extends TestCase { public final class TestFormulaBugs extends TestCase {
private static final String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path";
/**
* Opens a sample file from the standard HSSF test data directory
*
* @return an open <tt>InputStream</tt> for the specified sample file
*/
private static InputStream openSampleFileStream(String sampleFileName) {
// TODO - move this method somewhere common
String dataDirName = System
.getProperty(TEST_DATA_DIR_SYS_PROPERTY_NAME);
if (dataDirName == null) {
throw new RuntimeException("Must set system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME
+ "' before running tests");
}
File dataDir = new File(dataDirName);
if (!dataDir.exists()) {
throw new RuntimeException("Data dir '" + dataDirName
+ "' specified by system property '"
+ TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist");
}
File f = new File(dataDir, sampleFileName);
if (!f.exists()) {
throw new RuntimeException("Sample file '" + sampleFileName
+ "' not found in data dir '" + dataDirName + "'");
}
InputStream is;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
return is;
}
/** /**
* Bug 27349 - VLOOKUP with reference to another sheet.<p/> This test was * Bug 27349 - VLOOKUP with reference to another sheet.<p/> This test was
* added <em>long</em> after the relevant functionality was fixed. * added <em>long</em> after the relevant functionality was fixed.
*/ */
public void test27349() { public void test27349() {
// 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622 // 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622
InputStream is = openSampleFileStream("27349-vlookupAcrossSheets.xls"); InputStream is = HSSFTestDataSamples.openSampleFileStream("27349-vlookupAcrossSheets.xls");
HSSFWorkbook wb; HSSFWorkbook wb;
try { try {
// original bug may have thrown exception here, or output warning to // original bug may have thrown exception here, or output warning to

View File

@ -17,13 +17,13 @@
package org.apache.poi.hssf.record.formula.eval; package org.apache.poi.hssf.record.formula.eval;
import java.io.FileInputStream;
import java.io.PrintStream; import java.io.PrintStream;
import junit.framework.Assert; import junit.framework.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.formula.functions.TestMathX; import org.apache.poi.hssf.record.formula.functions.TestMathX;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
@ -155,9 +155,7 @@ public final class TestFormulasFromSpreadsheet extends TestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
if (workbook == null) { if (workbook == null) {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME; workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME);
FileInputStream fin = new FileInputStream( filePath );
workbook = new HSSFWorkbook( fin );
sheet = workbook.getSheetAt( 0 ); sheet = workbook.getSheetAt( 0 );
} }
_functionFailureCount = 0; _functionFailureCount = 0;
@ -178,14 +176,14 @@ public final class TestFormulasFromSpreadsheet extends TestCase {
String successMsg = "There were " String successMsg = "There were "
+ _evaluationSuccessCount + " successful evaluation(s) and " + _evaluationSuccessCount + " successful evaluation(s) and "
+ _functionSuccessCount + " function(s) without error"; + _functionSuccessCount + " function(s) without error";
if(_functionFailureCount > 0) { if(_functionFailureCount > 0) {
String msg = _functionFailureCount + " function(s) failed in " String msg = _functionFailureCount + " function(s) failed in "
+ _evaluationFailureCount + " evaluation(s). " + successMsg; + _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionFailedError(msg); throw new AssertionFailedError(msg);
} }
if(false) { // normally no output for successful tests if(false) { // normally no output for successful tests
System.out.println(getClass().getName() + ": " + successMsg); System.out.println(getClass().getName() + ": " + successMsg);
} }
} }
/** /**

View File

@ -23,6 +23,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.RecordFormatException; import org.apache.poi.hssf.record.RecordFormatException;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -45,14 +46,7 @@ public final class TestReadMissingBuiltInFuncs extends TestCase {
private static HSSFSheet getSheet() { private static HSSFSheet getSheet() {
if (_sheet == null) { if (_sheet == null) {
String cwd = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME);
HSSFWorkbook wb;
try {
InputStream is = new FileInputStream(new File(cwd, SAMPLE_SPREADSHEET_FILE_NAME));
wb = new HSSFWorkbook(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
_sheet = wb.getSheetAt(0); _sheet = wb.getSheetAt(0);
} }
return _sheet; return _sheet;

View File

@ -26,6 +26,7 @@ import junit.framework.Assert;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.formula.eval.ErrorEval; import org.apache.poi.hssf.record.formula.eval.ErrorEval;
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
@ -66,17 +67,17 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
public final static String README_SHEET_NAME = "Read Me"; public final static String README_SHEET_NAME = "Read Me";
/** Row (zero-based) in each sheet where the evaluation cases start. */ /** Row (zero-based) in each sheet where the evaluation cases start. */
public static final int START_TEST_CASES_ROW_INDEX = 4; // Row '5' public static final int START_TEST_CASES_ROW_INDEX = 4; // Row '5'
/** Index of the column that contains the function names */ /** Index of the column that contains the function names */
public static final short COLUMN_INDEX_MARKER = 0; // Column 'A' public static final short COLUMN_INDEX_MARKER = 0; // Column 'A'
public static final short COLUMN_INDEX_EVALUATION = 1; // Column 'B' public static final short COLUMN_INDEX_EVALUATION = 1; // Column 'B'
public static final short COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' public static final short COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C'
public static final short COLUMN_ROW_COMMENT = 3; // Column 'D' public static final short COLUMN_ROW_COMMENT = 3; // Column 'D'
/** Used to indicate when there are no more test cases on the current sheet */ /** Used to indicate when there are no more test cases on the current sheet */
public static final String TEST_CASES_END_MARKER = "<end>"; public static final String TEST_CASES_END_MARKER = "<end>";
/** Used to indicate that the test on the current row should be ignored */ /** Used to indicate that the test on the current row should be ignored */
public static final String SKIP_CURRENT_TEST_CASE_MARKER = "<skip>"; public static final String SKIP_CURRENT_TEST_CASE_MARKER = "<skip>";
} }
@ -90,8 +91,8 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
private static void confirmExpectedResult(String msg, HSSFCell expected, CellValue actual) { private static void confirmExpectedResult(String msg, HSSFCell expected, CellValue actual) {
if (expected == null) { if (expected == null) {
throw new AssertionFailedError(msg + " - Bad setup data expected value is null"); throw new AssertionFailedError(msg + " - Bad setup data expected value is null");
} }
if(actual == null) { if(actual == null) {
@ -111,18 +112,18 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
switch (expected.getCellType()) { switch (expected.getCellType()) {
case HSSFCell.CELL_TYPE_BOOLEAN: case HSSFCell.CELL_TYPE_BOOLEAN:
assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue());
break; break;
case HSSFCell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation case HSSFCell.CELL_TYPE_FORMULA: // will never be used, since we will call method after formula evaluation
throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg); throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg);
case HSSFCell.CELL_TYPE_NUMERIC: case HSSFCell.CELL_TYPE_NUMERIC:
assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0); assertEquals(expected.getNumericCellValue(), actual.getNumberValue(), 0.0);
break; break;
case HSSFCell.CELL_TYPE_STRING: case HSSFCell.CELL_TYPE_STRING:
assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString()); assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getRichTextStringValue().getString());
break; break;
} }
} }
private static AssertionFailedError wrongTypeError(String msgPrefix, HSSFCell expectedCell, CellValue actualValue) { private static AssertionFailedError wrongTypeError(String msgPrefix, HSSFCell expectedCell, CellValue actualValue) {
@ -178,55 +179,48 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
protected void setUp() throws Exception { protected void setUp() throws Exception {
_sheetFailureCount = 0; _sheetFailureCount = 0;
_sheetSuccessCount = 0; _sheetSuccessCount = 0;
_evaluationFailureCount = 0; _evaluationFailureCount = 0;
_evaluationSuccessCount = 0; _evaluationSuccessCount = 0;
} }
public void testFunctionsFromTestSpreadsheet() { public void testFunctionsFromTestSpreadsheet() {
String filePath = System.getProperty("HSSF.testdata.path")+ "/" + SS.FILENAME; HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME);
HSSFWorkbook workbook;
try { confirmReadMeSheet(workbook);
FileInputStream fin = new FileInputStream( filePath ); int nSheets = workbook.getNumberOfSheets();
workbook = new HSSFWorkbook( fin ); for(int i=1; i< nSheets; i++) {
} catch (IOException e) { int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i));
throw new RuntimeException(e); switch(sheetResult) {
case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break;
case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break;
}
} }
confirmReadMeSheet(workbook); // confirm results
int nSheets = workbook.getNumberOfSheets(); String successMsg = "There were "
for(int i=1; i< nSheets; i++) { + _sheetSuccessCount + " successful sheets(s) and "
int sheetResult = processTestSheet(workbook, i, workbook.getSheetName(i));
switch(sheetResult) {
case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount ++; break;
case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount ++; break;
}
}
// confirm results
String successMsg = "There were "
+ _sheetSuccessCount + " successful sheets(s) and "
+ _evaluationSuccessCount + " function(s) without error"; + _evaluationSuccessCount + " function(s) without error";
if(_sheetFailureCount > 0) { if(_sheetFailureCount > 0) {
String msg = _sheetFailureCount + " sheets(s) failed with " String msg = _sheetFailureCount + " sheets(s) failed with "
+ _evaluationFailureCount + " evaluation(s). " + successMsg; + _evaluationFailureCount + " evaluation(s). " + successMsg;
throw new AssertionFailedError(msg); throw new AssertionFailedError(msg);
} }
if(false) { // normally no output for successful tests if(false) { // normally no output for successful tests
System.out.println(getClass().getName() + ": " + successMsg); System.out.println(getClass().getName() + ": " + successMsg);
} }
} }
private int processTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) { private int processTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) {
HSSFSheet sheet = workbook.getSheetAt(sheetIndex); HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, workbook); HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet, workbook);
int maxRows = sheet.getLastRowNum()+1; int maxRows = sheet.getLastRowNum()+1;
int result = Result.NO_EVALUATIONS_FOUND; // so far int result = Result.NO_EVALUATIONS_FOUND; // so far
String currentGroupComment = null; String currentGroupComment = null;
for(int rowIndex=SS.START_TEST_CASES_ROW_INDEX; rowIndex<maxRows; rowIndex++) { for(int rowIndex=SS.START_TEST_CASES_ROW_INDEX; rowIndex<maxRows; rowIndex++) {
HSSFRow r = sheet.getRow(rowIndex); HSSFRow r = sheet.getRow(rowIndex);
String newMarkerValue = getMarkerColumnValue(r); String newMarkerValue = getMarkerColumnValue(r);
if(r == null) { if(r == null) {
continue; continue;
@ -242,7 +236,7 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
if(newMarkerValue != null) { if(newMarkerValue != null) {
currentGroupComment = newMarkerValue; currentGroupComment = newMarkerValue;
} }
HSSFCell c = r.getCell(SS.COLUMN_INDEX_EVALUATION); HSSFCell c = r.getCell(SS.COLUMN_INDEX_EVALUATION);
if (c == null || c.getCellType() != HSSFCell.CELL_TYPE_FORMULA) { if (c == null || c.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
continue; continue;
} }
@ -303,11 +297,11 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
} }
/** /**
* Asserts that the 'read me' comment page exists, and has this class' name in one of the * Asserts that the 'read me' comment page exists, and has this class' name in one of the
* cells. This back-link is to make it easy to find this class if a reader encounters the * cells. This back-link is to make it easy to find this class if a reader encounters the
* spreadsheet first. * spreadsheet first.
*/ */
private void confirmReadMeSheet(HSSFWorkbook workbook) { private void confirmReadMeSheet(HSSFWorkbook workbook) {
String firstSheetName = workbook.getSheetName(0); String firstSheetName = workbook.getSheetName(0);
if(!firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME)) { if(!firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME)) {
throw new RuntimeException("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'"); throw new RuntimeException("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'");
@ -319,9 +313,9 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
} }
/** /**
* Useful to keep output concise when expecting many failures to be reported by this test case * Useful to keep output concise when expecting many failures to be reported by this test case
*/ */
private static void printShortStackTrace(PrintStream ps, Throwable e) { private static void printShortStackTrace(PrintStream ps, Throwable e) {
StackTraceElement[] stes = e.getStackTrace(); StackTraceElement[] stes = e.getStackTrace();
@ -363,7 +357,7 @@ public final class TestLookupFunctionsFromSpreadsheet extends TestCase {
/** /**
* @return <code>null</code> if cell is missing, empty or blank * @return <code>null</code> if cell is missing, empty or blank
*/ */
private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) { private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) {
if(r == null) { if(r == null) {
return null; return null;

View File

@ -14,42 +14,35 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.ss.usermodel.FormulaEvaluator.CellValue; import org.apache.poi.ss.usermodel.FormulaEvaluator.CellValue;
import org.apache.poi.hssf.util.CellReference; import org.apache.poi.hssf.util.CellReference;
/**
*
*/
public final class TestBug42464 extends TestCase { public final class TestBug42464 extends TestCase {
String dirname;
protected void setUp() throws Exception {
super.setUp();
dirname = System.getProperty("HSSF.testdata.path");
}
public void testOKFile() throws Exception { public void testOKFile() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook( HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls");
new FileInputStream(new File(dirname,"42464-ExpPtg-ok.xls"))
);
process(wb); process(wb);
} }
public void testExpSharedBadFile() throws Exception { public void testExpSharedBadFile() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook( HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls");
new FileInputStream(new File(dirname,"42464-ExpPtg-bad.xls"))
);
process(wb); process(wb);
} }
protected void process(HSSFWorkbook wb) { private static void process(HSSFWorkbook wb) {
for(int i=0; i<wb.getNumberOfSheets(); i++) { for(int i=0; i<wb.getNumberOfSheets(); i++) {
HSSFSheet s = wb.getSheetAt(i); HSSFSheet s = wb.getSheetAt(i);
HSSFFormulaEvaluator eval = HSSFFormulaEvaluator eval =
@ -64,7 +57,7 @@ public final class TestBug42464 extends TestCase {
} }
} }
protected void process(HSSFRow row, HSSFFormulaEvaluator eval) { private static void process(HSSFRow row, HSSFFormulaEvaluator eval) {
Iterator it = row.cellIterator(); Iterator it = row.cellIterator();
while(it.hasNext()) { while(it.hasNext()) {
HSSFCell cell = (HSSFCell)it.next(); HSSFCell cell = (HSSFCell)it.next();

File diff suppressed because it is too large Load Diff

View File

@ -14,28 +14,28 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.record.formula.AreaPtg;
import org.apache.poi.hssf.record.formula.FuncVarPtg;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.hssf.record.formula.AreaPtg;
import org.apache.poi.hssf.record.formula.FuncVarPtg;
/**
*
*/
public final class TestFormulaEvaluatorBugs extends TestCase { public final class TestFormulaEvaluatorBugs extends TestCase {
private String dirName;
private String tmpDirName; private String tmpDirName;
protected void setUp() throws Exception { protected void setUp() {
super.setUp();
dirName = System.getProperty("HSSF.testdata.path");
tmpDirName = System.getProperty("java.io.tmpdir"); tmpDirName = System.getProperty("java.io.tmpdir");
} }
@ -51,8 +51,8 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
public void test44636() throws Exception { public void test44636() throws Exception {
// Open the existing file, tweak one value and // Open the existing file, tweak one value and
// re-calculate // re-calculate
FileInputStream in = new FileInputStream(new File(dirName,"44636.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44636.xls");
HSSFSheet sheet = wb.getSheetAt (0); HSSFSheet sheet = wb.getSheetAt (0);
HSSFRow row = sheet.getRow (0); HSSFRow row = sheet.getRow (0);
@ -99,72 +99,71 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public void test44297() throws IOException { public void test44297() {
FileInputStream in = new FileInputStream(new File(dirName, "44297.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
HSSFRow row; HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44297.xls");
HSSFCell cell;
HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row;
HSSFCell cell;
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); HSSFSheet sheet = wb.getSheetAt(0);
row = (HSSFRow)sheet.getRow(0); HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb);
cell = row.getCell((short)0);
assertEquals("31+46", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(1); row = sheet.getRow(0);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("30+53", cell.getCellFormula()); assertEquals("31+46", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(83, eva.evaluate(cell).getNumberValue(), 0); assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(2); row = sheet.getRow(1);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("SUM(A1:A2)", cell.getCellFormula()); assertEquals("30+53", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(160, eva.evaluate(cell).getNumberValue(), 0); assertEquals(83, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(4); row = sheet.getRow(2);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("32767+32768", cell.getCellFormula()); assertEquals("SUM(A1:A2)", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0); assertEquals(160, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(7); row = sheet.getRow(4);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("32744+42333", cell.getCellFormula()); assertEquals("32767+32768", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0); assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(8); row = sheet.getRow(7);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("327680.0/32768", cell.getCellFormula()); assertEquals("32744+42333", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(10, eva.evaluate(cell).getNumberValue(), 0); assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(9); row = sheet.getRow(8);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("32767+32769", cell.getCellFormula()); assertEquals("327680.0/32768", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0); assertEquals(10, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(10); row = sheet.getRow(9);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("35000+36000", cell.getCellFormula()); assertEquals("32767+32769", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0); assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0);
row = (HSSFRow)sheet.getRow(11); row = sheet.getRow(10);
cell = row.getCell((short)0); cell = row.getCell((short)0);
assertEquals("-1000000.0-3000000.0", cell.getCellFormula()); assertEquals("35000+36000", cell.getCellFormula());
eva.setCurrentRow(row); eva.setCurrentRow(row);
assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0);
}
row = sheet.getRow(11);
cell = row.getCell((short)0);
assertEquals("-1000000.0-3000000.0", cell.getCellFormula());
eva.setCurrentRow(row);
assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0);
}
/** /**
* Bug 44410: SUM(C:C) is valid in excel, and means a sum * Bug 44410: SUM(C:C) is valid in excel, and means a sum
@ -172,86 +171,85 @@ public final class TestFormulaEvaluatorBugs extends TestCase {
* *
* @author Nick Burch * @author Nick Burch
*/ */
public void test44410() throws IOException { public void test44410() {
FileInputStream in = new FileInputStream(new File(dirName, "SingleLetterRanges.xls"));
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
HSSFSheet sheet = wb.getSheetAt(0); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SingleLetterRanges.xls");
HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb); HSSFSheet sheet = wb.getSheetAt(0);
// =index(C:C,2,1) -> 2 HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(sheet, wb);
HSSFRow rowIDX = (HSSFRow)sheet.getRow(3);
// =sum(C:C) -> 6
HSSFRow rowSUM = (HSSFRow)sheet.getRow(4);
// =sum(C:D) -> 66
HSSFRow rowSUM2D = (HSSFRow)sheet.getRow(5);
// Test the sum // =index(C:C,2,1) -> 2
HSSFCell cellSUM = rowSUM.getCell((short)0); HSSFRow rowIDX = sheet.getRow(3);
// =sum(C:C) -> 6
HSSFRow rowSUM = sheet.getRow(4);
// =sum(C:D) -> 66
HSSFRow rowSUM2D = sheet.getRow(5);
FormulaRecordAggregate frec = // Test the sum
(FormulaRecordAggregate)cellSUM.getCellValueRecord(); HSSFCell cellSUM = rowSUM.getCell((short)0);
List ops = frec.getFormulaRecord().getParsedExpression();
assertEquals(2, ops.size());
assertEquals(AreaPtg.class, ops.get(0).getClass());
assertEquals(FuncVarPtg.class, ops.get(1).getClass());
// Actually stored as C1 to C65536 FormulaRecordAggregate frec =
// (last row is -1 === 65535) (FormulaRecordAggregate)cellSUM.getCellValueRecord();
AreaPtg ptg = (AreaPtg)ops.get(0); List ops = frec.getFormulaRecord().getParsedExpression();
assertEquals(2, ptg.getFirstColumn()); assertEquals(2, ops.size());
assertEquals(2, ptg.getLastColumn()); assertEquals(AreaPtg.class, ops.get(0).getClass());
assertEquals(0, ptg.getFirstRow()); assertEquals(FuncVarPtg.class, ops.get(1).getClass());
assertEquals(65535, ptg.getLastRow());
assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook()));
// Will show as C:C, but won't know how many // Actually stored as C1 to C65536
// rows it covers as we don't have the sheet // (last row is -1 === 65535)
// to hand when turning the Ptgs into a string AreaPtg ptg = (AreaPtg)ops.get(0);
assertEquals("SUM(C:C)", cellSUM.getCellFormula()); assertEquals(2, ptg.getFirstColumn());
eva.setCurrentRow(rowSUM); assertEquals(2, ptg.getLastColumn());
assertEquals(0, ptg.getFirstRow());
assertEquals(65535, ptg.getLastRow());
assertEquals("C:C", ptg.toFormulaString(wb.getWorkbook()));
// But the evaluator knows the sheet, so it // Will show as C:C, but won't know how many
// can do it properly // rows it covers as we don't have the sheet
assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0); // to hand when turning the Ptgs into a string
assertEquals("SUM(C:C)", cellSUM.getCellFormula());
eva.setCurrentRow(rowSUM);
// But the evaluator knows the sheet, so it
// can do it properly
assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0);
// Test the index // Test the index
// Again, the formula string will be right but // Again, the formula string will be right but
// lacking row count, evaluated will be right // lacking row count, evaluated will be right
HSSFCell cellIDX = rowIDX.getCell((short)0); HSSFCell cellIDX = rowIDX.getCell((short)0);
assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula()); assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula());
eva.setCurrentRow(rowIDX); eva.setCurrentRow(rowIDX);
assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0); assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0);
// Across two colums // Across two colums
HSSFCell cellSUM2D = rowSUM2D.getCell((short)0); HSSFCell cellSUM2D = rowSUM2D.getCell((short)0);
assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); assertEquals("SUM(C:D)", cellSUM2D.getCellFormula());
eva.setCurrentRow(rowSUM2D); eva.setCurrentRow(rowSUM2D);
assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0);
} }
/** /**
* Tests that we can evaluate boolean cells properly * Tests that we can evaluate boolean cells properly
*/ */
public void testEvaluateBooleanInCell_bug44508() { public void testEvaluateBooleanInCell_bug44508() {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "Sheet1"); wb.setSheetName(0, "Sheet1");
HSSFRow row = sheet.createRow(0); HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short)0); HSSFCell cell = row.createCell((short)0);
cell.setCellFormula("1=1"); cell.setCellFormula("1=1");
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb); HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(sheet, wb);
fe.setCurrentRow(row); fe.setCurrentRow(row);
try { try {
fe.evaluateInCell(cell); fe.evaluateInCell(cell);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
fail("Identified bug 44508"); fail("Identified bug 44508");
} }
assertEquals(true, cell.getBooleanCellValue()); assertEquals(true, cell.getBooleanCellValue());
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,7 +15,6 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File; import java.io.File;
@ -27,6 +25,7 @@ import java.util.Date;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.util.CellReference; import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
@ -34,11 +33,10 @@ import org.apache.poi.util.TempFile;
* @author Andrew C. Oliver (acoliver at apache dot org) * @author Andrew C. Oliver (acoliver at apache dot org)
* @author Avik Sengupta * @author Avik Sengupta
*/ */
public final class TestFormulas extends TestCase {
public class TestFormulas private static HSSFWorkbook openSample(String sampleFileName) {
extends TestCase { return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
public TestFormulas(String s) {
super(s);
} }
/** /**
@ -48,7 +46,6 @@ extends TestCase {
public void testBasicAddIntegers() public void testBasicAddIntegers()
throws Exception { throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormula",".xls"); File file = TempFile.createTempFile("testFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -170,7 +167,6 @@ extends TestCase {
private void floatTest(String operator) private void floatTest(String operator)
throws Exception { throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaFloat",".xls"); File file = TempFile.createTempFile("testFormulaFloat",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -210,7 +206,6 @@ extends TestCase {
private void floatVerify(String operator, File file) private void floatVerify(String operator, File file)
throws Exception { throws Exception {
short rownum = 0;
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFWorkbook wb = new HSSFWorkbook(in);
@ -334,7 +329,6 @@ extends TestCase {
*/ */
private void operationalRefVerify(String operator, File file) private void operationalRefVerify(String operator, File file)
throws Exception { throws Exception {
short rownum = 0;
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFWorkbook wb = new HSSFWorkbook(in);
@ -451,7 +445,6 @@ extends TestCase {
*/ */
private void binomialOperator(String operator) private void binomialOperator(String operator)
throws Exception { throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormula",".xls"); File file = TempFile.createTempFile("testFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -495,7 +488,6 @@ extends TestCase {
*/ */
private void binomialVerify(String operator, File file) private void binomialVerify(String operator, File file)
throws Exception { throws Exception {
short rownum = 0;
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFWorkbook wb = new HSSFWorkbook(in);
@ -549,7 +541,6 @@ extends TestCase {
public void areaFunctionTest(String function) public void areaFunctionTest(String function)
throws Exception { throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaAreaFunction"+function,".xls"); File file = TempFile.createTempFile("testFormulaAreaFunction"+function,".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -587,7 +578,6 @@ extends TestCase {
public void refArrayFunctionTest(String function) public void refArrayFunctionTest(String function)
throws Exception { throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaArrayFunction"+function,".xls"); File file = TempFile.createTempFile("testFormulaArrayFunction"+function,".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -626,7 +616,6 @@ extends TestCase {
public void refAreaArrayFunctionTest(String function) public void refAreaArrayFunctionTest(String function)
throws Exception { throws Exception {
short rownum = 0;
File file = TempFile.createTempFile("testFormulaAreaArrayFunction"+function,".xls"); File file = TempFile.createTempFile("testFormulaAreaArrayFunction"+function,".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -711,8 +700,6 @@ extends TestCase {
public void testSheetFunctions() public void testSheetFunctions()
throws IOException throws IOException
{ {
String filename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testSheetFormula",".xls"); File file = TempFile.createTempFile("testSheetFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -785,8 +772,6 @@ extends TestCase {
public void testStringFormulas() public void testStringFormulas()
throws IOException throws IOException
{ {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testStringFormula",".xls"); File file = TempFile.createTempFile("testStringFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -801,17 +786,13 @@ extends TestCase {
wb.write(out); wb.write(out);
out.close(); out.close();
assertTrue("file exists",file.exists()); wb = openSample("StringFormulas.xls");
FileInputStream in = new FileInputStream(readFilename+File.separator+"StringFormulas.xls");
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0); s = wb.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell((short)0); c = r.getCell((short)0);
assertTrue("expected: UPPER(\"xyz\") got "+c.getCellFormula(), ("UPPER(\"xyz\")").equals(c.getCellFormula())); assertTrue("expected: UPPER(\"xyz\") got "+c.getCellFormula(), ("UPPER(\"xyz\")").equals(c.getCellFormula()));
//c = r.getCell((short)1); //c = r.getCell((short)1);
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); //assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
in.close();
} }
@ -847,8 +828,6 @@ extends TestCase {
public void testDateFormulas() public void testDateFormulas()
throws IOException throws IOException
{ {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testDateFormula",".xls"); File file = TempFile.createTempFile("testDateFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -885,8 +864,6 @@ extends TestCase {
public void testIfFormulas() public void testIfFormulas()
throws IOException throws IOException
{ {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testIfFormula",".xls"); File file = TempFile.createTempFile("testIfFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -913,9 +890,7 @@ extends TestCase {
assertTrue("expected: IF(A1=D1,\"A1\",\"B1\") got "+c.getCellFormula(), ("IF(A1=D1,\"A1\",\"B1\")").equals(c.getCellFormula())); assertTrue("expected: IF(A1=D1,\"A1\",\"B1\") got "+c.getCellFormula(), ("IF(A1=D1,\"A1\",\"B1\")").equals(c.getCellFormula()));
in.close(); in.close();
wb = openSample("IfFormulaTest.xls");
in = new FileInputStream(readFilename+File.separator+"IfFormulaTest.xls");
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0); s = wb.getSheetAt(0);
r = s.getRow(3); r = s.getRow(3);
c = r.getCell((short)0); c = r.getCell((short)0);
@ -924,117 +899,106 @@ extends TestCase {
//assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); //assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula()));
in.close(); in.close();
File simpleIf = TempFile.createTempFile("testSimpleIfFormulaWrite",".xls"); File simpleIf = TempFile.createTempFile("testSimpleIfFormulaWrite",".xls");
out = new FileOutputStream(simpleIf); out = new FileOutputStream(simpleIf);
wb = new HSSFWorkbook(); wb = new HSSFWorkbook();
s = wb.createSheet("testSheet1"); s = wb.createSheet("testSheet1");
r = null; r = null;
c = null; c = null;
r = s.createRow((short)0); r = s.createRow((short)0);
c=r.createCell((short)0); c.setCellFormula("IF(1=1,0,1)"); c=r.createCell((short)0); c.setCellFormula("IF(1=1,0,1)");
wb.write(out); wb.write(out);
out.close(); out.close();
assertTrue("file exists", simpleIf.exists()); assertTrue("file exists", simpleIf.exists());
assertTrue("length of simpleIf file is zero", (simpleIf.length()>0)); assertTrue("length of simpleIf file is zero", (simpleIf.length()>0));
File nestedIf = TempFile.createTempFile("testNestedIfFormula",".xls"); File nestedIf = TempFile.createTempFile("testNestedIfFormula",".xls");
out = new FileOutputStream(nestedIf); out = new FileOutputStream(nestedIf);
wb = new HSSFWorkbook(); wb = new HSSFWorkbook();
s = wb.createSheet("testSheet1"); s = wb.createSheet("testSheet1");
r = null; r = null;
c = null; c = null;
r = s.createRow((short)0); r = s.createRow((short)0);
c=r.createCell((short)0); c=r.createCell((short)0);
c.setCellValue(1); c.setCellValue(1);
c=r.createCell((short)1); c=r.createCell((short)1);
c.setCellValue(3); c.setCellValue(3);
HSSFCell formulaCell=r.createCell((short)3); HSSFCell formulaCell=r.createCell((short)3);
r = s.createRow((short)1); r = s.createRow((short)1);
c=r.createCell((short)0); c=r.createCell((short)0);
c.setCellValue(3); c.setCellValue(3);
c=r.createCell((short)1); c=r.createCell((short)1);
c.setCellValue(7); c.setCellValue(7);
formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))"); formulaCell.setCellFormula("IF(A1=B1,AVERAGE(A1:B1),AVERAGE(A2:B2))");
wb.write(out); wb.write(out);
out.close(); out.close();
assertTrue("file exists", nestedIf.exists()); assertTrue("file exists", nestedIf.exists());
assertTrue("length of nestedIf file is zero", (nestedIf.length()>0)); assertTrue("length of nestedIf file is zero", (nestedIf.length()>0));
} }
public void testSumIf() public void testSumIf()
throws IOException throws IOException
{ {
String readFilename = System.getProperty("HSSF.testdata.path"); String function ="SUMIF(A1:A5,\">4000\",B1:B5)";
String function ="SUMIF(A1:A5,\">4000\",B1:B5)";
File inFile = new File(readFilename+"/sumifformula.xls"); HSSFWorkbook wb = openSample("sumifformula.xls");
FileInputStream in = new FileInputStream(inFile);
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
HSSFSheet s = wb.getSheetAt(0); HSSFSheet s = wb.getSheetAt(0);
HSSFRow r = s.getRow(0); HSSFRow r = s.getRow(0);
HSSFCell c = r.getCell((short)2); HSSFCell c = r.getCell((short)2);
assertEquals(function, c.getCellFormula()); assertEquals(function, c.getCellFormula());
File file = TempFile.createTempFile("testSumIfFormula",".xls"); File file = TempFile.createTempFile("testSumIfFormula",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
wb = new HSSFWorkbook(); wb = new HSSFWorkbook();
s = wb.createSheet(); s = wb.createSheet();
r = s.createRow((short)0); r = s.createRow((short)0);
c=r.createCell((short)0); c.setCellValue((double)1000); c=r.createCell((short)0); c.setCellValue((double)1000);
c=r.createCell((short)1); c.setCellValue((double)1); c=r.createCell((short)1); c.setCellValue((double)1);
r = s.createRow((short)1); r = s.createRow((short)1);
c=r.createCell((short)0); c.setCellValue((double)2000); c=r.createCell((short)0); c.setCellValue((double)2000);
c=r.createCell((short)1); c.setCellValue((double)2); c=r.createCell((short)1); c.setCellValue((double)2);
r = s.createRow((short)2); r = s.createRow((short)2);
c=r.createCell((short)0); c.setCellValue((double)3000); c=r.createCell((short)0); c.setCellValue((double)3000);
c=r.createCell((short)1); c.setCellValue((double)3); c=r.createCell((short)1); c.setCellValue((double)3);
r = s.createRow((short)3); r = s.createRow((short)3);
c=r.createCell((short)0); c.setCellValue((double)4000); c=r.createCell((short)0); c.setCellValue((double)4000);
c=r.createCell((short)1); c.setCellValue((double)4); c=r.createCell((short)1); c.setCellValue((double)4);
r = s.createRow((short)4); r = s.createRow((short)4);
c=r.createCell((short)0); c.setCellValue((double)5000); c=r.createCell((short)0); c.setCellValue((double)5000);
c=r.createCell((short)1); c.setCellValue((double)5); c=r.createCell((short)1); c.setCellValue((double)5);
r = s.getRow(0); r = s.getRow(0);
c=r.createCell((short)2); c.setCellFormula(function); c=r.createCell((short)2); c.setCellFormula(function);
wb.write(out); wb.write(out);
out.close(); out.close();
assertTrue("sumif file doesnt exists", (file.exists())); assertTrue("sumif file doesnt exists", (file.exists()));
assertTrue("sumif == 0 bytes", file.length() > 0); assertTrue("sumif == 0 bytes", file.length() > 0);
} }
public void testSquareMacro() {
HSSFWorkbook w = openSample("SquareMacro.xls");
public void testSquareMacro() throws IOException {
File dir = new File(System.getProperty("HSSF.testdata.path"));
File xls = new File(dir, "SquareMacro.xls");
FileInputStream in = new FileInputStream(xls);
HSSFWorkbook w;
try {
w = new HSSFWorkbook(in);
} finally {
in.close();
}
HSSFSheet s0 = w.getSheetAt(0); HSSFSheet s0 = w.getSheetAt(0);
HSSFRow[] r = {s0.getRow(0), s0.getRow(1)}; HSSFRow[] r = {s0.getRow(0), s0.getRow(1)};
@ -1071,78 +1035,58 @@ extends TestCase {
assertEquals(4d, d2.getNumericCellValue(), 1e-9); assertEquals(4d, d2.getNumericCellValue(), 1e-9);
} }
public void testStringFormulaRead() throws IOException { public void testStringFormulaRead() {
File dir = new File(System.getProperty("HSSF.testdata.path")); HSSFWorkbook w = openSample("StringFormulas.xls");
File xls = new File(dir, "StringFormulas.xls");
FileInputStream in = new FileInputStream(xls);
HSSFWorkbook w;
try {
w = new HSSFWorkbook(in);
} finally {
in.close();
}
HSSFCell c = w.getSheetAt(0).getRow(0).getCell((short)0); HSSFCell c = w.getSheetAt(0).getRow(0).getCell((short)0);
assertEquals("String Cell value","XYZ",c.getStringCellValue()); assertEquals("String Cell value","XYZ",c.getRichStringCellValue().getString());
} }
/** test for bug 34021*/ /** test for bug 34021*/
public void testComplexSheetRefs () throws IOException { public void testComplexSheetRefs () throws IOException {
HSSFWorkbook sb = new HSSFWorkbook(); HSSFWorkbook sb = new HSSFWorkbook();
HSSFSheet s1 = sb.createSheet("Sheet a.1"); HSSFSheet s1 = sb.createSheet("Sheet a.1");
HSSFSheet s2 = sb.createSheet("Sheet.A"); HSSFSheet s2 = sb.createSheet("Sheet.A");
s2.createRow(1).createCell((short) 2).setCellFormula("'Sheet a.1'!A1"); s2.createRow(1).createCell((short) 2).setCellFormula("'Sheet a.1'!A1");
s1.createRow(1).createCell((short) 2).setCellFormula("'Sheet.A'!A1"); s1.createRow(1).createCell((short) 2).setCellFormula("'Sheet.A'!A1");
File file = TempFile.createTempFile("testComplexSheetRefs",".xls"); File file = TempFile.createTempFile("testComplexSheetRefs",".xls");
sb.write(new FileOutputStream(file)); sb.write(new FileOutputStream(file));
} }
/*Unknown Ptg 3C*/ /*Unknown Ptg 3C*/
public void test27272_1() throws Exception { public void test27272_1() throws Exception {
String readFilename = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = openSample("27272_1.xls");
File inFile = new File(readFilename+"/27272_1.xls"); wb.getSheetAt(0);
FileInputStream in = new FileInputStream(inFile); assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference());
HSSFWorkbook wb = new HSSFWorkbook(in); File outF = File.createTempFile("bug27272_1",".xls");
wb.getSheetAt(0); wb.write(new FileOutputStream(outF));
assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference()); System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
File outF = File.createTempFile("bug27272_1",".xls"); }
wb.write(new FileOutputStream(outF)); /*Unknown Ptg 3D*/
System.out.println("Open "+outF.getAbsolutePath()+" in Excel"); public void test27272_2() throws Exception {
} HSSFWorkbook wb = openSample("27272_2.xls");
/*Unknown Ptg 3D*/ assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference());
public void test27272_2() throws Exception { File outF = File.createTempFile("bug27272_2",".xls");
String readFilename = System.getProperty("HSSF.testdata.path"); wb.write(new FileOutputStream(outF));
File inFile = new File(readFilename+"/27272_2.xls"); System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
FileInputStream in = new FileInputStream(inFile); }
HSSFWorkbook wb = new HSSFWorkbook(in);
assertEquals("Reference for named range ", "#REF!",wb.getNameAt(0).getReference());
File outF = File.createTempFile("bug27272_2",".xls");
wb.write(new FileOutputStream(outF));
System.out.println("Open "+outF.getAbsolutePath()+" in Excel");
}
/* MissingArgPtg */ /* MissingArgPtg */
public void testMissingArgPtg() throws Exception { public void testMissingArgPtg() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell((short) 0); HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell((short) 0);
cell.setCellFormula("IF(A1=\"A\",1,)"); cell.setCellFormula("IF(A1=\"A\",1,)");
} }
public void testSharedFormula() throws Exception { public void testSharedFormula() {
String readFilename = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = openSample("SharedFormulaTest.xls");
File inFile = new File(readFilename+"/SharedFormulaTest.xls");
FileInputStream fis = new FileInputStream(inFile);
HSSFWorkbook wb = new HSSFWorkbook(fis);
assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell((short)1).toString()); assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell((short)1).toString());
assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell((short)1).toString()); assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell((short)1).toString());
assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell((short)128).toString()); assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell((short)128).toString());
assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell((short)1).toString()); assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell((short)1).toString());
} }
public static void main(String [] args) { public static void main(String [] args) {
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestFormulas");
junit.textui.TestRunner.run(TestFormulas.class); junit.textui.TestRunner.run(TestFormulas.class);
} }
} }

View File

@ -17,18 +17,21 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import junit.framework.AssertionFailedError; import junit.framework.AssertionFailedError;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
/** /**
@ -40,12 +43,26 @@ import org.apache.poi.util.TempFile;
*/ */
public final class TestHSSFCell extends TestCase { public final class TestHSSFCell extends TestCase {
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
private static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
original.write(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new HSSFWorkbook(bais);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** /**
* test that Boolean and Error types (BoolErrRecord) are supported properly. * test that Boolean and Error types (BoolErrRecord) are supported properly.
*/ */
public void testBoolErr() public void testBoolErr()
throws java.io.IOException { throws java.io.IOException {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testBoolErr",".xls"); File file = TempFile.createTempFile("testBoolErr",".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
@ -102,33 +119,24 @@ public final class TestHSSFCell extends TestCase {
public void testDateWindowingRead() throws Exception { public void testDateWindowingRead() throws Exception {
GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000
Date date = cal.getTime(); Date date = cal.getTime();
String path = System.getProperty("HSSF.testdata.path");
// first check a file with 1900 Date Windowing // first check a file with 1900 Date Windowing
String filename = path + "/1900DateWindowing.xls"; HSSFWorkbook workbook = openSample("1900DateWindowing.xls");
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals("Date from file using 1900 Date Windowing", assertEquals("Date from file using 1900 Date Windowing",
date.getTime(), date.getTime(),
sheet.getRow(0).getCell((short)0) sheet.getRow(0).getCell((short)0)
.getDateCellValue().getTime()); .getDateCellValue().getTime());
stream.close();
// now check a file with 1904 Date Windowing // now check a file with 1904 Date Windowing
filename = path + "/1904DateWindowing.xls"; workbook = openSample("1904DateWindowing.xls");
stream = new FileInputStream(filename);
fs = new POIFSFileSystem(stream);
workbook = new HSSFWorkbook(fs);
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
assertEquals("Date from file using 1904 Date Windowing", assertEquals("Date from file using 1904 Date Windowing",
date.getTime(), date.getTime(),
sheet.getRow(0).getCell((short)0) sheet.getRow(0).getCell((short)0)
.getDateCellValue().getTime()); .getDateCellValue().getTime());
stream.close();
} }
/** /**
@ -140,55 +148,39 @@ public final class TestHSSFCell extends TestCase {
public void testDateWindowingWrite() throws Exception { public void testDateWindowingWrite() throws Exception {
GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000 GregorianCalendar cal = new GregorianCalendar(2000,0,1); // Jan. 1, 2000
Date date = cal.getTime(); Date date = cal.getTime();
String path = System.getProperty("HSSF.testdata.path");
// first check a file with 1900 Date Windowing // first check a file with 1900 Date Windowing
String filename = path + "/1900DateWindowing.xls"; HSSFWorkbook wb;
writeCell(filename, 0, (short) 1, date); wb = openSample("1900DateWindowing.xls");
setCell(wb, 0, 1, date);
wb = writeOutAndReadBack(wb);
assertEquals("Date from file using 1900 Date Windowing", assertEquals("Date from file using 1900 Date Windowing",
date.getTime(), date.getTime(),
readCell(filename, 0, (short) 1).getTime()); readCell(wb, 0, 1).getTime());
// now check a file with 1904 Date Windowing // now check a file with 1904 Date Windowing
filename = path + "/1904DateWindowing.xls"; wb = openSample("1904DateWindowing.xls");
writeCell(filename, 0, (short) 1, date); setCell(wb, 0, 1, date);
wb = writeOutAndReadBack(wb);
assertEquals("Date from file using 1900 Date Windowing", assertEquals("Date from file using 1900 Date Windowing",
date.getTime(), date.getTime(),
readCell(filename, 0, (short) 1).getTime()); readCell(wb, 0, 1).getTime());
} }
/** private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) {
* Sets cell value and writes file.
*/
private void writeCell(String filename,
int rowIdx, short colIdx, Date date) throws Exception {
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIdx); HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx); HSSFCell cell = row.getCell(colIdx);
if (cell == null) { if (cell == null) {
cell = row.createCell(colIdx); cell = row.createCell((short)colIdx);
} }
cell.setCellValue(date); cell.setCellValue(date);
// Write the file
stream.close();
FileOutputStream oStream = new FileOutputStream(filename);
workbook.write(oStream);
oStream.close();
} }
/** private static Date readCell(HSSFWorkbook workbook, int rowIdx, int colIdx) {
* Reads cell value from file.
*/
private Date readCell(String filename,
int rowIdx, short colIdx) throws Exception {
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIdx); HSSFRow row = sheet.getRow(rowIdx);
HSSFCell cell = row.getCell(colIdx); HSSFCell cell = row.getCell(colIdx);
@ -201,12 +193,7 @@ public final class TestHSSFCell extends TestCase {
public void testActiveCell() throws Exception public void testActiveCell() throws Exception
{ {
//read in sample //read in sample
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook book = openSample("Simple.xls");
File sample = new File(dir + "/Simple.xls");
assertTrue("Simple.xls exists and is readable", sample.canRead());
FileInputStream fis = new FileInputStream(sample);
HSSFWorkbook book = new HSSFWorkbook(fis);
fis.close();
//check initial position //check initial position
HSSFSheet umSheet = book.getSheetAt(0); HSSFSheet umSheet = book.getSheetAt(0);
@ -225,14 +212,8 @@ public final class TestHSSFCell extends TestCase {
3, s.getActiveCellRow()); 3, s.getActiveCellRow());
//write book to temp file; read and verify that position is serialized //write book to temp file; read and verify that position is serialized
File temp = TempFile.createTempFile("testActiveCell", ".xls"); book = writeOutAndReadBack(book);
FileOutputStream fos = new FileOutputStream(temp);
book.write(fos);
fos.close();
fis = new FileInputStream(temp);
book = new HSSFWorkbook(fis);
fis.close();
umSheet = book.getSheetAt(0); umSheet = book.getSheetAt(0);
s = umSheet.getSheet(); s = umSheet.getSheet();
@ -245,12 +226,8 @@ public final class TestHSSFCell extends TestCase {
/** /**
* test that Cell Styles being applied to formulas remain intact * test that Cell Styles being applied to formulas remain intact
*/ */
public void testFormulaStyle() public void testFormulaStyle() {
throws java.io.IOException {
String readFilename = System.getProperty("HSSF.testdata.path");
File file = TempFile.createTempFile("testFormulaStyle",".xls");
FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("testSheet1"); HSSFSheet s = wb.createSheet("testSheet1");
HSSFRow r = null; HSSFRow r = null;
@ -258,7 +235,7 @@ public final class TestHSSFCell extends TestCase {
HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs = wb.createCellStyle();
HSSFFont f = wb.createFont(); HSSFFont f = wb.createFont();
f.setFontHeightInPoints((short) 20); f.setFontHeightInPoints((short) 20);
f.setColor((short) HSSFColor.RED.index); f.setColor(HSSFColor.RED.index);
f.setBoldweight(f.BOLDWEIGHT_BOLD); f.setBoldweight(f.BOLDWEIGHT_BOLD);
f.setFontName("Arial Unicode MS"); f.setFontName("Arial Unicode MS");
cs.setFillBackgroundColor((short)3); cs.setFillBackgroundColor((short)3);
@ -273,13 +250,7 @@ public final class TestHSSFCell extends TestCase {
c.setCellStyle(cs); c.setCellStyle(cs);
c.setCellFormula("2*3"); c.setCellFormula("2*3");
wb.write(out); wb = writeOutAndReadBack(wb);
out.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
s = wb.getSheetAt(0); s = wb.getSheetAt(0);
r = s.getRow(0); r = s.getRow(0);
c = r.getCell((short)0); c = r.getCell((short)0);
@ -293,17 +264,14 @@ public final class TestHSSFCell extends TestCase {
assertTrue("Left Border", (cs.getBorderLeft() == (short)1)); assertTrue("Left Border", (cs.getBorderLeft() == (short)1));
assertTrue("Right Border", (cs.getBorderRight() == (short)1)); assertTrue("Right Border", (cs.getBorderRight() == (short)1));
assertTrue("Bottom Border", (cs.getBorderBottom() == (short)1)); assertTrue("Bottom Border", (cs.getBorderBottom() == (short)1));
in.close();
} }
/** /**
* Test reading hyperlinks * Test reading hyperlinks
*/ */
public void testWithHyperlink() throws Exception { public void testWithHyperlink() {
String dir = System.getProperty("HSSF.testdata.path");
File f = new File(dir, "WithHyperlink.xls"); HSSFWorkbook wb = openSample("WithHyperlink.xls");
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
HSSFCell cell = sheet.getRow(4).getCell((short)0); HSSFCell cell = sheet.getRow(4).getCell((short)0);
@ -320,9 +288,8 @@ public final class TestHSSFCell extends TestCase {
* Test reading hyperlinks * Test reading hyperlinks
*/ */
public void testWithTwoHyperlinks() throws Exception { public void testWithTwoHyperlinks() throws Exception {
String dir = System.getProperty("HSSF.testdata.path");
File f = new File(dir, "WithTwoHyperLinks.xls"); HSSFWorkbook wb = openSample("WithTwoHyperLinks.xls");
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
@ -346,38 +313,38 @@ public final class TestHSSFCell extends TestCase {
/*tests the toString() method of HSSFCell*/ /*tests the toString() method of HSSFCell*/
public void testToString() throws Exception { public void testToString() throws Exception {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("Sheet1"); HSSFSheet s = wb.createSheet("Sheet1");
HSSFRow r = s.createRow(0); HSSFRow r = s.createRow(0);
HSSFCell c; HSSFCell c;
c=r.createCell((short) 0); c.setCellValue(true); c=r.createCell((short) 0); c.setCellValue(true);
assertEquals("Boolean", "TRUE", c.toString()); assertEquals("Boolean", "TRUE", c.toString());
c=r.createCell((short) 1); c.setCellValue(1.5); c=r.createCell((short) 1); c.setCellValue(1.5);
assertEquals("Numeric", "1.5", c.toString()); assertEquals("Numeric", "1.5", c.toString());
c=r.createCell((short)(2)); c.setCellValue("Astring"); c=r.createCell((short)(2)); c.setCellValue(new HSSFRichTextString("Astring"));
assertEquals("String", "Astring", c.toString()); assertEquals("String", "Astring", c.toString());
c=r.createCell((short) 3); c.setCellErrorValue((byte) 7); c=r.createCell((short) 3); c.setCellErrorValue((byte) 7);
assertEquals("Error", "#ERR7", c.toString()); assertEquals("Error", "#ERR7", c.toString());
c=r.createCell((short)4); c.setCellFormula("A1+B1"); c=r.createCell((short)4); c.setCellFormula("A1+B1");
assertEquals("Formula", "A1+B1", c.toString()); assertEquals("Formula", "A1+B1", c.toString());
//Write out the file, read it in, and then check cell values //Write out the file, read it in, and then check cell values
File f = File.createTempFile("testCellToString",".xls"); File f = File.createTempFile("testCellToString",".xls");
wb.write(new FileOutputStream(f)); wb.write(new FileOutputStream(f));
wb = new HSSFWorkbook(new FileInputStream(f)); wb = new HSSFWorkbook(new FileInputStream(f));
assertTrue("File exists and can be read", f.canRead()); assertTrue("File exists and can be read", f.canRead());
s = wb.getSheetAt(0);r=s.getRow(0); s = wb.getSheetAt(0);r=s.getRow(0);
c=r.getCell((short) 0); c=r.getCell((short) 0);
assertEquals("Boolean", "TRUE", c.toString()); assertEquals("Boolean", "TRUE", c.toString());
c=r.getCell((short) 1); c=r.getCell((short) 1);
assertEquals("Numeric", "1.5", c.toString()); assertEquals("Numeric", "1.5", c.toString());
c=r.getCell((short)(2)); c=r.getCell((short)(2));
assertEquals("String", "Astring", c.toString()); assertEquals("String", "Astring", c.toString());
c=r.getCell((short) 3); c=r.getCell((short) 3);
assertEquals("Error", "#ERR7", c.toString()); assertEquals("Error", "#ERR7", c.toString());
c=r.getCell((short)4); c=r.getCell((short)4);
assertEquals("Formula", "A1+B1", c.toString()); assertEquals("Formula", "A1+B1", c.toString());
} }
public void testSetStringInFormulaCell_bug44606() { public void testSetStringInFormulaCell_bug44606() {
@ -392,10 +359,7 @@ public final class TestHSSFCell extends TestCase {
} }
public static void main(String [] args) { public static void main(String [] args) {
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestHSSFCell");
junit.textui.TestRunner.run(TestHSSFCell.class); junit.textui.TestRunner.run(TestHSSFCell.class);
} }
} }

View File

@ -20,13 +20,14 @@ import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests TestHSSFCellComment. * Tests TestHSSFCellComment.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class TestHSSFComment extends TestCase {
public class TestHSSFComment extends TestCase {
/** /**
* Test that we can create cells and add comments to it. * Test that we can create cells and add comments to it.
@ -103,12 +104,9 @@ public class TestHSSFComment extends TestCase {
/** /**
* test that we can read cell comments from an existing workbook. * test that we can read cell comments from an existing workbook.
*/ */
public static void testReadComments() throws Exception { public static void testReadComments() {
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls");
FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
@ -143,12 +141,9 @@ public class TestHSSFComment extends TestCase {
/** /**
* test that we can modify existing cell comments * test that we can modify existing cell comments
*/ */
public static void testModifyComments() throws Exception { public static void testModifyComments() throws IOException {
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithComments.xls");
FileInputStream is = new FileInputStream(new File(dir, "SimpleWithComments.xls"));
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);

View File

@ -28,7 +28,7 @@ import org.apache.poi.ss.util.Region;
*/ */
public final class TestHSSFConditionalFormatting extends TestCase public final class TestHSSFConditionalFormatting extends TestCase
{ {
public void testLastAndFirstColumns() public void testCreateCF()
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(); HSSFSheet sheet = workbook.createSheet();
@ -83,8 +83,26 @@ public final class TestHSSFConditionalFormatting extends TestCase
assertEquals("7",rule1.getFormula1()); assertEquals("7",rule1.getFormula1());
assertNull(rule1.getFormula2()); assertNull(rule1.getFormula2());
HSSFFontFormatting r1fp = rule1.getFontFormatting();
assertNotNull(r1fp);
assertTrue(r1fp.isItalic());
assertFalse(r1fp.isBold());
HSSFBorderFormatting r1bf = rule1.getBorderFormatting();
assertNotNull(r1bf);
assertEquals(HSSFBorderFormatting.BORDER_THIN, r1bf.getBorderBottom());
assertEquals(HSSFBorderFormatting.BORDER_THICK,r1bf.getBorderTop());
assertEquals(HSSFBorderFormatting.BORDER_DASHED,r1bf.getBorderLeft());
assertEquals(HSSFBorderFormatting.BORDER_DOTTED,r1bf.getBorderRight());
HSSFPatternFormatting r1pf = rule1.getPatternFormatting();
assertNotNull(r1pf);
assertEquals(HSSFColor.RED.index,r1pf.getFillBackgroundColor());
HSSFConditionalFormattingRule rule2 = cf.getRule(1); HSSFConditionalFormattingRule rule2 = cf.getRule(1);
assertEquals("2",rule2.getFormula2()); assertEquals("2",rule2.getFormula2());
assertEquals("1",rule2.getFormula1()); assertEquals("1",rule2.getFormula1());
} }
} }

View File

@ -19,16 +19,15 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.TimeZone; import java.util.TimeZone;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Class TestHSSFDateUtil * Class TestHSSFDateUtil
@ -40,16 +39,13 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* @author Alex Jacoby (ajacoby at gmail.com) * @author Alex Jacoby (ajacoby at gmail.com)
* @version %I%, %G% * @version %I%, %G%
*/ */
public class TestHSSFDateUtil extends TestCase {
public class TestHSSFDateUtil public static final int CALENDAR_JANUARY = 0;
extends TestCase public static final int CALENDAR_FEBRUARY = 1;
{ public static final int CALENDAR_MARCH = 2;
public static final int CALENDAR_APRIL = 3;
public static final int CALENDAR_JANUARY = 0; public static final int CALENDAR_JULY = 6;
public static final int CALENDAR_FEBRUARY = 1;
public static final int CALENDAR_MARCH = 2;
public static final int CALENDAR_APRIL = 3;
public static final int CALENDAR_JULY = 6;
public static final int CALENDAR_OCTOBER = 9; public static final int CALENDAR_OCTOBER = 9;
public TestHSSFDateUtil(String s) public TestHSSFDateUtil(String s)
@ -223,77 +219,77 @@ public class TestHSSFDateUtil
* Tests that we correctly detect date formats as such * Tests that we correctly detect date formats as such
*/ */
public void testIdentifyDateFormats() { public void testIdentifyDateFormats() {
// First up, try with a few built in date formats // First up, try with a few built in date formats
short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e }; short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e };
for(int i=0; i<builtins.length; i++) { for(int i=0; i<builtins.length; i++) {
String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]); String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]);
assertTrue( HSSFDateUtil.isInternalDateFormat(builtins[i]) ); assertTrue( HSSFDateUtil.isInternalDateFormat(builtins[i]) );
assertTrue( HSSFDateUtil.isADateFormat(builtins[i],formatStr) ); assertTrue( HSSFDateUtil.isADateFormat(builtins[i],formatStr) );
} }
// Now try a few built-in non date formats // Now try a few built-in non date formats
builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 }; builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 };
for(int i=0; i<builtins.length; i++) { for(int i=0; i<builtins.length; i++) {
String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]); String formatStr = HSSFDataFormat.getBuiltinFormat(builtins[i]);
assertFalse( HSSFDateUtil.isInternalDateFormat(builtins[i]) ); assertFalse( HSSFDateUtil.isInternalDateFormat(builtins[i]) );
assertFalse( HSSFDateUtil.isADateFormat(builtins[i],formatStr) ); assertFalse( HSSFDateUtil.isADateFormat(builtins[i],formatStr) );
} }
// Now for some non-internal ones // Now for some non-internal ones
// These come after the real ones // These come after the real ones
int numBuiltins = HSSFDataFormat.getNumberOfBuiltinBuiltinFormats(); int numBuiltins = HSSFDataFormat.getNumberOfBuiltinBuiltinFormats();
assertTrue(numBuiltins < 60); assertTrue(numBuiltins < 60);
short formatId = 60; short formatId = 60;
assertFalse( HSSFDateUtil.isInternalDateFormat(formatId) ); assertFalse( HSSFDateUtil.isInternalDateFormat(formatId) );
// Valid ones first // Valid ones first
String[] formats = new String[] { String[] formats = new String[] {
"yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd", "yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd",
"dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy", "dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy",
"dd-mm-yy", "dd-mm-yyyy", "dd-mm-yy", "dd-mm-yyyy",
"DD-MM-YY", "DD-mm-YYYY", "DD-MM-YY", "DD-mm-YYYY",
"dd\\-mm\\-yy", // Sometimes escaped "dd\\-mm\\-yy", // Sometimes escaped
// These crazy ones are valid // These crazy ones are valid
"yyyy-mm-dd;@", "yyyy/mm/dd;@", "yyyy-mm-dd;@", "yyyy/mm/dd;@",
"dd-mm-yy;@", "dd-mm-yyyy;@", "dd-mm-yy;@", "dd-mm-yyyy;@",
// These even crazier ones are also valid // These even crazier ones are also valid
// (who knows what they mean though...) // (who knows what they mean though...)
"[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy", "[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy",
"[$-F900]ddd/mm/yyy", "[$-F900]ddd/mm/yyy",
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
// Then time based ones too // Then time based ones too
formats = new String[] { formats = new String[] {
"yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS", "yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS",
"mm/dd HH:MM", "yy/mmm/dd SS", "mm/dd HH:MM", "yy/mmm/dd SS",
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); assertTrue( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
// Then invalid ones // Then invalid ones
formats = new String[] { formats = new String[] {
"yyyy*mm*dd", "yyyy*mm*dd",
"0.0", "0.000", "0.0", "0.000",
"0%", "0.0%", "0%", "0.0%",
"", null "", null
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
// And these are ones we probably shouldn't allow, // And these are ones we probably shouldn't allow,
// but would need a better regexp // but would need a better regexp
formats = new String[] { formats = new String[] {
"yyyy:mm:dd", "yyyy:mm:dd",
}; };
for(int i=0; i<formats.length; i++) { for(int i=0; i<formats.length; i++) {
// assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); // assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) );
} }
} }
/** /**
@ -301,11 +297,8 @@ public class TestHSSFDateUtil
* correctly * correctly
*/ */
public void testOnARealFile() throws Exception { public void testOnARealFile() throws Exception {
String path = System.getProperty("HSSF.testdata.path");
String filename = path + "/DateFormats.xls"; HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream(filename));
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
Workbook wb = workbook.getWorkbook(); Workbook wb = workbook.getWorkbook();

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,20 +15,16 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests row shifting capabilities. * Tests row shifting capabilities.
@ -37,117 +32,90 @@ import java.io.FileOutputStream;
* *
* @author Shawn Laubach (slaubach at apache dot com) * @author Shawn Laubach (slaubach at apache dot com)
*/ */
public final class TestHSSFHeaderFooter extends TestCase {
public class TestHSSFHeaderFooter extends TestCase { /**
* Tests that get header retreives the proper values.
*
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testRetrieveCorrectHeader() {
// Read initial file in
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls");
HSSFSheet s = wb.getSheetAt( 0 );
HSSFHeader head = s.getHeader();
/** assertEquals("Top Left", head.getLeft());
* Constructor for TestHeaderFooter. assertEquals("Top Center", head.getCenter());
* @param arg0 assertEquals("Top Right", head.getRight());
*/ }
public TestHSSFHeaderFooter(String arg0) {
super(arg0);
}
/** /**
* Tests that get header retreives the proper values. * Tests that get header retreives the proper values.
* *
* @author Shawn Laubach (slaubach at apache dot org) * @author Shawn Laubach (slaubach at apache dot org)
*/ */
public void testRetrieveCorrectHeader() throws Exception public void testRetrieveCorrectFooter() {
{ // Read initial file in
// Read initial file in HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls");
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFSheet s = wb.getSheetAt( 0 );
filename = filename + "/EmbeddedChartHeaderTest.xls"; HSSFFooter foot = s.getFooter();
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet s = wb.getSheetAt( 0 );
HSSFHeader head = s.getHeader();
assertEquals("Top Left", head.getLeft()); assertEquals("Bottom Left", foot.getLeft());
assertEquals("Top Center", head.getCenter()); assertEquals("Bottom Center", foot.getCenter());
assertEquals("Top Right", head.getRight()); assertEquals("Bottom Right", foot.getRight());
} }
/** /**
* Tests that get header retreives the proper values.
*
* @author Shawn Laubach (slaubach at apache dot org)
*/
public void testRetrieveCorrectFooter() throws Exception
{
// Read initial file in
String filename = System.getProperty( "HSSF.testdata.path" );
filename = filename + "/EmbeddedChartHeaderTest.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet s = wb.getSheetAt( 0 );
HSSFFooter foot = s.getFooter();
assertEquals("Bottom Left", foot.getLeft());
assertEquals("Bottom Center", foot.getCenter());
assertEquals("Bottom Right", foot.getRight());
}
/**
* Testcase for Bug 17039 HSSFHeader doesnot support DBCS * Testcase for Bug 17039 HSSFHeader doesnot support DBCS
*/ */
public void testHeaderHas16bitCharacter() throws Exception { public void testHeaderHas16bitCharacter() {
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet("Test"); HSSFSheet s = b.createSheet("Test");
HSSFHeader h = s.getHeader(); HSSFHeader h = s.getHeader();
h.setLeft("\u0391"); h.setLeft("\u0391");
h.setCenter("\u0392"); h.setCenter("\u0392");
h.setRight("\u0393"); h.setRight("\u0393");
ByteArrayOutputStream out = new ByteArrayOutputStream(); HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b);
b.write(out); HSSFHeader h2 = b2.getSheet("Test").getHeader();
HSSFWorkbook b2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); assertEquals(h2.getLeft(),"\u0391");
HSSFHeader h2 = b2.getSheet("Test").getHeader(); assertEquals(h2.getCenter(),"\u0392");
assertEquals(h2.getRight(),"\u0393");
assertEquals(h2.getLeft(),"\u0391");
assertEquals(h2.getCenter(),"\u0392");
assertEquals(h2.getRight(),"\u0393");
} }
/** /**
* Testcase for Bug 17039 HSSFFooter doesnot support DBCS * Testcase for Bug 17039 HSSFFooter doesnot support DBCS
*/ */
public void testFooterHas16bitCharacter() throws Exception{ public void testFooterHas16bitCharacter() {
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet("Test"); HSSFSheet s = b.createSheet("Test");
HSSFFooter f = s.getFooter(); HSSFFooter f = s.getFooter();
f.setLeft("\u0391"); f.setLeft("\u0391");
f.setCenter("\u0392"); f.setCenter("\u0392");
f.setRight("\u0393"); f.setRight("\u0393");
ByteArrayOutputStream out = new ByteArrayOutputStream(); HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b);
b.write(out); HSSFFooter f2 = b2.getSheet("Test").getFooter();
HSSFWorkbook b2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); assertEquals(f2.getLeft(),"\u0391");
HSSFFooter f2 = b2.getSheet("Test").getFooter(); assertEquals(f2.getCenter(),"\u0392");
assertEquals(f2.getRight(),"\u0393");
assertEquals(f2.getLeft(),"\u0391");
assertEquals(f2.getCenter(),"\u0392");
assertEquals(f2.getRight(),"\u0393");
} }
public void testReadDBCSHeaderFooter() throws Exception{ public void testReadDBCSHeaderFooter() {
String readFilename = System.getProperty("HSSF.testdata.path"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSHeader.xls");
FileInputStream in = new FileInputStream(readFilename+File.separator+"DBCSHeader.xls"); HSSFSheet s = wb.getSheetAt(0);
HSSFWorkbook wb = new HSSFWorkbook(in); HSSFHeader h = s.getHeader();
HSSFSheet s = wb.getSheetAt(0); assertEquals("Header Left " ,h.getLeft(),"\u090f\u0915");
HSSFHeader h = s.getHeader(); assertEquals("Header Center " ,h.getCenter(),"\u0939\u094b\u0917\u093e");
assertEquals("Header Left " ,h.getLeft(),"\u090f\u0915"); assertEquals("Header Right " ,h.getRight(),"\u091c\u093e");
assertEquals("Header Center " ,h.getCenter(),"\u0939\u094b\u0917\u093e");
assertEquals("Header Right " ,h.getRight(),"\u091c\u093e");
HSSFFooter f = s.getFooter(); HSSFFooter f = s.getFooter();
assertEquals("Footer Left " ,f.getLeft(),"\u091c\u093e"); assertEquals("Footer Left " ,f.getLeft(),"\u091c\u093e");
assertEquals("Footer Center " ,f.getCenter(),"\u091c\u093e"); assertEquals("Footer Center " ,f.getCenter(),"\u091c\u093e");
assertEquals("Footer Right " ,f.getRight(),"\u091c\u093e"); assertEquals("Footer Right " ,f.getRight(),"\u091c\u093e");
} }
} }

View File

@ -14,28 +14,28 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests HSSFHyperlink. * Tests HSSFHyperlink.
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class TestHSSFHyperlink extends TestCase { public final class TestHSSFHyperlink extends TestCase {
protected String cwd = System.getProperty("HSSF.testdata.path");
/** /**
* Test that we can read hyperlinks. * Test that we can read hyperlinks.
*/ */
public void testRead() throws Exception { public void testRead() {
FileInputStream is = new FileInputStream(new File(cwd, "HyperlinksOnManySheets.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet; HSSFSheet sheet;
HSSFCell cell; HSSFCell cell;
@ -74,9 +74,7 @@ public class TestHSSFHyperlink extends TestCase {
} }
public void testModify() throws Exception { public void testModify() throws Exception {
FileInputStream is = new FileInputStream(new File(cwd, "HyperlinksOnManySheets.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFSheet sheet; HSSFSheet sheet;
HSSFCell cell; HSSFCell cell;
@ -168,10 +166,8 @@ public class TestHSSFHyperlink extends TestCase {
assertEquals("'Target Sheet'!A1", link.getAddress()); assertEquals("'Target Sheet'!A1", link.getAddress());
} }
public void testCloneSheet() throws Exception { public void testCloneSheet() {
FileInputStream is = new FileInputStream(new File(cwd, "HyperlinksOnManySheets.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
HSSFCell cell; HSSFCell cell;
HSSFHyperlink link; HSSFHyperlink link;

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -25,6 +24,8 @@ import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.PaletteRecord; import org.apache.poi.hssf.record.PaletteRecord;
import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
@ -32,15 +33,10 @@ import org.apache.poi.util.TempFile;
/** /**
* @author Brian Sanders (bsanders at risklabs dot com) * @author Brian Sanders (bsanders at risklabs dot com)
*/ */
public class TestHSSFPalette extends TestCase public final class TestHSSFPalette extends TestCase {
{
private PaletteRecord palette; private PaletteRecord palette;
private HSSFPalette hssfPalette; private HSSFPalette hssfPalette;
public TestHSSFPalette(String name)
{
super(name);
}
public void setUp() public void setUp()
{ {
@ -54,12 +50,7 @@ public class TestHSSFPalette extends TestCase
public void testCustomPalette() throws IOException public void testCustomPalette() throws IOException
{ {
//reading sample xls //reading sample xls
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("Simple.xls");
File sample = new File(dir + "/Simple.xls");
assertTrue("Simple.xls exists and is readable", sample.canRead());
FileInputStream fis = new FileInputStream(sample);
HSSFWorkbook book = new HSSFWorkbook(fis);
fis.close();
//creating custom palette //creating custom palette
HSSFPalette palette = book.getCustomPalette(); HSSFPalette palette = book.getCustomPalette();
@ -72,7 +63,7 @@ public class TestHSSFPalette extends TestCase
book.write(fos); book.write(fos);
fos.close(); fos.close();
fis = new FileInputStream(temp); FileInputStream fis = new FileInputStream(temp);
book = new HSSFWorkbook(fis); book = new HSSFWorkbook(fis);
fis.close(); fis.close();
@ -98,13 +89,8 @@ public class TestHSSFPalette extends TestCase
/** /**
* Uses the palette from cell stylings * Uses the palette from cell stylings
*/ */
public void testPaletteFromCellColours() throws Exception { public void testPaletteFromCellColours() {
String dir = System.getProperty("HSSF.testdata.path"); HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("SimpleWithColours.xls");
File sample = new File(dir + "/SimpleWithColours.xls");
assertTrue("SimpleWithColours.xls exists and is readable", sample.canRead());
FileInputStream fis = new FileInputStream(sample);
HSSFWorkbook book = new HSSFWorkbook(fis);
fis.close();
HSSFPalette p = book.getCustomPalette(); HSSFPalette p = book.getCustomPalette();
@ -161,46 +147,46 @@ public class TestHSSFPalette extends TestCase
} }
public void testFindSimilar() throws Exception { public void testFindSimilar() throws Exception {
HSSFWorkbook book = new HSSFWorkbook(); HSSFWorkbook book = new HSSFWorkbook();
HSSFPalette p = book.getCustomPalette(); HSSFPalette p = book.getCustomPalette();
// Add a few edge colours in // Add a few edge colours in
p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0); p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0);
p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0); p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0);
p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1); p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1);
// And some near a few of them // And some near a few of them
p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2); p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2);
p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10); p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10);
p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0); p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0);
p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0); p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0);
assertEquals( assertEquals(
"FFFF:0:0", p.getColor((short)8).getHexString() "FFFF:0:0", p.getColor((short)8).getHexString()
); );
// Now check we get the right stuff back // Now check we get the right stuff back
assertEquals( assertEquals(
p.getColor((short)8).getHexString(), p.getColor((short)8).getHexString(),
p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString() p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)8).getHexString(), p.getColor((short)8).getHexString(),
p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString() p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)8).getHexString(), p.getColor((short)8).getHexString(),
p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString() p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)11).getHexString(), p.getColor((short)11).getHexString(),
p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString() p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString()
); );
assertEquals( assertEquals(
p.getColor((short)12).getHexString(), p.getColor((short)12).getHexString(),
p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString() p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString()
); );
} }
/** /**

View File

@ -17,13 +17,13 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Test <code>HSSFPicture</code>. * Test <code>HSSFPicture</code>.
* *
@ -58,9 +58,8 @@ public final class TestHSSFPicture extends TestCase{
private static byte[] getTestDataFileContent(String fileName) { private static byte[] getTestDataFileContent(String fileName) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
String readFilename = System.getProperty("HSSF.testdata.path");
try { try {
InputStream fis = new FileInputStream(readFilename+File.separator+fileName); InputStream fis = HSSFTestDataSamples.openSampleFileStream(fileName);
byte[] buf = new byte[512]; byte[] buf = new byte[512];
while(true) { while(true) {

View File

@ -15,20 +15,19 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
/*
* HSSFWorkbook.java
*
* Created on September 30, 2001, 3:37 PM
*/
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import junit.framework.TestCase; import junit.framework.TestCase;
import javax.imageio.ImageIO; import org.apache.poi.hssf.HSSFTestDataSamples;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
/** /**
* Test <code>HSSFPictureData</code>. * Test <code>HSSFPictureData</code>.
@ -37,14 +36,11 @@ import java.awt.image.BufferedImage;
* @author Yegor Kozlov (yegor at apache dot org) * @author Yegor Kozlov (yegor at apache dot org)
* @author Trejkaz (trejkaz at trypticon dot org) * @author Trejkaz (trejkaz at trypticon dot org)
*/ */
public class TestHSSFPictureData extends TestCase{ public final class TestHSSFPictureData extends TestCase{
static String cwd = System.getProperty("HSSF.testdata.path");
public void testPictures() throws IOException { public void testPictures() throws IOException {
FileInputStream is = new FileInputStream(new File(cwd, "SimpleWithImages.xls")); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls");
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
List lst = wb.getAllPictures(); List lst = wb.getAllPictures();
//assertEquals(2, lst.size()); //assertEquals(2, lst.size());
@ -69,6 +65,5 @@ public class TestHSSFPictureData extends TestCase{
//TODO: test code for PICT, WMF and EMF //TODO: test code for PICT, WMF and EMF
} }
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -14,28 +14,22 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import junit.framework.*; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.NameRecord; import org.apache.poi.hssf.record.NameRecord;
/**
*
*/
public final class TestHSSFWorkbook extends TestCase {
private static HSSFWorkbook openSample(String sampleFileName) {
return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
}
public class TestHSSFWorkbook extends TestCase public void testSetRepeatingRowsAndColumns() {
{
HSSFWorkbook hssfWorkbook;
String filename;
protected void setUp() throws Exception {
super.setUp();
filename = System.getProperty("HSSF.testdata.path");
}
public void testSetRepeatingRowsAndColumns() throws Exception
{
// Test bug 29747 // Test bug 29747
HSSFWorkbook b = new HSSFWorkbook( ); HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet(); b.createSheet();
@ -46,9 +40,7 @@ public class TestHSSFWorkbook extends TestCase
assertEquals( 3, nameRecord.getIndexToSheet() ); assertEquals( 3, nameRecord.getIndexToSheet() );
} }
public void testDuplicateNames() public void testDuplicateNames() {
throws Exception
{
HSSFWorkbook b = new HSSFWorkbook( ); HSSFWorkbook b = new HSSFWorkbook( );
b.createSheet("Sheet1"); b.createSheet("Sheet1");
b.createSheet(); b.createSheet();
@ -105,15 +97,15 @@ public class TestHSSFWorkbook extends TestCase
public void testSheetSelection() { public void testSheetSelection() {
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
b.createSheet("Sheet One"); b.createSheet("Sheet One");
HSSFSheet s = b.createSheet("Sheet Two"); b.createSheet("Sheet Two");
b.setSelectedTab((short) 1); b.setSelectedTab((short) 1);
b.setDisplayedTab((short) 1); b.setDisplayedTab((short) 1);
assertEquals(b.getSelectedTab(), 1); assertEquals(b.getSelectedTab(), 1);
assertEquals(b.getDisplayedTab(), 1); assertEquals(b.getDisplayedTab(), 1);
} }
public void testSheetClone() throws Exception { public void testSheetClone() {
// First up, try a simple file // First up, try a simple file
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
assertEquals(0, b.getNumberOfSheets()); assertEquals(0, b.getNumberOfSheets());
b.createSheet("Sheet One"); b.createSheet("Sheet One");
@ -123,23 +115,19 @@ public class TestHSSFWorkbook extends TestCase
b.cloneSheet(0); b.cloneSheet(0);
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
// Now try a problem one with drawing records in it // Now try a problem one with drawing records in it
b = new HSSFWorkbook( b = openSample("SheetWithDrawing.xls");
new FileInputStream(new File(filename,"SheetWithDrawing.xls"))
);
assertEquals(1, b.getNumberOfSheets()); assertEquals(1, b.getNumberOfSheets());
b.cloneSheet(0); b.cloneSheet(0);
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
} }
public void testReadWriteWithCharts() throws Exception { public void testReadWriteWithCharts() {
HSSFWorkbook b; HSSFWorkbook b;
HSSFSheet s; HSSFSheet s;
// Single chart, two sheets // Single chart, two sheets
b = new HSSFWorkbook( b = openSample("44010-SingleChart.xls");
new FileInputStream(new File(filename,"44010-SingleChart.xls"))
);
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
s = b.getSheetAt(1); s = b.getSheetAt(1);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
@ -154,9 +142,7 @@ public class TestHSSFWorkbook extends TestCase
// We've now called getDrawingPatriarch() so // We've now called getDrawingPatriarch() so
// everything will be all screwy // everything will be all screwy
// So, start again // So, start again
b = new HSSFWorkbook( b = openSample("44010-SingleChart.xls");
new FileInputStream(new File(filename,"44010-SingleChart.xls"))
);
b = writeRead(b); b = writeRead(b);
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b.getNumberOfSheets());
@ -166,9 +152,7 @@ public class TestHSSFWorkbook extends TestCase
// Two charts, three sheets // Two charts, three sheets
b = new HSSFWorkbook( b = openSample("44010-TwoCharts.xls");
new FileInputStream(new File(filename,"44010-TwoCharts.xls"))
);
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
s = b.getSheetAt(1); s = b.getSheetAt(1);
@ -188,9 +172,7 @@ public class TestHSSFWorkbook extends TestCase
// We've now called getDrawingPatriarch() so // We've now called getDrawingPatriarch() so
// everything will be all screwy // everything will be all screwy
// So, start again // So, start again
b = new HSSFWorkbook( b = openSample("44010-TwoCharts.xls");
new FileInputStream(new File(filename,"44010-TwoCharts.xls"))
);
b = writeRead(b); b = writeRead(b);
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b.getNumberOfSheets());
@ -203,11 +185,7 @@ public class TestHSSFWorkbook extends TestCase
assertEquals(0, s.getLastRowNum()); assertEquals(0, s.getLastRowNum());
} }
private HSSFWorkbook writeRead(HSSFWorkbook b) throws Exception { private static HSSFWorkbook writeRead(HSSFWorkbook b) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); return HSSFTestDataSamples.writeOutAndReadBack(b);
b.write(baos);
return new HSSFWorkbook(
new ByteArrayInputStream(baos.toByteArray())
);
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,16 +15,8 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.hssf.util.AreaReference;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.TempFile;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -33,6 +24,12 @@ import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.util.AreaReference;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.util.TempFile;
/** /**
* *
@ -41,115 +38,69 @@ import java.io.IOException;
* @author Danny Mui (danny at muibros.com) * @author Danny Mui (danny at muibros.com)
* @author Amol S. Deshmukh &lt; amol at ap ache dot org &gt; * @author Amol S. Deshmukh &lt; amol at ap ache dot org &gt;
*/ */
public class TestNamedRange public final class TestNamedRange extends TestCase {
extends TestCase {
public TestNamedRange(String testName) { private static HSSFWorkbook openSample(String sampleFileName) {
super(testName); return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
} }
public static void main(java.lang.String[] args) { public static void main(String[] args) {
String filename = System.getProperty("HSSF.testdata.path"); junit.textui.TestRunner.run(TestNamedRange.class);
}
// assume andy is running this in the debugger /** Test of TestCase method, of class test.RangeTest. */
if (filename == null) public void testNamedRange()
{ throws IOException
if (args != null && args.length == 1) {
System.setProperty(
"HSSF.testdata.path",
args[0]);
} else {
System.err.println("Geesh, no HSSF.testdata.path system " +
"property, no command line arg with the path "+
"what do you expect me to do, guess where teh data " +
"files are? Sorry, I give up!");
}
}
junit.textui.TestRunner.run(TestNamedRange.class);
}
/** Test of TestCase method, of class test.RangeTest. */
public void testNamedRange()
throws IOException
{
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Simple.xls";
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
wb = new HSSFWorkbook(fs);
//Creating new Named Range
HSSFName newNamedRange = wb.createName();
//Getting Sheet Name for the reference
String sheetName = wb.getSheetName(0);
//Setting its name
newNamedRange.setNameName("RangeTest");
//Setting its reference
newNamedRange.setReference(sheetName + "!$D$4:$E$8");
//Getting NAmed Range
HSSFName namedRange1 = wb.getNameAt(0);
//Getting it sheet name
sheetName = namedRange1.getSheetName();
//Getting its reference
String referece = namedRange1.getReference();
// sanity check
SanityChecker c = new SanityChecker();
c.checkHSSFWorkbook(wb);
File file = TempFile.createTempFile("testNamedRange",
".xls");
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fis.close();
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference());
}
/**
* Reads an excel file already containing a named range.
* <p>
* Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=9632" target="_bug">#9632</a>
*/
public void testNamedRead() throws IOException
{ {
FileInputStream fis = null; HSSFWorkbook wb = openSample("Simple.xls");
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
String filename = System.getProperty("HSSF.testdata.path"); //Creating new Named Range
HSSFName newNamedRange = wb.createName();
filename = filename + "/namedinput.xls"; //Getting Sheet Name for the reference
String sheetName = wb.getSheetName(0);
//Setting its name
newNamedRange.setNameName("RangeTest");
//Setting its reference
newNamedRange.setReference(sheetName + "!$D$4:$E$8");
//Getting NAmed Range
HSSFName namedRange1 = wb.getNameAt(0);
//Getting it sheet name
sheetName = namedRange1.getSheetName();
//Getting its reference
String referece = namedRange1.getReference();
// sanity check
SanityChecker c = new SanityChecker();
c.checkHSSFWorkbook(wb);
File file = TempFile.createTempFile("testNamedRange", ".xls");
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file);
wb = new HSSFWorkbook(in);
HSSFName nm =wb.getNameAt(wb.getNameIndex("RangeTest"));
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertEquals(wb.getSheetName(0)+"!$D$4:$E$8", nm.getReference());
fis = new FileInputStream(filename); }
fs = new POIFSFileSystem(fis);
wb = new HSSFWorkbook(fs); /**
* Reads an excel file already containing a named range.
* <p>
* Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=9632" target="_bug">#9632</a>
*/
public void testNamedRead() {
HSSFWorkbook wb = openSample("namedinput.xls");
//Get index of the namedrange with the name = "NamedRangeName" , which was defined in input.xls as A1:D10 //Get index of the namedrange with the name = "NamedRangeName" , which was defined in input.xls as A1:D10
int NamedRangeIndex = wb.getNameIndex("NamedRangeName"); int NamedRangeIndex = wb.getNameIndex("NamedRangeName");
@ -161,37 +112,21 @@ public class TestNamedRange
//Getting its reference //Getting its reference
String reference = namedRange1.getReference(); String reference = namedRange1.getReference();
fis.close();
assertEquals(sheetName+"!$A$1:$D$10", reference); assertEquals(sheetName+"!$A$1:$D$10", reference);
HSSFName namedRange2 = wb.getNameAt(1); HSSFName namedRange2 = wb.getNameAt(1);
assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getReference()); assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getReference());
assertEquals("SecondNamedRange", namedRange2.getNameName()); assertEquals("SecondNamedRange", namedRange2.getNameName());
} }
/** /**
* Reads an excel file already containing a named range and updates it * Reads an excel file already containing a named range and updates it
* <p> * <p>
* Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=16411" target="_bug">#16411</a> * Addresses Bug <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=16411" target="_bug">#16411</a>
*/ */
public void testNamedReadModify() throws IOException public void testNamedReadModify() {
{ HSSFWorkbook wb = openSample("namedinput.xls");
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/namedinput.xls";
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
wb = new HSSFWorkbook(fs);
HSSFName name = wb.getNameAt(0); HSSFName name = wb.getNameAt(0);
String sheetName = wb.getSheetName(0); String sheetName = wb.getSheetName(0);
@ -203,40 +138,39 @@ public class TestNamedRange
name.setReference(newReference); name.setReference(newReference);
assertEquals(newReference, name.getReference()); assertEquals(newReference, name.getReference());
}
}
/** /**
* Test that multiple named ranges can be added written and read * Test that multiple named ranges can be added written and read
*/ */
public void testMultipleNamedWrite() public void testMultipleNamedWrite()
throws IOException throws IOException
{ {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("testSheet1"); HSSFSheet sheet = wb.createSheet("testSheet1");
String sheetName = wb.getSheetName(0); String sheetName = wb.getSheetName(0);
assertEquals("testSheet1", sheetName); assertEquals("testSheet1", sheetName);
//Creating new Named Range //Creating new Named Range
HSSFName newNamedRange = wb.createName(); HSSFName newNamedRange = wb.createName();
newNamedRange.setNameName("RangeTest"); newNamedRange.setNameName("RangeTest");
newNamedRange.setReference(sheetName + "!$D$4:$E$8"); newNamedRange.setReference(sheetName + "!$D$4:$E$8");
//Creating another new Named Range //Creating another new Named Range
HSSFName newNamedRange2 = wb.createName(); HSSFName newNamedRange2 = wb.createName();
newNamedRange2.setNameName("AnotherTest"); newNamedRange2.setNameName("AnotherTest");
newNamedRange2.setReference(sheetName + "!$F$1:$G$6"); newNamedRange2.setReference(sheetName + "!$F$1:$G$6");
HSSFName namedRange1 = wb.getNameAt(0); HSSFName namedRange1 = wb.getNameAt(0);
String referece = namedRange1.getReference(); String referece = namedRange1.getReference();
File file = TempFile.createTempFile("testMultiNamedRange", ".xls"); File file = TempFile.createTempFile("testMultiNamedRange", ".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut); wb.write(fileOut);
@ -252,9 +186,9 @@ public class TestNamedRange
assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),(wb.getSheetName(0)+"!$D$4:$E$8").equals(nm.getReference())); assertTrue("Reference is "+nm.getReference(),(wb.getSheetName(0)+"!$D$4:$E$8").equals(nm.getReference()));
nm = wb.getNameAt(wb.getNameIndex("AnotherTest")); nm = wb.getNameAt(wb.getNameIndex("AnotherTest"));
assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName())); assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName()));
assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference())); assertTrue("Reference is "+nm.getReference(),newNamedRange2.getReference().equals(nm.getReference()));
} }
@ -320,20 +254,20 @@ public class TestNamedRange
} }
public void testUnicodeNamedRange() throws Exception { public void testUnicodeNamedRange() throws Exception {
HSSFWorkbook workBook = new HSSFWorkbook(); HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("Test"); HSSFSheet sheet = workBook.createSheet("Test");
HSSFName name = workBook.createName(); HSSFName name = workBook.createName();
name.setNameName("\u03B1"); name.setNameName("\u03B1");
name.setReference("Test!$D$3:$E$8"); name.setReference("Test!$D$3:$E$8");
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
workBook.write(out); workBook.write(out);
HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray())); HSSFWorkbook workBook2 = new HSSFWorkbook(new ByteArrayInputStream(out.toByteArray()));
HSSFName name2 = workBook2.getNameAt(0); HSSFName name2 = workBook2.getNameAt(0);
assertEquals("\u03B1", name2.getNameName()); assertEquals("\u03B1", name2.getNameName());
assertEquals("Test!$D$3:$E$8", name2.getReference()); assertEquals("Test!$D$3:$E$8", name2.getReference());
} }
/** /**
@ -341,17 +275,17 @@ public class TestNamedRange
*/ */
public void testSinglePrintArea() public void testSinglePrintArea()
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$B$1"; String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
} }
@ -378,35 +312,13 @@ public class TestNamedRange
/** /**
* Test to see if the print area can be retrieved from an excel created file * Test to see if the print area can be retrieved from an excel created file
*/ */
public void testPrintAreaFileRead() public void testPrintAreaFileRead() {
throws IOException HSSFWorkbook workbook = openSample("SimpleWithPrintArea.xls");
{
FileInputStream fis = null;
POIFSFileSystem fs = null;
HSSFWorkbook workbook = null;
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithPrintArea.xls";
try {
fis = new FileInputStream(filename);
fs = new POIFSFileSystem(fis);
workbook = new HSSFWorkbook(fs);
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$C$5";
assertEquals(reference, workbook.getPrintArea(0));
} finally {
fis.close();
}
String sheetName = workbook.getSheetName(0);
String reference = sheetName+"!$A$1:$C$5";
assertEquals(reference, workbook.getPrintArea(0));
} }
@ -424,16 +336,16 @@ public class TestNamedRange
String reference = sheetName+"!$A$1:$B$1"; String reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
File file = TempFile.createTempFile("testPrintArea",".xls"); File file = TempFile.createTempFile("testPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut); workbook.write(fileOut);
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in); workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
@ -447,57 +359,57 @@ public class TestNamedRange
public void testMultiplePrintAreaFile() public void testMultiplePrintAreaFile()
throws IOException throws IOException
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1"); HSSFSheet sheet = workbook.createSheet("Sheet1");
sheet = workbook.createSheet("Sheet2"); sheet = workbook.createSheet("Sheet2");
sheet = workbook.createSheet("Sheet3"); sheet = workbook.createSheet("Sheet3");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = null; String reference = null;
reference = sheetName+"!$A$1:$B$1"; reference = sheetName+"!$A$1:$B$1";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
sheetName = workbook.getSheetName(1); sheetName = workbook.getSheetName(1);
String reference2 = sheetName+"!$B$2:$D$5"; String reference2 = sheetName+"!$B$2:$D$5";
workbook.setPrintArea(1, reference2); workbook.setPrintArea(1, reference2);
sheetName = workbook.getSheetName(2); sheetName = workbook.getSheetName(2);
String reference3 = sheetName+"!$D$2:$F$5"; String reference3 = sheetName+"!$D$2:$F$5";
workbook.setPrintArea(2, reference3); workbook.setPrintArea(2, reference3);
File file = TempFile.createTempFile("testMultiPrintArea",".xls"); File file = TempFile.createTempFile("testMultiPrintArea",".xls");
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut); workbook.write(fileOut);
fileOut.close(); fileOut.close();
assertTrue("file exists",file.exists()); assertTrue("file exists",file.exists());
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
workbook = new HSSFWorkbook(in); workbook = new HSSFWorkbook(in);
String retrievedPrintArea = workbook.getPrintArea(0); String retrievedPrintArea = workbook.getPrintArea(0);
assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea);
assertEquals(reference, retrievedPrintArea); assertEquals(reference, retrievedPrintArea);
String retrievedPrintArea2 = workbook.getPrintArea(1); String retrievedPrintArea2 = workbook.getPrintArea(1);
assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2); assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea2);
assertEquals(reference2, retrievedPrintArea2); assertEquals(reference2, retrievedPrintArea2);
String retrievedPrintArea3 = workbook.getPrintArea(2); String retrievedPrintArea3 = workbook.getPrintArea(2);
assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3); assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea3);
assertEquals(reference3, retrievedPrintArea3); assertEquals(reference3, retrievedPrintArea3);
} }
/** /**
* Tests the setting of print areas with coordinates (Row/Column designations) * Tests the setting of print areas with coordinates (Row/Column designations)
* *
*/ */
public void testPrintAreaCoords(){ public void testPrintAreaCoords(){
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
@ -509,20 +421,20 @@ public class TestNamedRange
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea);
} }
/** /**
* Tests the parsing of union area expressions, and re-display in the presence of sheet names * Tests the parsing of union area expressions, and re-display in the presence of sheet names
* with special characters. * with special characters.
*/ */
public void testPrintAreaUnion(){ public void testPrintAreaUnion(){
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
String reference = sheetName + "!$A$1:$B$1, " + sheetName + "!$D$1:$F$2"; String reference = sheetName + "!$A$1:$B$1, " + sheetName + "!$D$1:$F$2";
String expResult = "'" + sheetName + "'!$A$1:$B$1,'" + sheetName + "'!$D$1:$F$2"; String expResult = "'" + sheetName + "'!$A$1:$B$1,'" + sheetName + "'!$D$1:$F$2";
workbook.setPrintArea(0, reference); workbook.setPrintArea(0, reference);
@ -530,13 +442,13 @@ public class TestNamedRange
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
assertEquals(expResult, retrievedPrintArea); assertEquals(expResult, retrievedPrintArea);
} }
/** /**
* Verifies an existing print area is deleted * Verifies an existing print area is deleted
* *
*/ */
public void testPrintAreaRemove() { public void testPrintAreaRemove() {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Area"); HSSFSheet sheet = workbook.createSheet("Test Print Area");
String sheetName = workbook.getSheetName(0); String sheetName = workbook.getSheetName(0);
@ -548,79 +460,77 @@ public class TestNamedRange
assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); assertNotNull("Print Area not defined for first sheet", retrievedPrintArea);
workbook.removePrintArea(0); workbook.removePrintArea(0);
assertNull("PrintArea was not removed", workbook.getPrintArea(0)); assertNull("PrintArea was not removed", workbook.getPrintArea(0));
} }
/** /**
* Verifies correct functioning for "single cell named range" (aka "named cell") * Verifies correct functioning for "single cell named range" (aka "named cell")
*/ */
public void testNamedCell_1() { public void testNamedCell_1() {
// setup for this testcase // setup for this testcase
String sheetName = "Test Named Cell"; String sheetName = "Test Named Cell";
String cellName = "A name for a named cell"; String cellName = "A name for a named cell";
String cellValue = "TEST Value"; String cellValue = "TEST Value";
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName); HSSFSheet sheet = wb.createSheet(sheetName);
sheet.createRow(0).createCell((short) 0).setCellValue(cellValue); sheet.createRow(0).createCell((short) 0).setCellValue(cellValue);
// create named range for a single cell using areareference // create named range for a single cell using areareference
HSSFName namedCell = wb.createName(); HSSFName namedCell = wb.createName();
namedCell.setNameName(cellName); namedCell.setNameName(cellName);
String reference = sheetName+"!A1:A1"; String reference = sheetName+"!A1:A1";
namedCell.setReference(reference); namedCell.setReference(reference);
// retrieve the newly created named range // retrieve the newly created named range
int namedCellIdx = wb.getNameIndex(cellName); int namedCellIdx = wb.getNameIndex(cellName);
HSSFName aNamedCell = wb.getNameAt(namedCellIdx); HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
assertNotNull(aNamedCell); assertNotNull(aNamedCell);
// retrieve the cell at the named range and test its contents // retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getReference()); AreaReference aref = new AreaReference(aNamedCell.getReference());
assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell()); assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell());
CellReference cref = aref.getFirstCell(); CellReference cref = aref.getFirstCell();
assertNotNull(cref); assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName()); HSSFSheet s = wb.getSheet(cref.getSheetName());
assertNotNull(s); assertNotNull(s);
HSSFRow r = sheet.getRow(cref.getRow()); HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol()); HSSFCell c = r.getCell(cref.getCol());
String contents = c.getRichStringCellValue().getString(); String contents = c.getRichStringCellValue().getString();
assertEquals("Contents of cell retrieved by its named reference", contents, cellValue); assertEquals("Contents of cell retrieved by its named reference", contents, cellValue);
} }
/** /**
* Verifies correct functioning for "single cell named range" (aka "named cell") * Verifies correct functioning for "single cell named range" (aka "named cell")
*/ */
public void testNamedCell_2() { public void testNamedCell_2() {
// setup for this testcase // setup for this testcase
String sname = "TestSheet", cname = "TestName", cvalue = "TestVal"; String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sname); HSSFSheet sheet = wb.createSheet(sname);
sheet.createRow(0).createCell((short) 0).setCellValue(cvalue); sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);
// create named range for a single cell using cellreference // create named range for a single cell using cellreference
HSSFName namedCell = wb.createName(); HSSFName namedCell = wb.createName();
namedCell.setNameName(cname); namedCell.setNameName(cname);
String reference = sname+"!A1"; String reference = sname+"!A1";
namedCell.setReference(reference); namedCell.setReference(reference);
// retrieve the newly created named range // retrieve the newly created named range
int namedCellIdx = wb.getNameIndex(cname); int namedCellIdx = wb.getNameIndex(cname);
HSSFName aNamedCell = wb.getNameAt(namedCellIdx); HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
assertNotNull(aNamedCell); assertNotNull(aNamedCell);
// retrieve the cell at the named range and test its contents
CellReference cref = new CellReference(aNamedCell.getReference());
assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName());
HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol());
String contents = c.getStringCellValue();
assertEquals("Contents of cell retrieved by its named reference", contents, cvalue);
}
// retrieve the cell at the named range and test its contents
CellReference cref = new CellReference(aNamedCell.getReference());
assertNotNull(cref);
HSSFSheet s = wb.getSheet(cref.getSheetName());
HSSFRow r = sheet.getRow(cref.getRow());
HSSFCell c = r.getCell(cref.getCol());
String contents = c.getStringCellValue();
assertEquals("Contents of cell retrieved by its named reference", contents, cvalue);
}
} }

View File

@ -17,36 +17,28 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
public class TestOLE2Embeding extends TestCase { import org.apache.poi.hssf.HSSFTestDataSamples;
public void testEmbeding() throws Exception {
String dirname = System.getProperty("HSSF.testdata.path");
String filename = dirname + "/ole2-embedding.xls";
File file = new File(filename); /**
FileInputStream in = new FileInputStream(file); *
HSSFWorkbook workbook; */
public final class TestOLE2Embeding extends TestCase {
public void testEmbeding() {
// This used to break, until bug #43116 was fixed // This used to break, until bug #43116 was fixed
workbook = new HSSFWorkbook(in); HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls");
in.close();
// Check we can get at the Escher layer still // Check we can get at the Escher layer still
workbook.getAllPictures(); workbook.getAllPictures();
} }
public void testEmbeddedObjects() throws Exception { public void testEmbeddedObjects() throws Exception {
String dirname = System.getProperty("HSSF.testdata.path"); HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls");
String filename = dirname + "/ole2-embedding.xls";
File file = new File(filename);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
List objects = workbook.getAllEmbeddedObjects(); List objects = workbook.getAllEmbeddedObjects();
assertEquals("Wrong number of objects", 2, objects.size()); assertEquals("Wrong number of objects", 2, objects.size());
assertEquals("Wrong name for first object", "MBD06CAB431", assertEquals("Wrong name for first object", "MBD06CAB431",
@ -56,6 +48,5 @@ public class TestOLE2Embeding extends TestCase {
((HSSFObjectData) ((HSSFObjectData)
objects.get(1)).getDirectory().getName()); objects.get(1)).getDirectory().getName());
} }
} }

View File

@ -17,32 +17,31 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hpsf.PropertySetFactory;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Old-style setting of POIFS properties doesn't work with POI 3.0.2 * Old-style setting of POIFS properties doesn't work with POI 3.0.2
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class TestPOIFSProperties extends TestCase{ public class TestPOIFSProperties extends TestCase{
protected String cwd = System.getProperty("HSSF.testdata.path");
protected String title = "Testing POIFS properties"; private static final String title = "Testing POIFS properties";
public void testFail() throws Exception { public void testFail() throws Exception {
FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls")); InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFWorkbook wb = new HSSFWorkbook(fs);
@ -62,19 +61,13 @@ public class TestPOIFSProperties extends TestCase{
POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
try { //failing assertion
//failing assertion assertEquals(title, summary2.getTitle());
assertEquals(title, summary2.getTitle());
} catch (AssertionError e){
assertTrue(true);
}
} }
public void testOK() throws Exception { public void testOK() throws Exception {
FileInputStream is = new FileInputStream(new File(cwd, "Simple.xls")); InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
//set POIFS properties before constructing HSSFWorkbook //set POIFS properties before constructing HSSFWorkbook
SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,46 +15,28 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Sheet; import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.EOFRecord; import org.apache.poi.hssf.record.EOFRecord;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.FileInputStream;
import java.util.GregorianCalendar;
import java.util.List;
/** /**
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public final class TestReadWriteChart extends TestCase {
public class TestReadWriteChart
extends TestCase
{
public TestReadWriteChart(String s)
{
super(s);
}
/** /**
* In the presence of a chart we need to make sure BOF/EOF records still exist. * In the presence of a chart we need to make sure BOF/EOF records still exist.
*/ */
public void testBOFandEOFRecords() {
public void testBOFandEOFRecords() HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls");
throws Exception
{
//System.out.println("made it in testBOFandEOF");
String path = System.getProperty("HSSF.testdata.path");
String filename = path + "/SimpleChart.xls";
//System.out.println("path is "+path);
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream(filename));
//System.out.println("opened file");
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow firstRow = sheet.getRow(0); HSSFRow firstRow = sheet.getRow(0);
HSSFCell firstCell = firstRow.getCell(( short ) 0); HSSFCell firstCell = firstRow.getCell(( short ) 0);
@ -77,29 +58,7 @@ public class TestReadWriteChart
assertTrue(records.get(records.size() - 1) instanceof EOFRecord); assertTrue(records.get(records.size() - 1) instanceof EOFRecord);
} }
public static void main(String [] args) public static void main(String [] args) {
{
String filename = System.getProperty("HSSF.testdata.path");
// assume andy is running this in the debugger
if (filename == null)
{
if (args != null && args[0].length() == 1) {
System.setProperty(
"HSSF.testdata.path",
args[0]);
} else {
System.err.println("Geesh, no HSSF.testdata.path system " +
"property, no command line arg with the path "+
"what do you expect me to do, guess where teh data " +
"files are? Sorry, I give up!");
}
}
System.out
.println("Testing org.apache.poi.hssf.usermodel.TestReadWriteChart");
junit.textui.TestRunner.run(TestReadWriteChart.class); junit.textui.TestRunner.run(TestReadWriteChart.class);
} }
} }

View File

@ -14,40 +14,28 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests for how HSSFWorkbook behaves with XLS files * Tests for how HSSFWorkbook behaves with XLS files
* with a WORKBOOK directory entry (instead of the more * with a WORKBOOK directory entry (instead of the more
* usual, Workbook) * usual, Workbook)
*/ */
public class TestSheetHiding extends TestCase { public final class TestSheetHiding extends TestCase {
private String dirPath;
private String xlsHidden = "TwoSheetsOneHidden.xls";
private String xlsShown = "TwoSheetsNoneHidden.xls";
private HSSFWorkbook wbH; private HSSFWorkbook wbH;
private HSSFWorkbook wbU; private HSSFWorkbook wbU;
protected void setUp() throws Exception { protected void setUp() {
super.setUp(); wbH = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsOneHidden.xls");
wbU = HSSFTestDataSamples.openSampleWorkbook("TwoSheetsNoneHidden.xls");
dirPath = System.getProperty("HSSF.testdata.path");
FileInputStream isH = new FileInputStream(dirPath + "/" + xlsHidden);
POIFSFileSystem fsH = new POIFSFileSystem(isH);
FileInputStream isU = new FileInputStream(dirPath + "/" + xlsShown);
POIFSFileSystem fsU = new POIFSFileSystem(isU);
wbH = new HSSFWorkbook(fsH);
wbU = new HSSFWorkbook(fsU);
} }
/** /**

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,19 +15,14 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.TempFile;
import java.io.File;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests row shifting capabilities. * Tests row shifting capabilities.
@ -37,16 +31,7 @@ import java.io.FileOutputStream;
* @author Shawn Laubach (slaubach at apache dot com) * @author Shawn Laubach (slaubach at apache dot com)
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public final class TestSheetShiftRows extends TestCase {
public class TestSheetShiftRows extends TestCase {
/**
* Constructor for TestSheetShiftRows.
* @param arg0
*/
public TestSheetShiftRows(String arg0) {
super(arg0);
}
/** /**
* Tests the shiftRows function. Does three different shifts. * Tests the shiftRows function. Does three different shifts.
@ -59,25 +44,16 @@ public class TestSheetShiftRows extends TestCase {
public void testShiftRows() throws Exception public void testShiftRows() throws Exception
{ {
// Read initial file in // Read initial file in
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls");
filename = filename + "/SimpleMultiCell.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet s = wb.getSheetAt( 0 ); HSSFSheet s = wb.getSheetAt( 0 );
// Shift the second row down 1 and write to temp file // Shift the second row down 1 and write to temp file
s.shiftRows( 1, 1, 1 ); s.shiftRows( 1, 1, 1 );
File tempFile = TempFile.createTempFile( "shift", "test.xls" );
FileOutputStream fout = new FileOutputStream( tempFile ); wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
wb.write( fout );
fout.close();
// Read from temp file and check the number of cells in each // Read from temp file and check the number of cells in each
// row (in original file each row was unique) // row (in original file each row was unique)
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 1 ); assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 1 );
@ -89,15 +65,9 @@ public class TestSheetShiftRows extends TestCase {
// Shift rows 1-3 down 3 in the current one. This tests when // Shift rows 1-3 down 3 in the current one. This tests when
// 1 row is blank. Write to a another temp file // 1 row is blank. Write to a another temp file
s.shiftRows( 0, 2, 3 ); s.shiftRows( 0, 2, 3 );
tempFile = TempFile.createTempFile( "shift", "test.xls" ); wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
// Read and ensure things are where they should be // Read and ensure things are where they should be
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertTrue( s.getRow( 0 ) == null || s.getRow( 0 ).getPhysicalNumberOfCells() == 0 ); assertTrue( s.getRow( 0 ) == null || s.getRow( 0 ).getPhysicalNumberOfCells() == 0 );
assertTrue( s.getRow( 1 ) == null || s.getRow( 1 ).getPhysicalNumberOfCells() == 0 ); assertTrue( s.getRow( 1 ) == null || s.getRow( 1 ).getPhysicalNumberOfCells() == 0 );
@ -107,22 +77,12 @@ public class TestSheetShiftRows extends TestCase {
assertEquals( s.getRow( 5 ).getPhysicalNumberOfCells(), 2 ); assertEquals( s.getRow( 5 ).getPhysicalNumberOfCells(), 2 );
// Read the first file again // Read the first file again
fin = new FileInputStream( filename ); wb = HSSFTestDataSamples.openSampleWorkbook("SimpleMultiCell.xls");
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
// Shift rows 3 and 4 up and write to temp file // Shift rows 3 and 4 up and write to temp file
s.shiftRows( 2, 3, -2 ); s.shiftRows( 2, 3, -2 );
tempFile = TempFile.createTempFile( "shift", "test.xls" ); wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
fout = new FileOutputStream( tempFile );
wb.write( fout );
fout.close();
// Read file and test
fin = new FileInputStream( tempFile );
wb = new HSSFWorkbook( fin );
fin.close();
s = wb.getSheetAt( 0 ); s = wb.getSheetAt( 0 );
assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 3 ); assertEquals( s.getRow( 0 ).getPhysicalNumberOfCells(), 3 );
assertEquals( s.getRow( 1 ).getPhysicalNumberOfCells(), 4 ); assertEquals( s.getRow( 1 ).getPhysicalNumberOfCells(), 4 );
@ -137,11 +97,11 @@ public class TestSheetShiftRows extends TestCase {
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public void testShiftRow(){ public void testShiftRow(){
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet(); HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1"); s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2"); s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
} }
/** /**
@ -150,11 +110,11 @@ public class TestSheetShiftRows extends TestCase {
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public void testShiftRow0(){ public void testShiftRow0(){
HSSFWorkbook b = new HSSFWorkbook(); HSSFWorkbook b = new HSSFWorkbook();
HSSFSheet s = b.createSheet(); HSSFSheet s = b.createSheet();
s.createRow(0).createCell((short)0).setCellValue("TEST1"); s.createRow(0).createCell((short)0).setCellValue("TEST1");
s.createRow(3).createCell((short)0).setCellValue("TEST2"); s.createRow(3).createCell((short)0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
} }
/** /**
@ -175,11 +135,7 @@ public class TestSheetShiftRows extends TestCase {
public void testShiftWithComments() throws Exception { public void testShiftWithComments() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("comments.xls");
filename = filename + "/comments.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet sheet = wb.getSheet("Sheet1"); HSSFSheet sheet = wb.getSheet("Sheet1");
assertEquals(3, sheet.getLastRowNum()); assertEquals(3, sheet.getLastRowNum());
@ -241,12 +197,8 @@ public class TestSheetShiftRows extends TestCase {
/** /**
* See bug #34023 * See bug #34023
*/ */
public void testShiftWithFormulas() throws Exception { public void testShiftWithFormulas() {
String filename = System.getProperty( "HSSF.testdata.path" ); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ForShifting.xls");
filename = filename + "/ForShifting.xls";
FileInputStream fin = new FileInputStream( filename );
HSSFWorkbook wb = new HSSFWorkbook( fin );
fin.close();
HSSFSheet sheet = wb.getSheet("Sheet1"); HSSFSheet sheet = wb.getSheet("Sheet1");
assertEquals(19, sheet.getLastRowNum()); assertEquals(19, sheet.getLastRowNum());

View File

@ -14,43 +14,36 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import junit.framework.AssertionFailedError;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.RecordFormatException;
/** /**
* @author aviks * @author aviks
* *
* This testcase contains tests for bugs that are yet to be fixed. * This testcase contains tests for bugs that are yet to be fixed. Therefore,
* Therefore, the standard ant test target does not run these tests. * the standard ant test target does not run these tests. Run this testcase with
* Run this testcase with the single-test target. * the single-test target. The names of the tests usually correspond to the
* The names of the tests usually correspond to the Bugzilla id's * Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are
* PLEASE MOVE tests from this class to TestBugs once the bugs are fixed, * fixed, so that they are then run automatically.
* so that they are then run automatically.
*/ */
public class TestUnfixedBugs extends TestCase { public final class TestUnfixedBugs extends TestCase {
public TestUnfixedBugs(String arg0) {
super(arg0);
public void test43493() {
// Has crazy corrupt sub-records on
// a EmbeddedObjectRefSubRecord
try {
HSSFTestDataSamples.openSampleWorkbook("43493.xls");
} catch (RecordFormatException e) {
if (e.getCause().getCause() instanceof ArrayIndexOutOfBoundsException) {
throw new AssertionFailedError("Identified bug 43493");
}
throw e;
}
} }
protected String cwd = System.getProperty("HSSF.testdata.path");
public void test43493() throws Exception {
// Has crazy corrup subrecords on
// a EmbeddedObjectRefSubRecord
File f = new File(cwd, "43493.xls");
HSSFWorkbook wb = new HSSFWorkbook(
new FileInputStream(f)
);
}
} }

View File

@ -14,37 +14,33 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/** /**
* Tests for how HSSFWorkbook behaves with XLS files * Tests for how HSSFWorkbook behaves with XLS files
* with a WORKBOOK directory entry (instead of the more * with a WORKBOOK directory entry (instead of the more
* usual, Workbook) * usual, Workbook)
*/ */
public class TestUppercaseWorkbook extends TestCase { public final class TestUppercaseWorkbook extends TestCase {
private String dirPath;
private String xlsA = "WORKBOOK_in_capitals.xls"; private String xlsA = "WORKBOOK_in_capitals.xls";
protected void setUp() throws Exception {
super.setUp();
dirPath = System.getProperty("HSSF.testdata.path");
}
/** /**
* Test that we can open a file with WORKBOOK * Test that we can open a file with WORKBOOK
*/ */
public void testOpen() throws Exception { public void testOpen() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
@ -68,7 +64,7 @@ public class TestUppercaseWorkbook extends TestCase {
* Test that when we write out, we go back to the correct case * Test that when we write out, we go back to the correct case
*/ */
public void testWrite() throws Exception { public void testWrite() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
// Open the workbook, not preserving nodes // Open the workbook, not preserving nodes
@ -96,7 +92,7 @@ public class TestUppercaseWorkbook extends TestCase {
* correct case * correct case
*/ */
public void testWritePreserve() throws Exception { public void testWritePreserve() throws Exception {
FileInputStream is = new FileInputStream(dirPath + "/" + xlsA); InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
POIFSFileSystem fs = new POIFSFileSystem(is); POIFSFileSystem fs = new POIFSFileSystem(is);
// Open the workbook, not preserving nodes // Open the workbook, not preserving nodes

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,10 +15,17 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.BackupRecord; import org.apache.poi.hssf.record.BackupRecord;
import org.apache.poi.hssf.record.LabelSSTRecord; import org.apache.poi.hssf.record.LabelSSTRecord;
@ -29,12 +35,6 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.util.Region; import org.apache.poi.ss.util.Region;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
/** /**
* Class to test Workbook functionality * Class to test Workbook functionality
* *
@ -42,10 +42,7 @@ import java.util.Iterator;
* @author Greg Merrill * @author Greg Merrill
* @author Siggi Cherem * @author Siggi Cherem
*/ */
public class TestWorkbook extends TestCase {
public class TestWorkbook
extends TestCase
{
private static final String LAST_NAME_KEY = "lastName"; private static final String LAST_NAME_KEY = "lastName";
private static final String FIRST_NAME_KEY = "firstName"; private static final String FIRST_NAME_KEY = "firstName";
private static final String SSN_KEY = "ssn"; private static final String SSN_KEY = "ssn";
@ -58,15 +55,9 @@ public class TestWorkbook
private static final String SSN_VALUE = "555555555"; private static final String SSN_VALUE = "555555555";
private SanityChecker sanityChecker = new SanityChecker(); private SanityChecker sanityChecker = new SanityChecker();
/**
* Constructor TestWorkbook
*
* @param name
*/
public TestWorkbook(String name) private static HSSFWorkbook openSample(String sampleFileName) {
{ return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
super(name);
} }
/** /**
@ -178,21 +169,12 @@ public class TestWorkbook
* *
*/ */
public void testReadSimple() public void testReadSimple() {
throws IOException HSSFWorkbook workbook = openSample("Simple.xls");
{ HSSFSheet sheet = workbook.getSheetAt(0);
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Simple.xls"; HSSFCell cell = sheet.getRow(0).getCell(0);
FileInputStream stream = new FileInputStream(filename); assertEquals(REPLACE_ME, cell .getRichStringCellValue().getString());
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals(REPLACE_ME,
sheet.getRow(( short ) 0).getCell(( short ) 0)
.getStringCellValue());
stream.close();
} }
/** /**
@ -204,24 +186,15 @@ public class TestWorkbook
* *
*/ */
public void testReadSimpleWithDataFormat() public void testReadSimpleWithDataFormat() {
throws IOException HSSFWorkbook workbook = openSample("SimpleWithDataFormat.xls");
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithDataFormat.xls";
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFDataFormat format = workbook.createDataFormat(); HSSFDataFormat format = workbook.createDataFormat();
HSSFCell cell = HSSFCell cell = sheet.getRow(0).getCell(0);
sheet.getRow(( short ) 0).getCell(( short ) 0);
assertEquals(1.25,cell.getNumericCellValue(), 1e-10); assertEquals(1.25,cell.getNumericCellValue(), 1e-10);
assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0");
stream.close();
} }
/** /**
@ -236,23 +209,23 @@ public class TestWorkbook
public void testWriteDataFormat() public void testWriteDataFormat()
throws IOException throws IOException
{ {
File file = TempFile.createTempFile("testWriteDataFormat", File file = TempFile.createTempFile("testWriteDataFormat",
".xls"); ".xls");
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
HSSFRow r = null; HSSFRow r = null;
HSSFCell c = null; HSSFCell c = null;
HSSFDataFormat format = wb.createDataFormat(); HSSFDataFormat format = wb.createDataFormat();
HSSFCellStyle cs = wb.createCellStyle(); HSSFCellStyle cs = wb.createCellStyle();
short df = format.getFormat("0.0"); short df = format.getFormat("0.0");
cs.setDataFormat(df); cs.setDataFormat(df);
r = s.createRow((short)0); r = s.createRow((short)0);
c = r.createCell((short)0); c = r.createCell((short)0);
c.setCellStyle(cs); c.setCellStyle(cs);
c.setCellValue(1.25); c.setCellValue(1.25);
wb.write(out); wb.write(out);
out.close(); out.close();
@ -261,15 +234,15 @@ public class TestWorkbook
POIFSFileSystem fs = new POIFSFileSystem(stream); POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs); HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell = HSSFCell cell =
sheet.getRow(( short ) 0).getCell(( short ) 0); sheet.getRow(( short ) 0).getCell(( short ) 0);
format = workbook.createDataFormat(); format = workbook.createDataFormat();
assertEquals(1.25,cell.getNumericCellValue(), 1e-10); assertEquals(1.25,cell.getNumericCellValue(), 1e-10);
assertEquals(format.getFormat(df), "0.0"); assertEquals(format.getFormat(df), "0.0");
assertEquals(format, workbook.createDataFormat()); assertEquals(format, workbook.createDataFormat());
stream.close(); stream.close();
} }
@ -283,30 +256,14 @@ public class TestWorkbook
* *
*/ */
public void testReadEmployeeSimple() public void testReadEmployeeSimple() {
throws IOException HSSFWorkbook workbook = openSample("Employee.xls");
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Employee.xls";
FileInputStream stream = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(stream);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
assertEquals(EMPLOYEE_INFORMATION, assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getStringCellValue());
sheet.getRow(1).getCell(( short ) 1) assertEquals(LAST_NAME_KEY, sheet.getRow(3).getCell(2).getStringCellValue());
.getStringCellValue()); assertEquals(FIRST_NAME_KEY, sheet.getRow(4).getCell(2).getStringCellValue());
assertEquals(LAST_NAME_KEY, assertEquals(SSN_KEY, sheet.getRow(5).getCell(2).getStringCellValue());
sheet.getRow(3).getCell(( short ) 2)
.getStringCellValue());
assertEquals(FIRST_NAME_KEY,
sheet.getRow(4).getCell(( short ) 2)
.getStringCellValue());
assertEquals(SSN_KEY,
sheet.getRow(5).getCell(( short ) 2)
.getStringCellValue());
stream.close();
} }
/** /**
@ -322,33 +279,17 @@ public class TestWorkbook
* *
*/ */
public void testModifySimple() public void testModifySimple() {
throws IOException HSSFWorkbook workbook = openSample("Simple.xls");
{ HSSFSheet sheet = workbook.getSheetAt(0);
String filename = System.getProperty("HSSF.testdata.path"); HSSFCell cell = sheet.getRow(0).getCell(0);
filename = filename + "/Simple.xls"; cell.setCellValue(new HSSFRichTextString(REPLACED));
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell =
sheet.getRow(( short ) 0).getCell(( short ) 0);
cell.setCellValue(REPLACED); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
File destination = TempFile.createTempFile("SimpleResult",
".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream);
instream.close();
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
cell = sheet.getRow(( short ) 0).getCell(( short ) 0); cell = sheet.getRow(0).getCell(0);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getRichStringCellValue().getString());
instream.close();
} }
/** /**
@ -364,42 +305,26 @@ public class TestWorkbook
* or is incorrect. <P> * or is incorrect. <P>
* *
*/ */
public void testModifySimpleWithSkip() {
public void testModifySimpleWithSkip() HSSFWorkbook workbook = openSample("SimpleWithSkip.xls");
throws IOException HSSFSheet sheet = workbook.getSheetAt(0);
{ HSSFCell cell = sheet.getRow(0).getCell(1);
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithSkip.xls";
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell =
sheet.getRow(( short ) 0).getCell(( short ) 1);
cell.setCellValue(REPLACED); cell.setCellValue(REPLACED);
cell = sheet.getRow(( short ) 1).getCell(( short ) 0); cell = sheet.getRow(1).getCell(0);
cell.setCellValue(REPLACED); cell.setCellValue(REPLACED);
File destination =
TempFile.createTempFile("SimpleWithSkipResult", ".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
instream.close();
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
cell = sheet.getRow(( short ) 0).getCell(( short ) 1); cell = sheet.getRow(0).getCell(1);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getStringCellValue());
cell = sheet.getRow(( short ) 0).getCell(( short ) 0); cell = sheet.getRow(0).getCell(0);
assertEquals(DO_NOT_REPLACE, cell.getStringCellValue()); assertEquals(DO_NOT_REPLACE, cell.getStringCellValue());
cell = sheet.getRow(( short ) 1).getCell(( short ) 0); cell = sheet.getRow(1).getCell(0);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getStringCellValue());
cell = sheet.getRow(( short ) 1).getCell(( short ) 1); cell = sheet.getRow(1).getCell(1);
assertEquals(DO_NOT_REPLACE, cell.getStringCellValue()); assertEquals(DO_NOT_REPLACE, cell.getStringCellValue());
instream.close();
} }
/** /**
@ -415,41 +340,26 @@ public class TestWorkbook
* is incorrect or has not been replaced. <P> * is incorrect or has not been replaced. <P>
* *
*/ */
public void testModifySimpleWithStyling() {
public void testModifySimpleWithStyling() HSSFWorkbook workbook = openSample("SimpleWithStyling.xls");
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/SimpleWithStyling.xls";
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
for (int k = 0; k < 4; k++) for (int k = 0; k < 4; k++)
{ {
HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0); HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0);
cell.setCellValue(REPLACED); cell.setCellValue(new HSSFRichTextString(REPLACED));
} }
File destination =
TempFile.createTempFile("SimpleWithStylingResult", ".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream);
instream.close(); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
for (int k = 0; k < 4; k++) for (int k = 0; k < 4; k++)
{ {
HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0); HSSFCell cell = sheet.getRow(( short ) k).getCell(( short ) 0);
assertEquals(REPLACED, cell.getStringCellValue()); assertEquals(REPLACED, cell.getRichStringCellValue().getString());
} }
instream.close();
} }
/** /**
@ -465,48 +375,23 @@ public class TestWorkbook
* is incorrect or has not been replaced. <P> * is incorrect or has not been replaced. <P>
* *
*/ */
public void testModifyEmployee() {
public void testModifyEmployee() HSSFWorkbook workbook = openSample("Employee.xls");
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/Employee.xls";
FileInputStream instream = new FileInputStream(filename);
POIFSFileSystem fsin = new POIFSFileSystem(instream);
HSSFWorkbook workbook = new HSSFWorkbook(fsin);
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cell = HSSFCell cell = sheet.getRow(3).getCell(2);
sheet.getRow(( short ) 3).getCell(( short ) 2);
cell.setCellValue(LAST_NAME_VALUE); cell.setCellValue(LAST_NAME_VALUE);
cell = sheet.getRow(( short ) 4).getCell(( short ) 2); cell = sheet.getRow(4).getCell(2);
cell.setCellValue(FIRST_NAME_VALUE); cell.setCellValue(FIRST_NAME_VALUE);
cell = sheet.getRow(( short ) 5).getCell(( short ) 2); cell = sheet.getRow(5).getCell(2);
cell.setCellValue(SSN_VALUE); cell.setCellValue(SSN_VALUE);
File destination = TempFile.createTempFile("EmployeeResult",
".xls");
FileOutputStream outstream = new FileOutputStream(destination);
workbook.write(outstream); workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook);
instream.close();
outstream.close();
instream = new FileInputStream(destination);
workbook = new HSSFWorkbook(new POIFSFileSystem(instream));
sheet = workbook.getSheetAt(0); sheet = workbook.getSheetAt(0);
assertEquals(EMPLOYEE_INFORMATION, assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getStringCellValue());
sheet.getRow(1).getCell(( short ) 1) assertEquals(LAST_NAME_VALUE, sheet.getRow(3).getCell(2).getStringCellValue());
.getStringCellValue()); assertEquals(FIRST_NAME_VALUE, sheet.getRow(4).getCell(2).getStringCellValue());
assertEquals(LAST_NAME_VALUE, assertEquals(SSN_VALUE, sheet.getRow(5).getCell(2).getStringCellValue());
sheet.getRow(3).getCell(( short ) 2)
.getStringCellValue());
assertEquals(FIRST_NAME_VALUE,
sheet.getRow(4).getCell(( short ) 2)
.getStringCellValue());
assertEquals(SSN_VALUE,
sheet.getRow(5).getCell(( short ) 2)
.getStringCellValue());
instream.close();
} }
/** /**
@ -517,21 +402,10 @@ public class TestWorkbook
* FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly indentifies the cell<P> * FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly indentifies the cell<P>
* *
*/ */
public void testReadSheetWithRK() {
public void testReadSheetWithRK() HSSFWorkbook h = openSample("rk.xls");
throws IOException
{
String filename = System.getProperty("HSSF.testdata.path");
filename = filename + "/rk.xls";
// a.xls has a value on position (0,0)
FileInputStream in = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook h = new HSSFWorkbook(fs);
HSSFSheet s = h.getSheetAt(0); HSSFSheet s = h.getSheetAt(0);
HSSFRow r = s.getRow(0); HSSFCell c = s.getRow(0).getCell(0);
HSSFCell c = r.getCell(( short ) 0);
int a = c.getCellType(); int a = c.getCellType();
assertEquals(a, c.CELL_TYPE_NUMERIC); assertEquals(a, c.CELL_TYPE_NUMERIC);
@ -564,7 +438,6 @@ public class TestWorkbook
{ {
r = s.createRow(rownum); r = s.createRow(rownum);
// r.setRowNum(( short ) rownum);
for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2) for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2)
{ {
c = r.createCell(cellnum); c = r.createCell(cellnum);
@ -572,7 +445,7 @@ public class TestWorkbook
+ ((( double ) rownum / 1000) + ((( double ) rownum / 1000)
+ (( double ) cellnum / 10000))); + (( double ) cellnum / 10000)));
c = r.createCell(( short ) (cellnum + 1)); c = r.createCell(( short ) (cellnum + 1));
c.setCellValue("TEST"); c.setCellValue(new HSSFRichTextString("TEST"));
} }
} }
s.addMergedRegion(new Region(( short ) 0, ( short ) 0, ( short ) 10, s.addMergedRegion(new Region(( short ) 0, ( short ) 0, ( short ) 10,
@ -632,7 +505,7 @@ public class TestWorkbook
HSSFRow row = sheet.createRow(( short ) 2); HSSFRow row = sheet.createRow(( short ) 2);
HSSFCell cell = row.createCell(( short ) 1); HSSFCell cell = row.createCell(( short ) 1);
cell.setCellValue("Class"); cell.setCellValue(new HSSFRichTextString("Class"));
cell = row.createCell(( short ) 2); cell = row.createCell(( short ) 2);
// workbook.write(new FileOutputStream("/a2.xls")); // workbook.write(new FileOutputStream("/a2.xls"));
@ -693,43 +566,29 @@ public class TestWorkbook
*/ */
public void testRepeatingColsRows() throws IOException public void testRepeatingColsRows() throws IOException
{ {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Test Print Titles"); HSSFSheet sheet = workbook.createSheet("Test Print Titles");
String sheetName = workbook.getSheetName(0);
HSSFRow row = sheet.createRow(0); HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short)1); HSSFCell cell = row.createCell((short)1);
cell.setCellValue("hi"); cell.setCellValue(new HSSFRichTextString("hi"));
workbook.setRepeatingRowsAndColumns(0, 0, 1, 0, 0); workbook.setRepeatingRowsAndColumns(0, 0, 1, 0, 0);
File file = TempFile.createTempFile("testPrintTitles",".xls"); File file = TempFile.createTempFile("testPrintTitles",".xls");
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
assertTrue("file exists",file.exists());
} }
public static void main(String [] ignored_args) public static void main(String [] ignored_args)
{ {
String filename = System.getProperty("HSSF.testdata.path");
// assume this is relative to basedir
if (filename == null)
{
System.setProperty(
"HSSF.testdata.path",
"src/testcases/org/apache/poi/hssf/data");
}
System.out
.println("Testing org.apache.poi.hssf.usermodel.HSSFWorkbook");
junit.textui.TestRunner.run(TestWorkbook.class); junit.textui.TestRunner.run(TestWorkbook.class);
} }
} }

View File

@ -15,23 +15,28 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.util; package org.apache.poi.hssf.util;
import junit.framework.TestCase;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.record.formula.MemFuncPtg;
import org.apache.poi.hssf.record.formula.Area3DPtg;
import org.apache.poi.hssf.record.formula.UnionPtg;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.record.formula.Area3DPtg;
import org.apache.poi.hssf.record.formula.MemFuncPtg;
import org.apache.poi.hssf.record.formula.UnionPtg;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFName;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
*
*/
public final class TestAreaReference extends TestCase { public final class TestAreaReference extends TestCase {
public void testAreaRef1() { public void testAreaRef1() {
@ -99,7 +104,7 @@ public final class TestAreaReference extends TestCase {
TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7");
} }
private static class HSSFWB extends HSSFWorkbook { private static final class HSSFWB extends HSSFWorkbook {
public HSSFWB(InputStream in) throws IOException { public HSSFWB(InputStream in) throws IOException {
super(in); super(in);
} }
@ -182,12 +187,9 @@ public final class TestAreaReference extends TestCase {
} }
public void testDiscontinousReference() throws Exception { public void testDiscontinousReference() throws Exception {
String filename = System.getProperty( "HSSF.testdata.path" ); InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls");
filename = filename + "/44167.xls"; HSSFWB wb = new HSSFWB(is);
FileInputStream fin = new FileInputStream( filename );
HSSFWB wb = new HSSFWB( fin );
Workbook workbook = wb.getWorkbook(); Workbook workbook = wb.getWorkbook();
fin.close();
assertEquals(1, wb.getNumberOfNames()); assertEquals(1, wb.getNumberOfNames());
String sheetName = "Tabelle1"; String sheetName = "Tabelle1";
@ -269,5 +271,4 @@ public final class TestAreaReference extends TestCase {
public static void main(String[] args) { public static void main(String[] args) {
junit.textui.TestRunner.run(TestAreaReference.class); junit.textui.TestRunner.run(TestAreaReference.class);
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -16,57 +15,55 @@
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.io.*; import java.io.*;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Class to test that POIFS complains when given an Office 2007 XML document * Class to test that POIFS complains when given an Office 2007 XML document
* *
* @author Marc Johnson * @author Marc Johnson
*/ */
public class TestOffice2007XMLException extends TestCase {
public class TestOffice2007XMLException extends TestCase private static final InputStream openSampleStream(String sampleFileName) {
{ return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
public String dirname;
public void setUp() {
dirname = System.getProperty("HSSF.testdata.path");
} }
public void testXMLException() throws IOException public void testXMLException() throws IOException
{ {
FileInputStream in = new FileInputStream(dirname + "/sample.xlsx"); InputStream in = openSampleStream("sample.xlsx");
try { try {
new POIFSFileSystem(in); new POIFSFileSystem(in);
fail(); fail("expected exception was not thrown");
} catch(OfficeXmlFileException e) { } catch(OfficeXmlFileException e) {
// Good // expected during successful test
assertTrue(e.getMessage().indexOf("POI only supports OLE2 Office documents") > 0);
} }
} }
public void testDetectAsPOIFS() throws IOException { public void testDetectAsPOIFS() {
InputStream in;
// ooxml file isn't // ooxml file isn't
in = new PushbackInputStream( confirmIsPOIFS("SampleSS.xlsx", false);
new FileInputStream(dirname + "/SampleSS.xlsx"), 10
);
assertFalse(POIFSFileSystem.hasPOIFSHeader(in));
// xls file is // xls file is
in = new PushbackInputStream( confirmIsPOIFS("SampleSS.xls", true);
new FileInputStream(dirname + "/SampleSS.xls"), 10
);
assertTrue(POIFSFileSystem.hasPOIFSHeader(in));
// text file isn't // text file isn't
in = new PushbackInputStream( confirmIsPOIFS("SampleSS.txt", false);
new FileInputStream(dirname + "/SampleSS.txt"), 10 }
); private void confirmIsPOIFS(String sampleFileName, boolean expectedResult) {
assertFalse(POIFSFileSystem.hasPOIFSHeader(in)); InputStream in = new PushbackInputStream(openSampleStream(sampleFileName), 10);
boolean actualResult;
try {
actualResult = POIFSFileSystem.hasPOIFSHeader(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
assertEquals(expectedResult, actualResult);
} }
} }

View File

@ -17,14 +17,13 @@
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
/** /**
* Tests for POIFSFileSystem * Tests for POIFSFileSystem
* *
@ -32,10 +31,6 @@ import junit.framework.TestCase;
*/ */
public final class TestPOIFSFileSystem extends TestCase { public final class TestPOIFSFileSystem extends TestCase {
public TestPOIFSFileSystem(String testName) {
super(testName);
}
/** /**
* Mock exception used to ensure correct error handling * Mock exception used to ensure correct error handling
*/ */
@ -121,16 +116,7 @@ public final class TestPOIFSFileSystem extends TestCase {
} }
private static InputStream openSampleStream(String sampleName) { private static InputStream openSampleStream(String sampleFileName) {
String dataDirName = System.getProperty("HSSF.testdata.path"); return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
if(dataDirName == null) {
throw new RuntimeException("Missing system property '" + "HSSF.testdata.path" + "'");
}
File f = new File(dataDirName + "/" + sampleName);
try {
return new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException("Sample file '" + f.getAbsolutePath() + "' not found");
}
} }
} }

View File

@ -18,12 +18,21 @@
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import junit.framework.TestCase; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import junit.framework.ComparisonFailure; import junit.framework.ComparisonFailure;
import junit.framework.TestCase;
import java.io.*; import org.apache.poi.hssf.HSSFTestDataSamples;
import java.util.*;
import org.apache.poi.poifs.property.DirectoryProperty; import org.apache.poi.poifs.property.DirectoryProperty;
import org.apache.poi.poifs.property.Property; import org.apache.poi.poifs.property.Property;
@ -36,45 +45,46 @@ import org.apache.poi.poifs.property.Property;
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class TestPropertySorter extends TestCase { public final class TestPropertySorter extends TestCase {
//the correct order of entries in the test file //the correct order of entries in the test file
protected static final String[] _entries = { private static final String[] _entries = {
"dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3", "dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3",
"__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5", "__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5",
"ThisWorkbook", "_VBA_PROJECT", "ThisWorkbook", "_VBA_PROJECT",
}; };
protected File testFile; private static POIFSFileSystem openSampleFS() {
InputStream is = HSSFTestDataSamples.openSampleFileStream("39234.xls");
public void setUp(){ try {
String home = System.getProperty("HSSF.testdata.path"); return new POIFSFileSystem(is);
testFile = new File(home + "/39234.xls"); } catch (IOException e) {
throw new RuntimeException(e);
}
} }
/** /**
* Test sorting of properties in <code>DirectoryProperty</code> * Test sorting of properties in <code>DirectoryProperty</code>
*/ */
public void testSortProperties() throws IOException { public void testSortProperties() throws IOException {
InputStream is = new FileInputStream(testFile); POIFSFileSystem fs = openSampleFS();
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
Property[] props = getVBAProperties(fs); Property[] props = getVBAProperties(fs);
assertEquals(_entries.length, props.length); assertEquals(_entries.length, props.length);
// (1). See that there is a problem with the old case-sensitive property comparartor // (1). See that there is a problem with the old case-sensitive property comparator
Arrays.sort(props, new CaseSensitivePropertyComparator()); Arrays.sort(props, OldCaseSensitivePropertyComparator);
try { try {
for (int i = 0; i < props.length; i++) { for (int i = 0; i < props.length; i++) {
assertEquals(_entries[i], props[i].getName()); assertEquals(_entries[i], props[i].getName());
} }
fail("case-sensitive property comparator returns properties in wrong order"); fail("expected old case-sensitive property comparator to return properties in wrong order");
} catch (ComparisonFailure e){ } catch (ComparisonFailure e){
; // as expected // expected during successful test
assertNotNull(e.getMessage());
} }
// (2) Verify that the fixed proeprty comparator works right // (2) Verify that the fixed property comparator works right
Arrays.sort(props, new DirectoryProperty.PropertyComparator()); Arrays.sort(props, new DirectoryProperty.PropertyComparator());
for (int i = 0; i < props.length; i++) { for (int i = 0; i < props.length; i++) {
assertEquals(_entries[i], props[i].getName()); assertEquals(_entries[i], props[i].getName());
@ -85,14 +95,12 @@ public class TestPropertySorter extends TestCase {
* Serialize file system and verify that the order of properties is the same as in the original file. * Serialize file system and verify that the order of properties is the same as in the original file.
*/ */
public void testSerialization() throws IOException { public void testSerialization() throws IOException {
InputStream is = new FileInputStream(testFile); POIFSFileSystem fs = openSampleFS();
POIFSFileSystem fs = new POIFSFileSystem(is);
is.close();
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
fs.writeFilesystem(out); fs.writeFilesystem(out);
out.close(); out.close();
is = new ByteArrayInputStream(out.toByteArray()); InputStream is = new ByteArrayInputStream(out.toByteArray());
fs = new POIFSFileSystem(is); fs = new POIFSFileSystem(is);
is.close(); is.close();
Property[] props = getVBAProperties(fs); Property[] props = getVBAProperties(fs);
@ -128,26 +136,17 @@ public class TestPropertySorter extends TestCase {
/** /**
* Old version of case-sensitive PropertyComparator to demonstrate the problem * Old version of case-sensitive PropertyComparator to demonstrate the problem
*/ */
private class CaseSensitivePropertyComparator implements Comparator private static final Comparator OldCaseSensitivePropertyComparator = new Comparator() {
{
public boolean equals(Object o) public int compare(Object o1, Object o2) {
{
return this == o;
}
public int compare(Object o1, Object o2)
{
String name1 = (( Property ) o1).getName(); String name1 = (( Property ) o1).getName();
String name2 = (( Property ) o2).getName(); String name2 = (( Property ) o2).getName();
int result = name1.length() - name2.length(); int result = name1.length() - name2.length();
if (result == 0) if (result == 0) {
{
result = name1.compareTo(name2); result = name1.compareTo(name2);
} }
return result; return result;
} }
} };
} }