fixed sonar issues and eclipse warnings

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1706742 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2015-10-05 00:28:54 +00:00
parent 0d29f8b2ec
commit eee32c0480
16 changed files with 841 additions and 530 deletions

View File

@ -514,8 +514,9 @@ public class MutableSection extends Section
{ {
/* Write the dictionary item in Unicode. */ /* Write the dictionary item in Unicode. */
int sLength = value.length() + 1; int sLength = value.length() + 1;
if (sLength % 2 == 1) if ((sLength & 1) == 1) {
sLength++; sLength++;
}
length += TypeWriter.writeUIntToStream(out, key.longValue()); length += TypeWriter.writeUIntToStream(out, key.longValue());
length += TypeWriter.writeUIntToStream(out, sLength); length += TypeWriter.writeUIntToStream(out, sLength);
final byte[] ca = CodePageUtil.getBytesInCodePage(value, codepage); final byte[] ca = CodePageUtil.getBytesInCodePage(value, codepage);

View File

@ -21,7 +21,6 @@ package org.apache.poi.poifs.dev;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
@ -41,10 +40,8 @@ public class POIFSViewer
* @param args the names of the files to be displayed * @param args the names of the files to be displayed
*/ */
public static void main(final String args[]) public static void main(final String args[]) {
{ if (args.length == 0) {
if (args.length < 0)
{
System.err.println("Must specify at least one file to view"); System.err.println("Must specify at least one file to view");
System.exit(1); System.exit(1);
} }
@ -56,16 +53,12 @@ public class POIFSViewer
} }
} }
private static void viewFile(final String filename, private static void viewFile(String filename, boolean printName) {
final boolean printName) if (printName) {
{
if (printName)
{
StringBuffer flowerbox = new StringBuffer(); StringBuffer flowerbox = new StringBuffer();
flowerbox.append("."); flowerbox.append(".");
for (int j = 0; j < filename.length(); j++) for (int j = 0; j < filename.length(); j++) {
{
flowerbox.append("-"); flowerbox.append("-");
} }
flowerbox.append("."); flowerbox.append(".");
@ -73,21 +66,14 @@ public class POIFSViewer
System.out.println("|" + filename + "|"); System.out.println("|" + filename + "|");
System.out.println(flowerbox); System.out.println(flowerbox);
} }
try try {
{ NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(filename));
POIFSViewable fs = List<String> strings = POIFSViewEngine.inspectViewable(fs, true, 0, " ");
new NPOIFSFileSystem(new File(filename)); for (String s : strings) {
List<String> strings = POIFSViewEngine.inspectViewable(fs, true, System.out.print(s);
0, " ");
Iterator<String> iter = strings.iterator();
while (iter.hasNext())
{
System.out.print(iter.next());
} }
} fs.close();
catch (IOException e) } catch (IOException e) {
{
System.out.println(e.getMessage()); System.out.println(e.getMessage());
} }
} }

View File

@ -66,11 +66,17 @@ public interface TextRun {
/** /**
* Returns the font size which is either set directly on this text run or
* given from the slide layout
*
* @return font size in points or null if font size is not set. * @return font size in points or null if font size is not set.
*/ */
Double getFontSize(); Double getFontSize();
/** /**
* Sets the font size directly on this text run, if null is given, the
* font size defaults to the values given from the slide layout
*
* @param fontSize font size in points, if null the underlying fontsize will be unset * @param fontSize font size in points, if null the underlying fontsize will be unset
*/ */
void setFontSize(Double fontSize); void setFontSize(Double fontSize);

View File

@ -52,7 +52,7 @@ public class TestSXSSFSheet extends BaseTestSheet {
*/ */
@Override @Override
@Test @Test
public void cloneSheet() { public void cloneSheet() throws IOException {
thrown.expect(RuntimeException.class); thrown.expect(RuntimeException.class);
thrown.expectMessage("NotImplemented"); thrown.expectMessage("NotImplemented");
super.cloneSheet(); super.cloneSheet();
@ -60,7 +60,7 @@ public class TestSXSSFSheet extends BaseTestSheet {
@Override @Override
@Test @Test
public void cloneSheetMultipleTimes() { public void cloneSheetMultipleTimes() throws IOException {
thrown.expect(RuntimeException.class); thrown.expect(RuntimeException.class);
thrown.expectMessage("NotImplemented"); thrown.expectMessage("NotImplemented");
super.cloneSheetMultipleTimes(); super.cloneSheetMultipleTimes();
@ -71,7 +71,7 @@ public class TestSXSSFSheet extends BaseTestSheet {
*/ */
@Override @Override
@Test @Test
public void shiftMerged(){ public void shiftMerged() throws IOException {
thrown.expect(RuntimeException.class); thrown.expect(RuntimeException.class);
thrown.expectMessage("NotImplemented"); thrown.expectMessage("NotImplemented");
super.shiftMerged(); super.shiftMerged();
@ -84,7 +84,7 @@ public class TestSXSSFSheet extends BaseTestSheet {
*/ */
@Override @Override
@Test @Test
public void bug35084(){ public void bug35084() throws IOException {
thrown.expect(RuntimeException.class); thrown.expect(RuntimeException.class);
thrown.expectMessage("NotImplemented"); thrown.expectMessage("NotImplemented");
super.bug35084(); super.bug35084();
@ -146,11 +146,12 @@ public class TestSXSSFSheet extends BaseTestSheet {
sheet.createRow(2); sheet.createRow(2);
} finally { } finally {
wb.close(); wb.close();
template.close();
} }
} }
@Test @Test(expected=IllegalArgumentException.class)
public void createRowAfterLastRow() { public void createRowAfterLastRow() throws IOException {
createRowAfterLastRow(SpreadsheetVersion.EXCEL2007); createRowAfterLastRow(SpreadsheetVersion.EXCEL2007);
} }
} }

View File

@ -18,9 +18,15 @@
*/ */
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.apache.poi.ss.usermodel.BaseTestConditionalFormatting; import org.apache.poi.ss.usermodel.BaseTestConditionalFormatting;
import org.apache.poi.ss.usermodel.Color; import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider;
import org.junit.Test;
/** /**
* XSSF-specific Conditional Formatting tests * XSSF-specific Conditional Formatting tests
@ -40,11 +46,13 @@ public class TestXSSFConditionalFormatting extends BaseTestConditionalFormatting
} }
} }
public void testRead(){ @Test
public void testRead() throws IOException {
testRead("WithConditionalFormatting.xlsx"); testRead("WithConditionalFormatting.xlsx");
} }
public void testReadOffice2007() { @Test
public void testReadOffice2007() throws IOException {
testReadOffice2007("NewStyleConditionalFormattings.xlsx"); testReadOffice2007("NewStyleConditionalFormattings.xlsx");
} }
} }

View File

@ -17,6 +17,8 @@
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.*;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -33,6 +35,8 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Ignore;
import org.junit.Test;
public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
@ -40,11 +44,13 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
super(XSSFITestDataProvider.instance); super(XSSFITestDataProvider.instance);
} }
public void testSharedFormulas(){ @Test
public void testSharedFormulas() throws IOException {
baseTestSharedFormulas("shared_formulas.xlsx"); baseTestSharedFormulas("shared_formulas.xlsx");
} }
public void testSharedFormulas_evaluateInCell(){ @Test
public void testSharedFormulas_evaluateInCell() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx"); XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
@ -59,20 +65,23 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
// get B3 and evaluate it in the cell // get B3 and evaluate it in the cell
XSSFCell b3 = sheet.getRow(2).getCell(1); XSSFCell b3 = sheet.getRow(2).getCell(1);
assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue()); assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0);
//at this point the master formula is gone, but we are still able to evaluate dependent cells //at this point the master formula is gone, but we are still able to evaluate dependent cells
XSSFCell c3 = sheet.getRow(2).getCell(2); XSSFCell c3 = sheet.getRow(2).getCell(2);
assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue()); assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0);
XSSFCell d3 = sheet.getRow(2).getCell(3); XSSFCell d3 = sheet.getRow(2).getCell(3);
assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue()); assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0);
wb.close();
} }
/** /**
* Evaluation of cell references with column indexes greater than 255. See bugzilla 50096 * Evaluation of cell references with column indexes greater than 255. See bugzilla 50096
*/ */
public void testEvaluateColumnGreaterThan255() { @Test
public void testEvaluateColumnGreaterThan255() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx"); XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx");
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
@ -95,8 +104,10 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
CellValue cv_noformula = evaluator.evaluate(cell_noformula); CellValue cv_noformula = evaluator.evaluate(cell_noformula);
CellValue cv_formula = evaluator.evaluate(cell_formula); CellValue cv_formula = evaluator.evaluate(cell_formula);
assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(), assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(),
cv_noformula.getNumberValue(), cv_formula.getNumberValue()); cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0);
} }
wb.close();
} }
/** /**
@ -104,6 +115,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
* formulas that refer to cells and named ranges in multiple other * formulas that refer to cells and named ranges in multiple other
* workbooks, both HSSF and XSSF ones * workbooks, both HSSF and XSSF ones
*/ */
@Test
public void testReferencesToOtherWorkbooks() throws Exception { public void testReferencesToOtherWorkbooks() throws Exception {
XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx"); XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx");
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
@ -120,7 +132,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
assertEquals("Hello!", cXSLX_cell.getStringCellValue()); assertEquals("Hello!", cXSLX_cell.getStringCellValue());
assertEquals("Test A1", cXSLX_sNR.getStringCellValue()); assertEquals("Test A1", cXSLX_sNR.getStringCellValue());
assertEquals(142.0, cXSLX_gNR.getNumericCellValue()); assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0);
// References to a .xls file // References to a .xls file
Row rXSL = s.getRow(4); Row rXSL = s.getRow(4);
@ -133,7 +145,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
assertEquals("Hello!", cXSL_cell.getStringCellValue()); assertEquals("Hello!", cXSL_cell.getStringCellValue());
assertEquals("Test A1", cXSL_sNR.getStringCellValue()); assertEquals("Test A1", cXSL_sNR.getStringCellValue());
assertEquals(142.0, cXSL_gNR.getNumericCellValue()); assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0);
// Try to evaluate without references, won't work // Try to evaluate without references, won't work
// (At least, not unit we fix bug #56752 that is) // (At least, not unit we fix bug #56752 that is)
@ -213,6 +225,8 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
} finally { } finally {
alt.close(); alt.close();
} }
wb.close();
} }
/** /**
@ -222,7 +236,9 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
* TODO Add the support then add a unit test * TODO Add the support then add a unit test
* See bug #56752 * See bug #56752
*/ */
public void TODOtestCachedReferencesToOtherWorkbooks() throws Exception { @Test
@Ignore
public void testCachedReferencesToOtherWorkbooks() throws Exception {
// TODO // TODO
} }
@ -233,12 +249,12 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
* This test, based on common test files for HSSF and XSSF, checks * This test, based on common test files for HSSF and XSSF, checks
* that we can correctly evaluate these * that we can correctly evaluate these
*/ */
@Test
public void testMultiSheetReferencesHSSFandXSSF() throws Exception { public void testMultiSheetReferencesHSSFandXSSF() throws Exception {
Workbook[] wbs = new Workbook[] { Workbook wb1 = HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls");
HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"), Workbook wb2 = XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx");
XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx")
}; for (Workbook wb : new Workbook[] {wb1,wb2}) {
for (Workbook wb : wbs) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet s1 = wb.getSheetAt(0); Sheet s1 = wb.getSheetAt(0);
@ -288,7 +304,11 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula()); assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula());
assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString()); assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString());
} }
wb2.close();
wb1.close();
} }
/** /**
* A handful of functions (such as SUM, COUNTA, MIN) support * A handful of functions (such as SUM, COUNTA, MIN) support
* multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2, * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2,
@ -296,12 +316,12 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
* This test, based on common test files for HSSF and XSSF, checks * This test, based on common test files for HSSF and XSSF, checks
* that we can correctly evaluate these * that we can correctly evaluate these
*/ */
public void testMultiSheetAreasHSSFandXSSF() throws Exception { @Test
Workbook[] wbs = new Workbook[] { public void testMultiSheetAreasHSSFandXSSF() throws IOException {
HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"), Workbook wb1 = HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls");
XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx") Workbook wb2 = XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx");
};
for (Workbook wb : wbs) { for (Workbook wb : new Workbook[]{wb1,wb2}) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet s1 = wb.getSheetAt(0); Sheet s1 = wb.getSheetAt(0);
@ -334,8 +354,12 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula());
assertEquals("4.0", evaluator.evaluate(countFA).formatAsString()); assertEquals("4.0", evaluator.evaluate(countFA).formatAsString());
} }
wb2.close();
wb1.close();
} }
@Test
public void testMultisheetFormulaEval() throws IOException { public void testMultisheetFormulaEval() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -376,15 +400,16 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
cell = sheet1.getRow(1).getCell(0); cell = sheet1.getRow(1).getCell(0);
assertEquals(3.0, cell.getNumericCellValue()); assertEquals(3.0, cell.getNumericCellValue(), 0);
cell = sheet1.getRow(2).getCell(0); cell = sheet1.getRow(2).getCell(0);
assertEquals(4.0, cell.getNumericCellValue()); assertEquals(4.0, cell.getNumericCellValue(), 0);
} finally { } finally {
wb.close(); wb.close();
} }
} }
@Test
public void testBug55843() throws IOException { public void testBug55843() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -397,12 +422,10 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
cellA2.setCellFormula("IF(B1=0,\"\",((ROW()-ROW(A$1))*12))"); cellA2.setCellFormula("IF(B1=0,\"\",((ROW()-ROW(A$1))*12))");
CellValue evaluate = formulaEvaluator.evaluate(cellA2); CellValue evaluate = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluate);
assertEquals("12.0", evaluate.formatAsString()); assertEquals("12.0", evaluate.formatAsString());
cellA2.setCellFormula("IF(NOT(B1=0),((ROW()-ROW(A$1))*12),\"\")"); cellA2.setCellFormula("IF(NOT(B1=0),((ROW()-ROW(A$1))*12),\"\")");
CellValue evaluateN = formulaEvaluator.evaluate(cellA2); CellValue evaluateN = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluateN);
assertEquals(evaluate.toString(), evaluateN.toString()); assertEquals(evaluate.toString(), evaluateN.toString());
assertEquals("12.0", evaluateN.formatAsString()); assertEquals("12.0", evaluateN.formatAsString());
@ -411,6 +434,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
} }
} }
@Test
public void testBug55843a() throws IOException { public void testBug55843a() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -423,12 +447,10 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
cellA2.setCellFormula("IF(B1=0,\"\",((ROW(A$1))))"); cellA2.setCellFormula("IF(B1=0,\"\",((ROW(A$1))))");
CellValue evaluate = formulaEvaluator.evaluate(cellA2); CellValue evaluate = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluate);
assertEquals("1.0", evaluate.formatAsString()); assertEquals("1.0", evaluate.formatAsString());
cellA2.setCellFormula("IF(NOT(B1=0),((ROW(A$1))),\"\")"); cellA2.setCellFormula("IF(NOT(B1=0),((ROW(A$1))),\"\")");
CellValue evaluateN = formulaEvaluator.evaluate(cellA2); CellValue evaluateN = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluateN);
assertEquals(evaluate.toString(), evaluateN.toString()); assertEquals(evaluate.toString(), evaluateN.toString());
assertEquals("1.0", evaluateN.formatAsString()); assertEquals("1.0", evaluateN.formatAsString());
@ -437,6 +459,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
} }
} }
@Test
public void testBug55843b() throws IOException { public void testBug55843b() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -450,12 +473,10 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))"); cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))");
CellValue evaluate = formulaEvaluator.evaluate(cellA2); CellValue evaluate = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluate);
assertEquals("2.0", evaluate.formatAsString()); assertEquals("2.0", evaluate.formatAsString());
cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")"); cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")");
CellValue evaluateN = formulaEvaluator.evaluate(cellA2); CellValue evaluateN = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluateN);
assertEquals(evaluate.toString(), evaluateN.toString()); assertEquals(evaluate.toString(), evaluateN.toString());
assertEquals("2.0", evaluateN.formatAsString()); assertEquals("2.0", evaluateN.formatAsString());
@ -464,6 +485,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
} }
} }
@Test
public void testBug55843c() throws IOException { public void testBug55843c() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -477,13 +499,13 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
cellA2.setCellFormula("IF(NOT(B1=0),((ROW())))"); cellA2.setCellFormula("IF(NOT(B1=0),((ROW())))");
CellValue evaluateN = formulaEvaluator.evaluate(cellA2); CellValue evaluateN = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluateN);
assertEquals("2.0", evaluateN.formatAsString()); assertEquals("2.0", evaluateN.formatAsString());
} finally { } finally {
wb.close(); wb.close();
} }
} }
@Test
public void testBug55843d() throws IOException { public void testBug55843d() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -497,13 +519,13 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")"); cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")");
CellValue evaluateN = formulaEvaluator.evaluate(cellA2); CellValue evaluateN = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluateN);
assertEquals("2.0", evaluateN.formatAsString()); assertEquals("2.0", evaluateN.formatAsString());
} finally { } finally {
wb.close(); wb.close();
} }
} }
@Test
public void testBug55843e() throws IOException { public void testBug55843e() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -517,13 +539,13 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))"); cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))");
CellValue evaluate = formulaEvaluator.evaluate(cellA2); CellValue evaluate = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluate);
assertEquals("2.0", evaluate.formatAsString()); assertEquals("2.0", evaluate.formatAsString());
} finally { } finally {
wb.close(); wb.close();
} }
} }
@Test
public void testBug55843f() throws IOException { public void testBug55843f() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
@ -537,13 +559,13 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
cellA2.setCellFormula("IF(B1=0,\"\",IF(B1=10,3,4))"); cellA2.setCellFormula("IF(B1=0,\"\",IF(B1=10,3,4))");
CellValue evaluate = formulaEvaluator.evaluate(cellA2); CellValue evaluate = formulaEvaluator.evaluate(cellA2);
System.out.println(evaluate);
assertEquals("3.0", evaluate.formatAsString()); assertEquals("3.0", evaluate.formatAsString());
} finally { } finally {
wb.close(); wb.close();
} }
} }
@Test
public void testBug56655() throws IOException { public void testBug56655() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -561,6 +583,7 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
wb.close(); wb.close();
} }
@Test
public void testBug56655a() throws IOException { public void testBug56655a() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();

View File

@ -17,11 +17,15 @@
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook;
import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
@ -51,7 +55,18 @@ import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.helpers.ColumnHelper; import org.apache.poi.xssf.usermodel.helpers.ColumnHelper;
import org.junit.Test; import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetProtection;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPane;
@SuppressWarnings("resource") @SuppressWarnings("resource")
@ -69,18 +84,18 @@ public final class TestXSSFSheet extends BaseTestSheet {
} }
@Test @Test
public void getSetMargin() { public void getSetMargin() throws IOException {
baseTestGetSetMargin(new double[]{0.7, 0.7, 0.75, 0.75, 0.3, 0.3}); baseTestGetSetMargin(new double[]{0.7, 0.7, 0.75, 0.75, 0.3, 0.3});
} }
@Test @Test
public void existingHeaderFooter() { public void existingHeaderFooter() throws IOException {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("45540_classic_Header.xlsx"); XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45540_classic_Header.xlsx");
XSSFOddHeader hdr; XSSFOddHeader hdr;
XSSFOddFooter ftr; XSSFOddFooter ftr;
// Sheet 1 has a header with center and right text // Sheet 1 has a header with center and right text
XSSFSheet s1 = workbook.getSheetAt(0); XSSFSheet s1 = wb1.getSheetAt(0);
assertNotNull(s1.getHeader()); assertNotNull(s1.getHeader());
assertNotNull(s1.getFooter()); assertNotNull(s1.getFooter());
hdr = (XSSFOddHeader) s1.getHeader(); hdr = (XSSFOddHeader) s1.getHeader();
@ -98,7 +113,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals("", ftr.getRight()); assertEquals("", ftr.getRight());
// Sheet 2 has a footer, but it's empty // Sheet 2 has a footer, but it's empty
XSSFSheet s2 = workbook.getSheetAt(1); XSSFSheet s2 = wb1.getSheetAt(1);
assertNotNull(s2.getHeader()); assertNotNull(s2.getHeader());
assertNotNull(s2.getFooter()); assertNotNull(s2.getFooter());
hdr = (XSSFOddHeader) s2.getHeader(); hdr = (XSSFOddHeader) s2.getHeader();
@ -116,10 +131,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals("", ftr.getRight()); assertEquals("", ftr.getRight());
// Save and reload // Save and reload
XSSFWorkbook wb = XSSFTestDataSamples.writeOutAndReadBack(workbook); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
hdr = (XSSFOddHeader) wb.getSheetAt(0).getHeader(); hdr = (XSSFOddHeader) wb2.getSheetAt(0).getHeader();
ftr = (XSSFOddFooter) wb.getSheetAt(0).getFooter(); ftr = (XSSFOddFooter) wb2.getSheetAt(0).getFooter();
assertEquals("", hdr.getLeft()); assertEquals("", hdr.getLeft());
assertEquals("testdoc", hdr.getCenter()); assertEquals("testdoc", hdr.getCenter());
@ -128,10 +144,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals("", ftr.getLeft()); assertEquals("", ftr.getLeft());
assertEquals("", ftr.getCenter()); assertEquals("", ftr.getCenter());
assertEquals("", ftr.getRight()); assertEquals("", ftr.getRight());
wb2.close();
} }
@Test @Test
public void getAllHeadersFooters() { public void getAllHeadersFooters() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1"); XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertNotNull(sheet.getOddFooter()); assertNotNull(sheet.getOddFooter());
@ -168,10 +186,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
// Defaults are odd // Defaults are odd
assertEquals("odd footer left", sheet.getFooter().getLeft()); assertEquals("odd footer left", sheet.getFooter().getLeft());
assertEquals("odd header center", sheet.getHeader().getCenter()); assertEquals("odd header center", sheet.getHeader().getCenter());
workbook.close();
} }
@Test @Test
public void autoSizeColumn() { public void autoSizeColumn() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1"); XSSFSheet sheet = workbook.createSheet("Sheet 1");
sheet.createRow(0).createCell(13).setCellValue("test"); sheet.createRow(0).createCell(13).setCellValue("test");
@ -181,11 +201,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
ColumnHelper columnHelper = sheet.getColumnHelper(); ColumnHelper columnHelper = sheet.getColumnHelper();
CTCol col = columnHelper.getColumn(13, false); CTCol col = columnHelper.getColumn(13, false);
assertTrue(col.getBestFit()); assertTrue(col.getBestFit());
workbook.close();
} }
@Test @Test
public void setCellComment() { public void setCellComment() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
@ -200,20 +221,21 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals("A1", ctComments.getCommentList().getCommentArray(0).getRef()); assertEquals("A1", ctComments.getCommentList().getCommentArray(0).getRef());
comment.setAuthor("test A1 author"); comment.setAuthor("test A1 author");
assertEquals("test A1 author", comments.getAuthor((int) ctComments.getCommentList().getCommentArray(0).getAuthorId())); assertEquals("test A1 author", comments.getAuthor((int) ctComments.getCommentList().getCommentArray(0).getAuthorId()));
workbook.close();
} }
@Test @Test
public void getActiveCell() { public void getActiveCell() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
sheet.setActiveCell("R5"); sheet.setActiveCell("R5");
assertEquals("R5", sheet.getActiveCell()); assertEquals("R5", sheet.getActiveCell());
workbook.close();
} }
@Test @Test
public void createFreezePane_XSSF() { public void createFreezePane_XSSF() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
CTWorksheet ctWorksheet = sheet.getCTWorksheet(); CTWorksheet ctWorksheet = sheet.getCTWorksheet();
@ -228,10 +250,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
sheet.createSplitPane(4, 8, 12, 12, 1); sheet.createSplitPane(4, 8, 12, 12, 1);
assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0); assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0);
assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane());
workbook.close();
} }
@Test @Test
public void removeMergedRegion_lowlevel() { public void removeMergedRegion_lowlevel() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
CTWorksheet ctWorksheet = sheet.getCTWorksheet(); CTWorksheet ctWorksheet = sheet.getCTWorksheet();
@ -263,10 +287,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
sheet.removeMergedRegions(rmIdx); sheet.removeMergedRegions(rmIdx);
assertEquals("A1:B2", ctWorksheet.getMergeCells().getMergeCellArray(0).getRef()); assertEquals("A1:B2", ctWorksheet.getMergeCells().getMergeCellArray(0).getRef());
assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef());
workbook.close();
} }
@Test @Test
public void setDefaultColumnStyle() { public void setDefaultColumnStyle() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
CTWorksheet ctWorksheet = sheet.getCTWorksheet(); CTWorksheet ctWorksheet = sheet.getCTWorksheet();
@ -288,12 +313,13 @@ public final class TestXSSFSheet extends BaseTestSheet {
sheet.setDefaultColumnStyle(3, cellStyle); sheet.setDefaultColumnStyle(3, cellStyle);
assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle()); assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle());
workbook.close();
} }
@Test @Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void groupUngroupColumn() { public void groupUngroupColumn() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
@ -334,10 +360,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
colArray = cols.getColArray(); colArray = cols.getColArray();
assertEquals(4, colArray.length); assertEquals(4, colArray.length);
assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol());
workbook.close();
} }
@Test @Test
public void groupUngroupRow() { public void groupUngroupRow() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
@ -369,10 +397,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(3, sheet.getPhysicalNumberOfRows()); assertEquals(3, sheet.getPhysicalNumberOfRows());
assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
workbook.close();
} }
@Test @Test(expected=IllegalArgumentException.class)
public void setZoom() { public void setZoom() throws IOException {
XSSFWorkbook workBook = new XSSFWorkbook(); XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet1 = workBook.createSheet("new sheet"); XSSFSheet sheet1 = workBook.createSheet("new sheet");
sheet1.setZoom(3, 4); // 75 percent magnification sheet1.setZoom(3, 4); // 75 percent magnification
@ -383,11 +413,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale();
assertEquals(zoom, 200); assertEquals(zoom, 200);
// Valid scale values range from 10 to 400
try { try {
sheet1.setZoom(500); sheet1.setZoom(500);
fail("Expecting exception"); } finally {
} catch (IllegalArgumentException e) { workBook.close();
assertEquals("Valid scale values range from 10 to 400", e.getMessage());
} }
} }
@ -398,7 +428,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
* better should really review this! * better should really review this!
*/ */
@Test @Test
public void setColumnGroupCollapsed(){ public void setColumnGroupCollapsed() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
XSSFSheet sheet1 =(XSSFSheet) wb.createSheet(); XSSFSheet sheet1 =(XSSFSheet) wb.createSheet();
@ -620,6 +650,8 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(false,cols.getColArray(5).isSetCollapsed()); assertEquals(false,cols.getColArray(5).isSetCollapsed());
assertEquals(14, cols.getColArray(5).getMin()); // 1 based assertEquals(14, cols.getColArray(5).getMin()); // 1 based
assertEquals(14, cols.getColArray(5).getMax()); // 1 based assertEquals(14, cols.getColArray(5).getMax()); // 1 based
wb.close();
} }
/** /**
@ -629,7 +661,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
* better should really review this! * better should really review this!
*/ */
@Test @Test
public void setRowGroupCollapsed(){ public void setRowGroupCollapsed() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)wb.createSheet(); XSSFSheet sheet1 = (XSSFSheet)wb.createSheet();
@ -638,75 +670,77 @@ public final class TestXSSFSheet extends BaseTestSheet {
sheet1.groupRow( 16, 19 ); sheet1.groupRow( 16, 19 );
assertEquals(14,sheet1.getPhysicalNumberOfRows()); assertEquals(14,sheet1.getPhysicalNumberOfRows());
assertEquals(false,sheet1.getRow(6).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(6).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(6).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(7).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(7).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(7).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(9).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(9).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(9).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(14).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(14).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(14).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(16).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(18).getCTRow().isSetHidden());
//collapsed //collapsed
sheet1.setRowGroupCollapsed( 7, true ); sheet1.setRowGroupCollapsed( 7, true );
assertEquals(false,sheet1.getRow(6).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(6).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(6).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(7).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(7).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(7).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(9).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(9).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(9).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(14).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(14).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(14).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(16).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(18).getCTRow().isSetHidden());
//expanded //expanded
sheet1.setRowGroupCollapsed( 7, false ); sheet1.setRowGroupCollapsed( 7, false );
assertEquals(false,sheet1.getRow(6).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(6).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(6).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(7).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(7).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(7).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(9).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(9).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(9).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(14).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(14).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(14).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(16).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(18).getCTRow().isSetHidden());
// Save and re-load // Save and re-load
wb = XSSFTestDataSamples.writeOutAndReadBack(wb); wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet1 = (XSSFSheet)wb.getSheetAt(0); sheet1 = (XSSFSheet)wb.getSheetAt(0);
assertEquals(false,sheet1.getRow(6).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(6).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(6).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(7).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(7).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(7).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(9).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(9).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(9).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(14).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed());
assertEquals(true, sheet1.getRow(14).getCTRow().isSetHidden()); assertTrue (sheet1.getRow(14).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(16).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(16).getCTRow().isSetHidden());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetCollapsed()); assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed());
assertEquals(false,sheet1.getRow(18).getCTRow().isSetHidden()); assertFalse(sheet1.getRow(18).getCTRow().isSetHidden());
wb.close();
} }
/** /**
* Get / Set column width and check the actual values of the underlying XML beans * Get / Set column width and check the actual values of the underlying XML beans
*/ */
@Test @Test
public void columnWidth_lowlevel() { public void columnWidth_lowlevel() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1"); XSSFSheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnWidth(1, 22 * 256); sheet.setColumnWidth(1, 22 * 256);
@ -746,13 +780,15 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(4, col.getMax()); assertEquals(4, col.getMax());
assertEquals(33.0, col.getWidth(), 0.0); assertEquals(33.0, col.getWidth(), 0.0);
assertTrue(col.getCustomWidth()); assertTrue(col.getCustomWidth());
workbook.close();
} }
/** /**
* Setting width of a column included in a column span * Setting width of a column included in a column span
*/ */
@Test @Test
public void bug47862() { public void bug47862() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47862.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47862.xlsx");
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
CTCols cols = sheet.getCTWorksheet().getColsArray(0); CTCols cols = sheet.getCTWorksheet().getColsArray(0);
@ -803,13 +839,15 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(cw[i]*256, sheet.getColumnWidth(i)); assertEquals(cw[i]*256, sheet.getColumnWidth(i));
assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0);
} }
wb.close();
} }
/** /**
* Hiding a column included in a column span * Hiding a column included in a column span
*/ */
@Test @Test
public void bug47804() { public void bug47804() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47804.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47804.xlsx");
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
CTCols cols = sheet.getCTWorksheet().getColsArray(0); CTCols cols = sheet.getCTWorksheet().getColsArray(0);
@ -874,10 +912,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertFalse(sheet.isColumnHidden(3)); assertFalse(sheet.isColumnHidden(3));
assertFalse(sheet.isColumnHidden(4)); assertFalse(sheet.isColumnHidden(4));
assertFalse(sheet.isColumnHidden(5)); assertFalse(sheet.isColumnHidden(5));
wb.close();
} }
@Test @Test
public void commentsTable() { public void commentsTable() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet(); XSSFSheet sheet1 = workbook.createSheet();
CommentsTable comment1 = sheet1.getCommentsTable(false); CommentsTable comment1 = sheet1.getCommentsTable(false);
@ -910,6 +950,8 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertNotNull(comment1); assertNotNull(comment1);
assertEquals("/xl/comments1.xml", comment1.getPackageRelationship().getTargetURI().toString()); assertEquals("/xl/comments1.xml", comment1.getPackageRelationship().getTargetURI().toString());
assertSame(comment1, sheet1.getCommentsTable(true)); assertSame(comment1, sheet1.getCommentsTable(true));
workbook.close();
} }
/** /**
@ -919,7 +961,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
@Override @Override
@Test @Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void createRow() { public void createRow() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(); XSSFSheet sheet = workbook.createSheet();
CTWorksheet wsh = sheet.getCTWorksheet(); CTWorksheet wsh = sheet.getCTWorksheet();
@ -994,15 +1036,16 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(2, xrow[2].sizeOfCArray()); assertEquals(2, xrow[2].sizeOfCArray());
assertEquals(3, xrow[2].getR()); assertEquals(3, xrow[2].getR());
workbook.close();
} }
@Test @Test(expected=IllegalArgumentException.class)
public void createRowAfterLastRow() { public void createRowAfterLastRow() throws IOException {
createRowAfterLastRow(SpreadsheetVersion.EXCEL2007); createRowAfterLastRow(SpreadsheetVersion.EXCEL2007);
} }
@Test @Test
public void setAutoFilter() { public void setAutoFilter() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("new sheet"); XSSFSheet sheet = wb.createSheet("new sheet");
sheet.setAutoFilter(CellRangeAddress.valueOf("A1:D100")); sheet.setAutoFilter(CellRangeAddress.valueOf("A1:D100"));
@ -1017,10 +1060,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(true, nm.getCTName().getHidden()); assertEquals(true, nm.getCTName().getHidden());
assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName()); assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName());
assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue()); assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue());
wb.close();
} }
@Test @Test
public void protectSheet_lowlevel() { public void protectSheet_lowlevel() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection();
@ -1038,10 +1083,12 @@ public final class TestXSSFSheet extends BaseTestSheet {
sheet.protectSheet(null); sheet.protectSheet(null);
assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection()); assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection());
wb.close();
} }
@Test @Test
public void protectSheet_lowlevel_2013() { public void protectSheet_lowlevel_2013() throws IOException {
String password = "test"; String password = "test";
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet xs = wb.createSheet(); XSSFSheet xs = wb.createSheet();
@ -1051,17 +1098,19 @@ public final class TestXSSFSheet extends BaseTestSheet {
wb = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx"); wb = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx");
assertTrue(wb.getSheetAt(0).validateSheetPassword("pwd")); assertTrue(wb.getSheetAt(0).validateSheetPassword("pwd"));
wb.close();
} }
@Test @Test
public void bug49966() { public void bug49966() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49966.xlsx"); XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("49966.xlsx");
CalculationChain calcChain = wb.getCalculationChain(); CalculationChain calcChain = wb1.getCalculationChain();
assertNotNull(wb.getCalculationChain()); assertNotNull(wb1.getCalculationChain());
assertEquals(3, calcChain.getCTCalcChain().sizeOfCArray()); assertEquals(3, calcChain.getCTCalcChain().sizeOfCArray());
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb1.getSheetAt(0);
XSSFRow row = sheet.getRow(0); XSSFRow row = sheet.getRow(0);
sheet.removeRow(row); sheet.removeRow(row);
@ -1069,16 +1118,17 @@ public final class TestXSSFSheet extends BaseTestSheet {
0, calcChain.getCTCalcChain().sizeOfCArray()); 0, calcChain.getCTCalcChain().sizeOfCArray());
//calcChain should be gone //calcChain should be gone
wb = XSSFTestDataSamples.writeOutAndReadBack(wb); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
assertNull(wb.getCalculationChain()); wb1.close();
assertNull(wb2.getCalculationChain());
wb2.close();
} }
/** /**
* See bug #50829 * See bug #50829
*/ */
@Test @Test
public void tables() { public void tables() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx");
assertEquals(3, wb.getNumberOfSheets()); assertEquals(3, wb.getNumberOfSheets());
@ -1100,15 +1150,16 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(0, s2.getTables().size()); assertEquals(0, s2.getTables().size());
XSSFSheet s3 = wb.getSheetAt(2); XSSFSheet s3 = wb.getSheetAt(2);
assertEquals(0, s3.getTables().size()); assertEquals(0, s3.getTables().size());
wb.close();
} }
/** /**
* Test to trigger OOXML-LITE generating to include org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetCalcPr * Test to trigger OOXML-LITE generating to include org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetCalcPr
*/ */
@Test @Test
public void setForceFormulaRecalculation() { public void setForceFormulaRecalculation() throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1"); XSSFSheet sheet = wb1.createSheet("Sheet 1");
assertFalse(sheet.getForceFormulaRecalculation()); assertFalse(sheet.getForceFormulaRecalculation());
@ -1117,7 +1168,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(true, sheet.getForceFormulaRecalculation()); assertEquals(true, sheet.getForceFormulaRecalculation());
// calcMode="manual" is unset when forceFormulaRecalculation=true // calcMode="manual" is unset when forceFormulaRecalculation=true
CTCalcPr calcPr = workbook.getCTWorkbook().addNewCalcPr(); CTCalcPr calcPr = wb1.getCTWorkbook().addNewCalcPr();
calcPr.setCalcMode(STCalcMode.MANUAL); calcPr.setCalcMode(STCalcMode.MANUAL);
sheet.setForceFormulaRecalculation(true); sheet.setForceFormulaRecalculation(true);
assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
@ -1128,9 +1179,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
// Save, re-load, and re-check // Save, re-load, and re-check
workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = workbook.getSheet("Sheet 1"); wb1.close();
sheet = wb2.getSheet("Sheet 1");
assertEquals(false, sheet.getForceFormulaRecalculation()); assertEquals(false, sheet.getForceFormulaRecalculation());
wb2.close();
} }
@Test @Test
@ -1218,10 +1271,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
}*/ }*/
assertEquals("Sheet should contain 8 tables", 8, tables.size()); assertEquals("Sheet should contain 8 tables", 8, tables.size());
assertNotNull("Sheet should contain a comments table", sheet.getCommentsTable(false)); assertNotNull("Sheet should contain a comments table", sheet.getCommentsTable(false));
wb.close();
} }
@Test @Test
public void bug55723b(){ public void bug55723b() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -1245,11 +1299,13 @@ public final class TestXSSFSheet extends BaseTestSheet {
name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
assertNotNull(name); assertNotNull(name);
assertEquals("Sheet0!$B:$C", name.getRefersToFormula()); assertEquals("Sheet0!$B:$C", name.getRefersToFormula());
wb.close();
} }
@Test(timeout=180000) @Test(timeout=180000)
public void bug51585(){ public void bug51585() throws IOException {
XSSFTestDataSamples.openSampleWorkbook("51585.xlsx"); XSSFTestDataSamples.openSampleWorkbook("51585.xlsx").close();;
} }
private XSSFWorkbook setupSheet(){ private XSSFWorkbook setupSheet(){
@ -1279,7 +1335,7 @@ public final class TestXSSFSheet extends BaseTestSheet {
} }
@Test @Test
public void testCreateTwoPivotTablesInOneSheet(){ public void testCreateTwoPivotTablesInOneSheet() throws IOException {
XSSFWorkbook wb = setupSheet(); XSSFWorkbook wb = setupSheet();
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
@ -1291,10 +1347,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
XSSFPivotTable pivotTable2 = sheet.createPivotTable(new AreaReference("A1:B2"), new CellReference("L5"), sheet); XSSFPivotTable pivotTable2 = sheet.createPivotTable(new AreaReference("A1:B2"), new CellReference("L5"), sheet);
assertNotNull(pivotTable2); assertNotNull(pivotTable2);
assertTrue(wb.getPivotTables().size() > 1); assertTrue(wb.getPivotTables().size() > 1);
wb.close();
} }
@Test @Test
public void testCreateTwoPivotTablesInTwoSheets(){ public void testCreateTwoPivotTablesInTwoSheets() throws IOException {
XSSFWorkbook wb = setupSheet(); XSSFWorkbook wb = setupSheet();
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
@ -1308,10 +1365,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
XSSFPivotTable pivotTable2 = sheet2.createPivotTable(new AreaReference("A1:B2"), new CellReference("H5"), sheet); XSSFPivotTable pivotTable2 = sheet2.createPivotTable(new AreaReference("A1:B2"), new CellReference("H5"), sheet);
assertNotNull(pivotTable2); assertNotNull(pivotTable2);
assertTrue(wb.getPivotTables().size() > 1); assertTrue(wb.getPivotTables().size() > 1);
wb.close();
} }
@Test @Test
public void testCreatePivotTable(){ public void testCreatePivotTable() throws IOException {
XSSFWorkbook wb = setupSheet(); XSSFWorkbook wb = setupSheet();
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
@ -1320,10 +1378,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A1:B2"), new CellReference("H5")); XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
assertNotNull(pivotTable); assertNotNull(pivotTable);
assertTrue(wb.getPivotTables().size() > 0); assertTrue(wb.getPivotTables().size() > 0);
wb.close();
} }
@Test @Test
public void testCreatePivotTableInOtherSheetThanDataSheet(){ public void testCreatePivotTableInOtherSheetThanDataSheet() throws IOException {
XSSFWorkbook wb = setupSheet(); XSSFWorkbook wb = setupSheet();
XSSFSheet sheet1 = wb.getSheetAt(0); XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFSheet sheet2 = wb.createSheet(); XSSFSheet sheet2 = wb.createSheet();
@ -1335,10 +1394,11 @@ public final class TestXSSFSheet extends BaseTestSheet {
assertEquals(1, wb.getPivotTables().size()); assertEquals(1, wb.getPivotTables().size());
assertEquals(0, sheet1.getPivotTables().size()); assertEquals(0, sheet1.getPivotTables().size());
assertEquals(1, sheet2.getPivotTables().size()); assertEquals(1, sheet2.getPivotTables().size());
wb.close();
} }
@Test @Test
public void testCreatePivotTableInOtherSheetThanDataSheetUsingAreaReference(){ public void testCreatePivotTableInOtherSheetThanDataSheetUsingAreaReference() throws IOException {
XSSFWorkbook wb = setupSheet(); XSSFWorkbook wb = setupSheet();
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
XSSFSheet sheet2 = wb.createSheet(); XSSFSheet sheet2 = wb.createSheet();
@ -1346,47 +1406,41 @@ public final class TestXSSFSheet extends BaseTestSheet {
XSSFPivotTable pivotTable = sheet2.createPivotTable XSSFPivotTable pivotTable = sheet2.createPivotTable
(new AreaReference(sheet.getSheetName()+"!A$1:B$2"), new CellReference("H5")); (new AreaReference(sheet.getSheetName()+"!A$1:B$2"), new CellReference("H5"));
assertEquals(0, pivotTable.getRowLabelColumns().size()); assertEquals(0, pivotTable.getRowLabelColumns().size());
wb.close();
} }
@Test @Test(expected=IllegalArgumentException.class)
public void testCreatePivotTableWithConflictingDataSheets(){ public void testCreatePivotTableWithConflictingDataSheets() throws IOException {
XSSFWorkbook wb = setupSheet(); XSSFWorkbook wb = setupSheet();
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
XSSFSheet sheet2 = wb.createSheet(); XSSFSheet sheet2 = wb.createSheet();
try {
sheet2.createPivotTable(new AreaReference(sheet.getSheetName()+"!A$1:B$2"), new CellReference("H5"), sheet2); sheet2.createPivotTable(new AreaReference(sheet.getSheetName()+"!A$1:B$2"), new CellReference("H5"), sheet2);
} catch(IllegalArgumentException e) {
return;
}
fail();
} }
@Test @Test(expected=POIXMLException.class)
public void testReadFails() { public void testReadFails() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
try { // Throws exception because we cannot read here
sheet.onDocumentRead(); sheet.onDocumentRead();
fail("Throws exception because we cannot read here");
} catch (POIXMLException e) {
// expected here
}
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public void testCreateComment() { public void testCreateComment() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
assertNotNull(sheet.createComment()); assertNotNull(sheet.createComment());
wb.close();
} }
@Test @Test
public void testNoMergedRegionsIsEmptyList() { public void testNoMergedRegionsIsEmptyList() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(); XSSFSheet sheet = wb.createSheet();
assertTrue(sheet.getMergedRegions().isEmpty()); assertTrue(sheet.getMergedRegions().isEmpty());
wb.close();
} }
} }

View File

@ -126,7 +126,7 @@ public final class StyleDescription implements HDFType
// the upx will always start on a word boundary. // the upx will always start on a word boundary.
if(upxSize % 2 == 1) if((upxSize & 1) == 1)
{ {
++varOffset; ++varOffset;
} }

View File

@ -389,7 +389,7 @@ public final class CharacterSprmUncompressor extends SprmUncompressor
//byte hpsPos = (byte)((param & 0xff0000) >>> 8); //byte hpsPos = (byte)((param & 0xff0000) >>> 8);
byte hpsPos = (byte) ((operand & 0xff0000) >>> 16); byte hpsPos = (byte) ((operand & 0xff0000) >>> 16);
if (hpsPos != 0x80) if (hpsPos != (byte)0x80)
{ {
newCHP.setHpsPos (hpsPos); newCHP.setHpsPos (hpsPos);
} }

View File

@ -18,6 +18,7 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import static org.junit.Assert.*;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
@ -28,6 +29,7 @@ import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.SheetConditionalFormatting; import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test;
/** /**
* HSSF-specific Conditional Formatting tests * HSSF-specific Conditional Formatting tests
@ -51,18 +53,20 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm
} }
} }
public void testRead() { @Test
public void testRead() throws IOException {
testRead("WithConditionalFormatting.xls"); testRead("WithConditionalFormatting.xls");
} }
public void testReadOffice2007() { @Test
public void testReadOffice2007() throws IOException {
testReadOffice2007("NewStyleConditionalFormattings.xls"); testReadOffice2007("NewStyleConditionalFormattings.xls");
} }
@Test
public void test53691() throws IOException { public void test53691() throws IOException {
SheetConditionalFormatting cf; SheetConditionalFormatting cf;
final Workbook wb; final Workbook wb = HSSFITestDataProvider.instance.openSampleWorkbook("53691.xls");
wb = HSSFITestDataProvider.instance.openSampleWorkbook("53691.xls");
/* /*
FileInputStream s = new FileInputStream("C:\\temp\\53691bbadfixed.xls"); FileInputStream s = new FileInputStream("C:\\temp\\53691bbadfixed.xls");
try { try {
@ -101,6 +105,8 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm
removeConditionalFormatting(sheet); removeConditionalFormatting(sheet);
removeConditionalFormatting(wb.getSheetAt(0)); removeConditionalFormatting(wb.getSheetAt(0));
writeTemp53691(wb, "fgood"); writeTemp53691(wb, "fgood");
wb.close();
} }
private void removeConditionalFormatting(Sheet sheet) { private void removeConditionalFormatting(Sheet sheet) {
@ -110,18 +116,10 @@ public final class TestHSSFConditionalFormatting extends BaseTestConditionalForm
} }
} }
private void writeTemp53691(Workbook wb, String suffix) throws FileNotFoundException, private void writeTemp53691(Workbook wb, String suffix) throws FileNotFoundException, IOException {
IOException {
// assert that we can write/read it in memory // assert that we can write/read it in memory
Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb);
assertNotNull(wbBack); assertNotNull(wbBack);
wbBack.close();
/* Just necessary for local testing... */
/*OutputStream out = new FileOutputStream("C:\\temp\\53691" + suffix + ".xls");
try {
wb.write(out);
} finally {
out.close();
}*/
} }
} }

View File

@ -17,7 +17,10 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import junit.framework.AssertionFailedError; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
@ -31,6 +34,7 @@ import org.apache.poi.ss.formula.eval.ValueEval;
import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.CellValue;
import org.junit.Test;
/** /**
* *
@ -46,7 +50,8 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
* Test that the HSSFFormulaEvaluator can evaluate simple named ranges * Test that the HSSFFormulaEvaluator can evaluate simple named ranges
* (single cells and rectangular areas) * (single cells and rectangular areas)
*/ */
public void testEvaluateSimple() { @Test
public void testEvaluateSimple() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls");
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
HSSFCell cell = sheet.getRow(8).getCell(0); HSSFCell cell = sheet.getRow(8).getCell(0);
@ -54,13 +59,15 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
CellValue cv = fe.evaluate(cell); CellValue cv = fe.evaluate(cell);
assertEquals(HSSFCell.CELL_TYPE_NUMERIC, cv.getCellType()); assertEquals(HSSFCell.CELL_TYPE_NUMERIC, cv.getCellType());
assertEquals(3.72, cv.getNumberValue(), 0.0); assertEquals(3.72, cv.getNumberValue(), 0.0);
wb.close();
} }
/** /**
* Test for bug due to attempt to convert a cached formula error result to a boolean * Test for bug due to attempt to convert a cached formula error result to a boolean
*/ */
@Test
@Override @Override
public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() { public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sheet1"); HSSFSheet sheet = wb.createSheet("Sheet1");
@ -79,10 +86,12 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
fe.evaluateInCell(cellB1); fe.evaluateInCell(cellB1);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
if (e.getMessage().equals("Cannot get a numeric value from a error formula cell")) { if (e.getMessage().equals("Cannot get a numeric value from a error formula cell")) {
throw new AssertionFailedError("Identified bug 46479a"); fail("Identified bug 46479a");
} }
} }
assertEquals(3.5, cellB1.getNumericCellValue(), 0.0); assertEquals(3.5, cellB1.getNumericCellValue(), 0.0);
wb.close();
} }
/** /**
@ -92,7 +101,8 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
* which contained a simple area ref. It is not clear what the 'complex' flag is used * which contained a simple area ref. It is not clear what the 'complex' flag is used
* for but POI should look elsewhere to decide whether it can evaluate the name. * for but POI should look elsewhere to decide whether it can evaluate the name.
*/ */
public void testDefinedNameWithComplexFlag_bug47048() { @Test
public void testDefinedNameWithComplexFlag_bug47048() throws IOException {
// Mock up a spreadsheet to match the critical details of the sample // Mock up a spreadsheet to match the critical details of the sample
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Input"); HSSFSheet sheet = wb.createSheet("Input");
@ -118,16 +128,20 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
CellValue value; CellValue value;
try { try {
value = hsf.evaluate(cellA1); value = hsf.evaluate(cellA1);
} catch (RuntimeException e) {
if (e.getMessage().equals("Don't now how to evalate name 'Is_Multicar_Vehicle'")) {
throw new AssertionFailedError("Identified bug 47048a");
}
throw e;
}
assertEquals(Cell.CELL_TYPE_NUMERIC, value.getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, value.getCellType());
assertEquals(5.33, value.getNumberValue(), 0.0); assertEquals(5.33, value.getNumberValue(), 0.0);
} catch (RuntimeException e) {
if (e.getMessage().equals("Don't now how to evalate name 'Is_Multicar_Vehicle'")) {
fail("Identified bug 47048a");
} }
throw e;
} finally {
wb.close();
}
}
private static final class EvalCountListener extends EvaluationListener { private static final class EvalCountListener extends EvaluationListener {
private int _evalCount; private int _evalCount;
public EvalCountListener() { public EvalCountListener() {
@ -145,7 +159,8 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
/** /**
* The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values
*/ */
public void testShortCircuitIfEvaluation() { @Test
public void testShortCircuitIfEvaluation() throws IOException {
// Set up a simple IF() formula that has measurable evaluation cost for its operands. // Set up a simple IF() formula that has measurable evaluation cost for its operands.
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
@ -166,23 +181,26 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
int evalCount = evalListener.getEvalCount(); int evalCount = evalListener.getEvalCount();
if (evalCount == 6) { if (evalCount == 6) {
// Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1) // Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1)
throw new AssertionFailedError("Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations."); fail("Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations.");
} }
assertEquals(3, evalCount); assertEquals(3, evalCount);
assertEquals(2.0, ((NumberEval)ve).getNumberValue(), 0D); assertEquals(2.0, ((NumberEval)ve).getNumberValue(), 0D);
wb.close();
} }
/** /**
* Ensures that we can handle NameXPtgs in the formulas * Ensures that we can handle NameXPtgs in the formulas
* we parse. * we parse.
*/ */
public void testXRefs() throws Exception { @Test
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); public void testXRefs() throws IOException {
HSSFWorkbook wbData = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls");
HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls");
Cell cell; Cell cell;
// VLookup on a name in another file // VLookup on a name in another file
cell = wb.getSheetAt(0).getRow(1).getCell(2); cell = wb1.getSheetAt(0).getRow(1).getCell(2);
assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType()); assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType()); assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType());
assertEquals(12.30, cell.getNumericCellValue(), 0.0001); assertEquals(12.30, cell.getNumericCellValue(), 0.0001);
@ -193,7 +211,7 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
// Simple reference to a name in another file // Simple reference to a name in another file
cell = wb.getSheetAt(0).getRow(1).getCell(4); cell = wb1.getSheetAt(0).getRow(1).getCell(4);
assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType()); assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType()); assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType());
assertEquals(36.90, cell.getNumericCellValue(), 0.0001); assertEquals(36.90, cell.getNumericCellValue(), 0.0001);
@ -203,37 +221,37 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
// Evaluate the cells // Evaluate the cells
HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1);
HSSFFormulaEvaluator.setupEnvironment( HSSFFormulaEvaluator.setupEnvironment(
new String[] { "XRefCalc.xls", "XRefCalcData.xls" }, new String[] { "XRefCalc.xls", "XRefCalcData.xls" },
new HSSFFormulaEvaluator[] { new HSSFFormulaEvaluator[] {
eval, eval,
new HSSFFormulaEvaluator(wbData) new HSSFFormulaEvaluator(wb2)
} }
); );
eval.evaluateFormulaCell( eval.evaluateFormulaCell(
wb.getSheetAt(0).getRow(1).getCell(2) wb1.getSheetAt(0).getRow(1).getCell(2)
); );
eval.evaluateFormulaCell( eval.evaluateFormulaCell(
wb.getSheetAt(0).getRow(1).getCell(4) wb1.getSheetAt(0).getRow(1).getCell(4)
); );
// Re-check VLOOKUP one // Re-check VLOOKUP one
cell = wb.getSheetAt(0).getRow(1).getCell(2); cell = wb1.getSheetAt(0).getRow(1).getCell(2);
assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType()); assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType()); assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType());
assertEquals(12.30, cell.getNumericCellValue(), 0.0001); assertEquals(12.30, cell.getNumericCellValue(), 0.0001);
// Re-check ref one // Re-check ref one
cell = wb.getSheetAt(0).getRow(1).getCell(4); cell = wb1.getSheetAt(0).getRow(1).getCell(4);
assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType()); assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType()); assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCachedFormulaResultType());
assertEquals(36.90, cell.getNumericCellValue(), 0.0001); assertEquals(36.90, cell.getNumericCellValue(), 0.0001);
// Add a formula that refers to one of the existing external workbooks // Add a formula that refers to one of the existing external workbooks
cell = wb.getSheetAt(0).getRow(1).createCell(40); cell = wb1.getSheetAt(0).getRow(1).createCell(40);
cell.setCellFormula("Cost*[XRefCalcData.xls]MarkupSheet!$B$1"); cell.setCellFormula("Cost*[XRefCalcData.xls]MarkupSheet!$B$1");
// Check is was stored correctly // Check is was stored correctly
@ -241,20 +259,20 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
// Check it evaluates correctly // Check it evaluates correctly
eval.evaluateFormulaCell(cell); eval.evaluateFormulaCell(cell);
assertEquals(24.60*1.8, cell.getNumericCellValue()); assertEquals(24.60*1.8, cell.getNumericCellValue(), 0);
// Try to add a formula for a new external workbook, won't be allowed to start // Try to add a formula for a new external workbook, won't be allowed to start
try { try {
cell = wb.getSheetAt(0).getRow(1).createCell(42); cell = wb1.getSheetAt(0).getRow(1).createCell(42);
cell.setCellFormula("[alt.xls]Sheet0!$A$1"); cell.setCellFormula("[alt.xls]Sheet0!$A$1");
fail("New workbook not linked, shouldn't be able to add"); fail("New workbook not linked, shouldn't be able to add");
} catch(Exception e) {} } catch(Exception e) {}
// Link our new workbook // Link our new workbook
HSSFWorkbook alt = new HSSFWorkbook(); HSSFWorkbook wb3 = new HSSFWorkbook();
alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); wb3.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
wb.linkExternalWorkbook("alt.xls", alt); wb1.linkExternalWorkbook("alt.xls", wb3);
// Now add a formula that refers to our new workbook // Now add a formula that refers to our new workbook
cell.setCellFormula("[alt.xls]Sheet0!$A$1"); cell.setCellFormula("[alt.xls]Sheet0!$A$1");
@ -271,8 +289,8 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
new String[] { "XRefCalc.xls", "XRefCalcData.xls", "alt.xls" }, new String[] { "XRefCalc.xls", "XRefCalcData.xls", "alt.xls" },
new HSSFFormulaEvaluator[] { new HSSFFormulaEvaluator[] {
eval, eval,
new HSSFFormulaEvaluator(wbData), new HSSFFormulaEvaluator(wb2),
new HSSFFormulaEvaluator(alt) new HSSFFormulaEvaluator(wb3)
} }
); );
eval.evaluateFormulaCell(cell); eval.evaluateFormulaCell(cell);
@ -280,31 +298,37 @@ public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
// Save and re-load // Save and re-load
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
eval = new HSSFFormulaEvaluator(wb); eval = new HSSFFormulaEvaluator(wb4);
HSSFFormulaEvaluator.setupEnvironment( HSSFFormulaEvaluator.setupEnvironment(
new String[] { "XRefCalc.xls", "XRefCalcData.xls", "alt.xls" }, new String[] { "XRefCalc.xls", "XRefCalcData.xls", "alt.xls" },
new HSSFFormulaEvaluator[] { new HSSFFormulaEvaluator[] {
eval, eval,
new HSSFFormulaEvaluator(wbData), new HSSFFormulaEvaluator(wb2),
new HSSFFormulaEvaluator(alt) new HSSFFormulaEvaluator(wb3)
} }
); );
// Check the one referring to the previously existing workbook behaves // Check the one referring to the previously existing workbook behaves
cell = wb.getSheetAt(0).getRow(1).getCell(40); cell = wb4.getSheetAt(0).getRow(1).getCell(40);
assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula()); assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula());
eval.evaluateFormulaCell(cell); eval.evaluateFormulaCell(cell);
assertEquals(24.60*1.8, cell.getNumericCellValue()); assertEquals(24.60*1.8, cell.getNumericCellValue(), 0);
// Now check the newly added reference // Now check the newly added reference
cell = wb.getSheetAt(0).getRow(1).getCell(42); cell = wb4.getSheetAt(0).getRow(1).getCell(42);
assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula()); assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula());
eval.evaluateFormulaCell(cell); eval.evaluateFormulaCell(cell);
assertEquals("In another workbook", cell.getStringCellValue()); assertEquals("In another workbook", cell.getStringCellValue());
wb4.close();
wb3.close();
wb2.close();
wb1.close();
} }
public void testSharedFormulas(){ @Test
public void testSharedFormulas() throws IOException {
baseTestSharedFormulas("shared_formulas.xls"); baseTestSharedFormulas("shared_formulas.xls");
} }

View File

@ -19,15 +19,14 @@ package org.apache.poi.hssf.usermodel;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.File; import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List; import java.util.List;
import org.apache.poi.ddf.EscherDgRecord; import org.apache.poi.ddf.EscherDgRecord;
@ -70,7 +69,6 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.util.TempFile;
import org.junit.Test; import org.junit.Test;
/** /**
@ -86,8 +84,8 @@ public final class TestHSSFSheet extends BaseTestSheet {
super(HSSFITestDataProvider.instance); super(HSSFITestDataProvider.instance);
} }
@Test @Test(expected=IllegalArgumentException.class)
public void createRowAfterLastRow() { public void createRowAfterLastRow() throws IOException {
createRowAfterLastRow(SpreadsheetVersion.EXCEL97); createRowAfterLastRow(SpreadsheetVersion.EXCEL97);
} }
@ -96,7 +94,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* Moved from TestHSSFWorkbook#testSetRepeatingRowsAndColumns(). * Moved from TestHSSFWorkbook#testSetRepeatingRowsAndColumns().
*/ */
@Test @Test
public void setRepeatingRowsAndColumnsBug29747() { public void setRepeatingRowsAndColumnsBug29747() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet(); wb.createSheet();
wb.createSheet(); wb.createSheet();
@ -104,11 +102,12 @@ public final class TestHSSFSheet extends BaseTestSheet {
sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:2")); sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:2"));
NameRecord nameRecord = wb.getWorkbook().getNameRecord(0); NameRecord nameRecord = wb.getWorkbook().getNameRecord(0);
assertEquals(3, nameRecord.getSheetNumber()); assertEquals(3, nameRecord.getSheetNumber());
wb.close();
} }
@Test @Test
public void getSetMargin() { public void getSetMargin() throws IOException {
baseTestGetSetMargin(new double[]{0.75, 0.75, 1.0, 1.0, 0.3, 0.3}); baseTestGetSetMargin(new double[]{0.75, 0.75, 1.0, 1.0, 0.3, 0.3});
} }
@ -116,13 +115,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
* Test the gridset field gets set as expected. * Test the gridset field gets set as expected.
*/ */
@Test @Test
public void backupRecord() { public void backupRecord() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
GridsetRecord gridsetRec = s.getSheet().getGridsetRecord(); GridsetRecord gridsetRec = s.getSheet().getGridsetRecord();
assertTrue(gridsetRec.getGridset()); assertTrue(gridsetRec.getGridset());
s.setGridsPrinted(true); s.setGridsPrinted(true);
assertFalse(gridsetRec.getGridset()); assertFalse(gridsetRec.getGridset());
wb.close();
} }
/** /**
@ -130,7 +130,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public void verticallyCenter() { public void verticallyCenter() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
VCenterRecord record = s.getSheet().getPageSettings().getVCenter(); VCenterRecord record = s.getSheet().getPageSettings().getVCenter();
@ -143,14 +143,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertTrue(s.getVerticallyCenter(true)); assertTrue(s.getVerticallyCenter(true));
assertTrue(s.getVerticallyCenter(false)); assertTrue(s.getVerticallyCenter(false));
// wb.write(new FileOutputStream("c:\\test.xls")); wb.close();
} }
/** /**
* Test horizontally centered output. * Test horizontally centered output.
*/ */
@Test @Test
public void horizontallyCenter() { public void horizontallyCenter() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
HCenterRecord record = s.getSheet().getPageSettings().getHCenter(); HCenterRecord record = s.getSheet().getPageSettings().getHCenter();
@ -158,6 +158,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertFalse(record.getHCenter()); assertFalse(record.getHCenter());
s.setHorizontallyCenter(true); s.setHorizontallyCenter(true);
assertTrue(record.getHCenter()); assertTrue(record.getHCenter());
wb.close();
} }
@ -165,7 +166,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* Test WSBboolRecord fields get set in the user model. * Test WSBboolRecord fields get set in the user model.
*/ */
@Test @Test
public void wsBool() { public void wsBool() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
WSBoolRecord record = WSBoolRecord record =
@ -208,20 +209,22 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertFalse(s.getFitToPage()); assertFalse(s.getFitToPage());
assertTrue(s.getRowSumsBelow()); assertTrue(s.getRowSumsBelow());
assertTrue(s.getRowSumsRight()); assertTrue(s.getRowSumsRight());
wb.close();
} }
/** /**
* Setting landscape and portrait stuff on existing sheets * Setting landscape and portrait stuff on existing sheets
*/ */
@Test @Test
public void printSetupLandscapeExisting() { public void printSetupLandscapeExisting() throws IOException {
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls");
assertEquals(3, workbook.getNumberOfSheets()); assertEquals(3, wb1.getNumberOfSheets());
HSSFSheet sheetL = workbook.getSheetAt(0); HSSFSheet sheetL = wb1.getSheetAt(0);
HSSFSheet sheetPM = workbook.getSheetAt(1); HSSFSheet sheetPM = wb1.getSheetAt(1);
HSSFSheet sheetLS = workbook.getSheetAt(2); HSSFSheet sheetLS = wb1.getSheetAt(2);
// Check two aspects of the print setup // Check two aspects of the print setup
assertFalse(sheetL.getPrintSetup().getLandscape()); assertFalse(sheetL.getPrintSetup().getLandscape());
@ -245,7 +248,12 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(1, sheetLS.getPrintSetup().getCopies()); assertEquals(1, sheetLS.getPrintSetup().getCopies());
// Save and re-load, and check still there // Save and re-load, and check still there
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheetL = wb1.getSheetAt(0);
sheetPM = wb1.getSheetAt(1);
sheetLS = wb1.getSheetAt(2);
assertTrue(sheetL.getPrintSetup().getLandscape()); assertTrue(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetPM.getPrintSetup().getLandscape()); assertFalse(sheetPM.getPrintSetup().getLandscape());
@ -253,12 +261,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(1, sheetL.getPrintSetup().getCopies()); assertEquals(1, sheetL.getPrintSetup().getCopies());
assertEquals(3, sheetPM.getPrintSetup().getCopies()); assertEquals(3, sheetPM.getPrintSetup().getCopies());
assertEquals(1, sheetLS.getPrintSetup().getCopies()); assertEquals(1, sheetLS.getPrintSetup().getCopies());
wb2.close();
} }
@Test @Test
public void groupRows() { public void groupRows() throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet s = workbook.createSheet(); HSSFSheet s = wb1.createSheet();
HSSFRow r1 = s.createRow(0); HSSFRow r1 = s.createRow(0);
HSSFRow r2 = s.createRow(1); HSSFRow r2 = s.createRow(1);
HSSFRow r3 = s.createRow(2); HSSFRow r3 = s.createRow(2);
@ -280,9 +290,10 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(0, r5.getOutlineLevel()); assertEquals(0, r5.getOutlineLevel());
// Save and re-open // Save and re-open
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
s = workbook.getSheetAt(0); s = wb2.getSheetAt(0);
r1 = s.getRow(0); r1 = s.getRow(0);
r2 = s.getRow(1); r2 = s.getRow(1);
r3 = s.getRow(2); r3 = s.getRow(2);
@ -294,13 +305,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(1, r3.getOutlineLevel()); assertEquals(1, r3.getOutlineLevel());
assertEquals(1, r4.getOutlineLevel()); assertEquals(1, r4.getOutlineLevel());
assertEquals(0, r5.getOutlineLevel()); assertEquals(0, r5.getOutlineLevel());
wb2.close();
} }
@Test @Test
public void groupRowsExisting() { public void groupRowsExisting() throws IOException {
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("NoGutsRecords.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("NoGutsRecords.xls");
HSSFSheet s = workbook.getSheetAt(0); HSSFSheet s = wb1.getSheetAt(0);
HSSFRow r1 = s.getRow(0); HSSFRow r1 = s.getRow(0);
HSSFRow r2 = s.getRow(1); HSSFRow r2 = s.getRow(1);
HSSFRow r3 = s.getRow(2); HSSFRow r3 = s.getRow(2);
@ -326,13 +338,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(0, r6.getOutlineLevel()); assertEquals(0, r6.getOutlineLevel());
// Save and re-open // Save and re-open
HSSFWorkbook wb2 = null;
try { try {
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
fail("Identified bug 39903"); fail("Identified bug 39903");
} }
s = workbook.getSheetAt(0); s = wb2.getSheetAt(0);
r1 = s.getRow(0); r1 = s.getRow(0);
r2 = s.getRow(1); r2 = s.getRow(1);
r3 = s.getRow(2); r3 = s.getRow(2);
@ -346,19 +359,23 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(1, r4.getOutlineLevel()); assertEquals(1, r4.getOutlineLevel());
assertEquals(1, r5.getOutlineLevel()); assertEquals(1, r5.getOutlineLevel());
assertEquals(0, r6.getOutlineLevel()); assertEquals(0, r6.getOutlineLevel());
wb2.close();
wb1.close();
} }
@Test @Test
public void createDrawings() { public void createDrawings() throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(); HSSFSheet sheet = workbook.createSheet();
HSSFPatriarch p1 = sheet.createDrawingPatriarch(); HSSFPatriarch p1 = sheet.createDrawingPatriarch();
HSSFPatriarch p2 = sheet.createDrawingPatriarch(); HSSFPatriarch p2 = sheet.createDrawingPatriarch();
assertSame(p1, p2); assertSame(p1, p2);
workbook.close();
} }
@Test @Test
public void getDrawings() { public void getDrawings() throws IOException {
HSSFWorkbook wb1c = HSSFTestDataSamples.openSampleWorkbook("WithChart.xls"); HSSFWorkbook wb1c = HSSFTestDataSamples.openSampleWorkbook("WithChart.xls");
HSSFWorkbook wb2c = HSSFTestDataSamples.openSampleWorkbook("WithTwoCharts.xls"); HSSFWorkbook wb2c = HSSFTestDataSamples.openSampleWorkbook("WithTwoCharts.xls");
@ -377,13 +394,15 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertFalse(wb2c.getSheetAt(0).getDrawingPatriarch().containsChart()); assertFalse(wb2c.getSheetAt(0).getDrawingPatriarch().containsChart());
assertTrue(wb2c.getSheetAt(1).getDrawingPatriarch().containsChart()); assertTrue(wb2c.getSheetAt(1).getDrawingPatriarch().containsChart());
assertTrue(wb2c.getSheetAt(2).getDrawingPatriarch().containsChart()); assertTrue(wb2c.getSheetAt(2).getDrawingPatriarch().containsChart());
wb2c.close();
wb1c.close();
} }
/** /**
* Test that the ProtectRecord is included when creating or cloning a sheet * Test that the ProtectRecord is included when creating or cloning a sheet
*/ */
@Test @Test
public void cloneWithProtect() { public void cloneWithProtect() throws IOException {
String passwordA = "secrect"; String passwordA = "secrect";
int expectedHashA = -6810; int expectedHashA = -6810;
String passwordB = "admin"; String passwordB = "admin";
@ -409,10 +428,11 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(expectedHashB, hssfSheet.getPassword()); assertEquals(expectedHashB, hssfSheet.getPassword());
// but the cloned sheet's password should remain unchanged // but the cloned sheet's password should remain unchanged
assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash()); assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash());
workbook.close();
} }
@Test @Test
public void protectSheetA() { public void protectSheetA() throws IOException {
int expectedHash = (short)0xfef1; int expectedHash = (short)0xfef1;
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
@ -422,6 +442,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertTrue("object protection should be on",pb.isObjectProtected()); assertTrue("object protection should be on",pb.isObjectProtected());
assertTrue("scenario protection should be on",pb.isScenarioProtected()); assertTrue("scenario protection should be on",pb.isScenarioProtected());
assertEquals("well known value for top secret hash should be "+Integer.toHexString(expectedHash).substring(4), expectedHash, pb.getPasswordHash()); assertEquals("well known value for top secret hash should be "+Integer.toHexString(expectedHash).substring(4), expectedHash, pb.getPasswordHash());
wb.close();
} }
/** /**
@ -429,7 +450,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* (which should be before {@link DimensionsRecord}). * (which should be before {@link DimensionsRecord}).
*/ */
@Test @Test
public void protectSheetRecordOrder_bug47363a() { public void protectSheetRecordOrder_bug47363a() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
s.protectSheet("secret"); s.protectSheet("secret");
@ -446,6 +467,8 @@ public final class TestHSSFSheet extends BaseTestSheet {
confirmRecordClass(recs, nRecs-8, ObjectProtectRecord.class); confirmRecordClass(recs, nRecs-8, ObjectProtectRecord.class);
confirmRecordClass(recs, nRecs-7, ScenarioProtectRecord.class); confirmRecordClass(recs, nRecs-7, ScenarioProtectRecord.class);
confirmRecordClass(recs, nRecs-6, PasswordRecord.class); confirmRecordClass(recs, nRecs-6, PasswordRecord.class);
wb.close();
} }
private static void confirmRecordClass(Record[] recs, int index, Class<? extends Record> cls) { private static void confirmRecordClass(Record[] recs, int index, Class<? extends Record> cls) {
@ -460,7 +483,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* There should be no problem with adding data validations after sheet protection * There should be no problem with adding data validations after sheet protection
*/ */
@Test @Test
public void dvProtectionOrder_bug47363b() { public void dvProtectionOrder_bug47363b() throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1"); HSSFSheet sheet = workbook.createSheet("Sheet1");
sheet.protectSheet("secret"); sheet.protectSheet("secret");
@ -476,6 +499,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
if (expMsg.equals(e.getMessage())) { if (expMsg.equals(e.getMessage())) {
fail("Identified bug 47363b"); fail("Identified bug 47363b");
} }
workbook.close();
throw e; throw e;
} }
RecordCollector rc; RecordCollector rc;
@ -489,10 +513,12 @@ public final class TestHSSFSheet extends BaseTestSheet {
int nRecsWithoutProtection = rc.getRecords().length; int nRecsWithoutProtection = rc.getRecords().length;
assertEquals(4, nRecsWithProtection - nRecsWithoutProtection); assertEquals(4, nRecsWithProtection - nRecsWithoutProtection);
workbook.close();
} }
@Test @Test
public void zoom() { public void zoom() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid)); assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid));
@ -531,6 +557,8 @@ public final class TestHSSFSheet extends BaseTestSheet {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage());
} }
wb.close();
} }
@ -539,10 +567,10 @@ public final class TestHSSFSheet extends BaseTestSheet {
* Make sure the excel file loads work * Make sure the excel file loads work
*/ */
@Test @Test
public void pageBreakFiles() { public void pageBreakFiles() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls");
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb1.getSheetAt(0);
assertNotNull(sheet); assertNotNull(sheet);
assertEquals("1 row page break", 1, sheet.getRowBreaks().length); assertEquals("1 row page break", 1, sheet.getRowBreaks().length);
@ -557,22 +585,26 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals("row breaks number", 2, sheet.getRowBreaks().length); assertEquals("row breaks number", 2, sheet.getRowBreaks().length);
assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); assertEquals("column breaks number", 2, sheet.getColumnBreaks().length);
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
assertTrue("No row page break", sheet.isRowBroken(22)); assertTrue("No row page break", sheet.isRowBroken(22));
assertTrue("No column page break", sheet.isColumnBroken((short)4)); assertTrue("No column page break", sheet.isColumnBroken((short)4));
assertEquals("row breaks number", 2, sheet.getRowBreaks().length); assertEquals("row breaks number", 2, sheet.getRowBreaks().length);
assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); assertEquals("column breaks number", 2, sheet.getColumnBreaks().length);
wb2.close();
} }
@Test @Test
public void dbcsName () { public void dbcsName () throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSSheetName.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSSheetName.xls");
wb.getSheetAt(1); wb.getSheetAt(1);
assertEquals ("DBCS Sheet Name 2", wb.getSheetName(1),"\u090f\u0915" ); assertEquals ("DBCS Sheet Name 2", wb.getSheetName(1),"\u090f\u0915" );
assertEquals("DBCS Sheet Name 1", wb.getSheetName(0),"\u091c\u093e"); assertEquals("DBCS Sheet Name 1", wb.getSheetName(0),"\u091c\u093e");
wb.close();
} }
/** /**
@ -581,7 +613,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* of the sheet when it is first opened. * of the sheet when it is first opened.
*/ */
@Test @Test
public void topRow() { public void topRow() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls");
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
@ -592,34 +624,38 @@ public final class TestHSSFSheet extends BaseTestSheet {
sheet.showInPane(toprow,leftcol); sheet.showInPane(toprow,leftcol);
assertEquals("HSSFSheet.getTopRow()", toprow, sheet.getTopRow()); assertEquals("HSSFSheet.getTopRow()", toprow, sheet.getTopRow());
assertEquals("HSSFSheet.getLeftCol()", leftcol, sheet.getLeftCol()); assertEquals("HSSFSheet.getLeftCol()", leftcol, sheet.getLeftCol());
wb.close();
} }
@Test @Test
public void addEmptyRow() { public void addEmptyRow() throws IOException {
//try to add 5 empty rows to a new sheet //try to add 5 empty rows to a new sheet
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(); HSSFSheet sheet = wb1.createSheet();
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
sheet.createRow(i); sheet.createRow(i);
} }
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); HSSFTestDataSamples.writeOutAndReadBack(wb1).close();
wb1.close();
//try adding empty rows in an existing worksheet //try adding empty rows in an existing worksheet
workbook = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls");
sheet = workbook.getSheetAt(0); sheet = wb2.getSheetAt(0);
for (int i = 3; i < 10; i++) sheet.createRow(i); for (int i = 3; i < 10; i++) sheet.createRow(i);
workbook = HSSFTestDataSamples.writeOutAndReadBack(workbook); HSSFTestDataSamples.writeOutAndReadBack(wb2).close();
wb2.close();
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public void autoSizeColumn() { public void autoSizeColumn() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("43902.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("43902.xls");
String sheetName = "my sheet"; String sheetName = "my sheet";
HSSFSheet sheet = wb.getSheet(sheetName); HSSFSheet sheet = wb1.getSheet(sheetName);
// Can't use literal numbers for column sizes, as // Can't use literal numbers for column sizes, as
// will come out with different values on different // will come out with different values on different
@ -641,7 +677,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
sheet.addMergedRegion(new CellRangeAddress(1,1,0,1)); sheet.addMergedRegion(new CellRangeAddress(1,1,0,1));
assertNotNull(sheet.getMergedRegionAt(0)); assertNotNull(sheet.getMergedRegionAt(0));
sheet.autoSizeColumn((short)0); sheet.autoSizeColumn((short)0);
HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
// check that the autoSized column width has ignored the 2nd row // check that the autoSized column width has ignored the 2nd row
// because it is included in a merged region (Excel like behavior) // because it is included in a merged region (Excel like behavior)
@ -656,17 +692,22 @@ public final class TestHSSFSheet extends BaseTestSheet {
HSSFSheet sheet3 = wb3.getSheet(sheetName); HSSFSheet sheet3 = wb3.getSheet(sheetName);
assertTrue(sheet3.getColumnWidth(0) >= minWithRow1And2); assertTrue(sheet3.getColumnWidth(0) >= minWithRow1And2);
assertTrue(sheet3.getColumnWidth(0) <= maxWithRow1And2); assertTrue(sheet3.getColumnWidth(0) <= maxWithRow1And2);
wb3.close();
wb2.close();
wb1.close();
} }
@Test @Test
public void testNoMergedRegionsIsEmptyList() { public void testNoMergedRegionsIsEmptyList() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet("Sheet1"); HSSFSheet s = wb.createSheet("Sheet1");
assertTrue(s.getMergedRegions().isEmpty()); assertTrue(s.getMergedRegions().isEmpty());
wb.close();
} }
@Test @Test
public void autoSizeDate() throws Exception { public void autoSizeDate() throws IOException {
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);
@ -701,17 +742,19 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertTrue("Date column too small: " + s.getColumnWidth(1), s.getColumnWidth(1) > 4750); assertTrue("Date column too small: " + s.getColumnWidth(1), s.getColumnWidth(1) > 4750);
assertTrue("Date column too big: " + s.getColumnWidth(0), s.getColumnWidth(0) < 6500); assertTrue("Date column too big: " + s.getColumnWidth(0), s.getColumnWidth(0) < 6500);
assertTrue("Date column too big: " + s.getColumnWidth(0), s.getColumnWidth(0) < 6500); assertTrue("Date column too big: " + s.getColumnWidth(0), s.getColumnWidth(0) < 6500);
wb.close();
} }
/** /**
* Setting ForceFormulaRecalculation on sheets * Setting ForceFormulaRecalculation on sheets
*/ */
@Test @Test
public void forceRecalculation() throws Exception { public void forceRecalculation() throws IOException {
HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("UncalcedRecord.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("UncalcedRecord.xls");
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = wb1.getSheetAt(0);
HSSFSheet sheet2 = workbook.getSheetAt(0); HSSFSheet sheet2 = wb1.getSheetAt(0);
HSSFRow row = sheet.getRow(0); HSSFRow row = sheet.getRow(0);
row.createCell(0).setCellValue(5); row.createCell(0).setCellValue(5);
row.createCell(1).setCellValue(8); row.createCell(1).setCellValue(8);
@ -719,22 +762,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertFalse(sheet2.getForceFormulaRecalculation()); assertFalse(sheet2.getForceFormulaRecalculation());
// Save and manually verify that on column C we have 0, value in template // Save and manually verify that on column C we have 0, value in template
File tempFile = TempFile.createTempFile("uncalced_err", ".xls" ); HSSFTestDataSamples.writeOutAndReadBack(wb1).close();
FileOutputStream fout = new FileOutputStream( tempFile );
workbook.write( fout );
fout.close();
sheet.setForceFormulaRecalculation(true); sheet.setForceFormulaRecalculation(true);
assertTrue(sheet.getForceFormulaRecalculation()); assertTrue(sheet.getForceFormulaRecalculation());
// Save and manually verify that on column C we have now 13, calculated value // Save and manually verify that on column C we have now 13, calculated value
tempFile = TempFile.createTempFile("uncalced_succ", ".xls");
tempFile.delete();
fout = new FileOutputStream( tempFile );
workbook.write( fout );
fout.close();
// Try it can be opened // Try it can be opened
HSSFWorkbook wb2 = new HSSFWorkbook(new FileInputStream(tempFile)); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
// And check correct sheet settings found // And check correct sheet settings found
sheet = wb2.getSheetAt(0); sheet = wb2.getSheetAt(0);
@ -745,44 +780,41 @@ public final class TestHSSFSheet extends BaseTestSheet {
// Now turn if back off again // Now turn if back off again
sheet.setForceFormulaRecalculation(false); sheet.setForceFormulaRecalculation(false);
fout = new FileOutputStream( tempFile ); HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
wb2.write( fout ); wb2.close();
fout.close();
wb2 = new HSSFWorkbook(new FileInputStream(tempFile));
assertFalse(wb2.getSheetAt(0).getForceFormulaRecalculation()); assertFalse(wb3.getSheetAt(0).getForceFormulaRecalculation());
assertFalse(wb2.getSheetAt(1).getForceFormulaRecalculation()); assertFalse(wb3.getSheetAt(1).getForceFormulaRecalculation());
assertFalse(wb2.getSheetAt(2).getForceFormulaRecalculation()); assertFalse(wb3.getSheetAt(2).getForceFormulaRecalculation());
// Now add a new sheet, and check things work // Now add a new sheet, and check things work
// with old ones unset, new one set // with old ones unset, new one set
HSSFSheet s4 = wb2.createSheet(); HSSFSheet s4 = wb3.createSheet();
s4.setForceFormulaRecalculation(true); s4.setForceFormulaRecalculation(true);
assertFalse(sheet.getForceFormulaRecalculation()); assertFalse(sheet.getForceFormulaRecalculation());
assertFalse(sheet2.getForceFormulaRecalculation()); assertFalse(sheet2.getForceFormulaRecalculation());
assertTrue(s4.getForceFormulaRecalculation()); assertTrue(s4.getForceFormulaRecalculation());
fout = new FileOutputStream( tempFile ); HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
wb2.write( fout ); wb3.close();
fout.close();
HSSFWorkbook wb3 = new HSSFWorkbook(new FileInputStream(tempFile)); assertFalse(wb4.getSheetAt(0).getForceFormulaRecalculation());
assertFalse(wb3.getSheetAt(0).getForceFormulaRecalculation()); assertFalse(wb4.getSheetAt(1).getForceFormulaRecalculation());
assertFalse(wb3.getSheetAt(1).getForceFormulaRecalculation()); assertFalse(wb4.getSheetAt(2).getForceFormulaRecalculation());
assertFalse(wb3.getSheetAt(2).getForceFormulaRecalculation()); assertTrue(wb4.getSheetAt(3).getForceFormulaRecalculation());
assertTrue(wb3.getSheetAt(3).getForceFormulaRecalculation()); wb4.close();
} }
@Test @Test
public void columnWidthA() { public void columnWidthA() throws IOException {
//check we can correctly read column widths from a reference workbook //check we can correctly read column widths from a reference workbook
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("colwidth.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("colwidth.xls");
//reference values //reference values
int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657}; int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657};
HSSFSheet sh = wb.getSheetAt(0); HSSFSheet sh = wb1.getSheetAt(0);
for (char i = 'A'; i <= 'S'; i++) { for (char i = 'A'; i <= 'S'; i++) {
int idx = i - 'A'; int idx = i - 'A';
int w = sh.getColumnWidth(idx); int w = sh.getColumnWidth(idx);
@ -790,7 +822,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
} }
//the second sheet doesn't have overridden column widths //the second sheet doesn't have overridden column widths
sh = wb.getSheetAt(1); sh = wb1.getSheetAt(1);
int def_width = sh.getDefaultColumnWidth(); int def_width = sh.getDefaultColumnWidth();
for (char i = 'A'; i <= 'S'; i++) { for (char i = 'A'; i <= 'S'; i++) {
int idx = i - 'A'; int idx = i - 'A';
@ -799,10 +831,11 @@ public final class TestHSSFSheet extends BaseTestSheet {
//getColumnWidth returns width measured in 1/256th units //getColumnWidth returns width measured in 1/256th units
assertEquals(def_width*256, w); assertEquals(def_width*256, w);
} }
wb1.close();
//test new workbook //test new workbook
wb = new HSSFWorkbook(); HSSFWorkbook wb2 = new HSSFWorkbook();
sh = wb.createSheet(); sh = wb2.createSheet();
sh.setDefaultColumnWidth(10); sh.setDefaultColumnWidth(10);
assertEquals(10, sh.getDefaultColumnWidth()); assertEquals(10, sh.getDefaultColumnWidth());
assertEquals(256*10, sh.getColumnWidth(0)); assertEquals(256*10, sh.getColumnWidth(0));
@ -815,9 +848,10 @@ public final class TestHSSFSheet extends BaseTestSheet {
} }
//serialize and read again //serialize and read again
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
wb2.close();
sh = wb.getSheetAt(0); sh = wb3.getSheetAt(0);
assertEquals(10, sh.getDefaultColumnWidth()); assertEquals(10, sh.getDefaultColumnWidth());
//columns A-C have default width //columns A-C have default width
assertEquals(256*10, sh.getColumnWidth(0)); assertEquals(256*10, sh.getColumnWidth(0));
@ -832,29 +866,33 @@ public final class TestHSSFSheet extends BaseTestSheet {
// check for 16-bit signed/unsigned error: // check for 16-bit signed/unsigned error:
sh.setColumnWidth(0, 40000); sh.setColumnWidth(0, 40000);
assertEquals(40000, sh.getColumnWidth(0)); assertEquals(40000, sh.getColumnWidth(0));
wb3.close();
} }
@Test @Test
public void defaultColumnWidth() { public void defaultColumnWidth() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook( "12843-1.xls" ); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook( "12843-1.xls" );
HSSFSheet sheet = wb.getSheetAt( 7 ); HSSFSheet sheet = wb1.getSheetAt( 7 );
// shall not be NPE // shall not be NPE
assertEquals(8, sheet.getDefaultColumnWidth()); assertEquals(8, sheet.getDefaultColumnWidth());
assertEquals(8*256, sheet.getColumnWidth(0)); assertEquals(8*256, sheet.getColumnWidth(0));
assertEquals(0xFF, sheet.getDefaultRowHeight()); assertEquals(0xFF, sheet.getDefaultRowHeight());
wb = HSSFTestDataSamples.openSampleWorkbook( "34775.xls" ); wb1.close();
HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook( "34775.xls" );
// second and third sheets miss DefaultColWidthRecord // second and third sheets miss DefaultColWidthRecord
for(int i = 1; i <= 2; i++){ for(int i = 1; i <= 2; i++){
int dw = wb.getSheetAt( i ).getDefaultColumnWidth(); int dw = wb2.getSheetAt( i ).getDefaultColumnWidth();
assertEquals(8, dw); assertEquals(8, dw);
int cw = wb.getSheetAt( i ).getColumnWidth(0); int cw = wb2.getSheetAt( i ).getColumnWidth(0);
assertEquals(8*256, cw); assertEquals(8*256, cw);
assertEquals(0xFF, sheet.getDefaultRowHeight()); assertEquals(0xFF, sheet.getDefaultRowHeight());
} }
wb2.close();
} }
/** /**
@ -863,22 +901,22 @@ public final class TestHSSFSheet extends BaseTestSheet {
* Now POI is too. * Now POI is too.
*/ */
@Test @Test
public void missingRowRecords_bug41187() { public void missingRowRecords_bug41187() throws IOException {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex41187-19267.xls"); HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex41187-19267.xls");
HSSFSheet sheet = wb.getSheetAt(0); HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0); HSSFRow row = sheet.getRow(0);
if(row == null) { assertNotNull("Identified bug 41187 a", row);
fail("Identified bug 41187 a");
} assertNotEquals("Identified bug 41187 b", (short)0, row.getHeight());
if (row.getHeight() == 0) {
fail("Identified bug 41187 b");
}
assertEquals("Hi Excel!", row.getCell(0).getRichStringCellValue().getString()); assertEquals("Hi Excel!", row.getCell(0).getRichStringCellValue().getString());
// check row height for 'default' flag // check row height for 'default' flag
assertEquals((short)0xFF, row.getHeight()); assertEquals((short)0xFF, row.getHeight());
HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFTestDataSamples.writeOutAndReadBack(wb).close();
wb.close();
} }
/** /**
@ -888,7 +926,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* See bug #45720. * See bug #45720.
*/ */
@Test @Test
public void cloneSheetWithDrawings() { public void cloneSheetWithDrawings() throws IOException {
HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("45720.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("45720.xls");
HSSFSheet sheet1 = wb1.getSheetAt(0); HSSFSheet sheet1 = wb1.getSheetAt(0);
@ -899,6 +937,8 @@ public final class TestHSSFSheet extends BaseTestSheet {
wb1.cloneSheet(0); wb1.cloneSheet(0);
HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
wb2.getWorkbook().findDrawingGroup(); wb2.getWorkbook().findDrawingGroup();
DrawingManager2 dm2 = wb2.getWorkbook().getDrawingManager(); DrawingManager2 dm2 = wb2.getWorkbook().getDrawingManager();
@ -915,6 +955,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(dg_id_1 + 1, dg_id_2); assertEquals(dg_id_1 + 1, dg_id_2);
//TODO: check shapeId in the cloned sheet //TODO: check shapeId in the cloned sheet
wb2.close();
} }
/** /**
@ -923,7 +964,7 @@ public final class TestHSSFSheet extends BaseTestSheet {
* 31 chars. * 31 chars.
*/ */
@Test @Test
public void longSheetNames() { public void longSheetNames() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
final String SAME_PREFIX = "A123456789B123456789C123456789"; // 30 chars final String SAME_PREFIX = "A123456789B123456789C123456789"; // 30 chars
@ -935,13 +976,14 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals("The workbook already contains a sheet of this name", e.getMessage()); assertEquals("The workbook already contains a sheet of this name", e.getMessage());
} }
wb.createSheet(SAME_PREFIX + "Exxxx"); // OK - differs in the 31st char wb.createSheet(SAME_PREFIX + "Exxxx"); // OK - differs in the 31st char
wb.close();
} }
/** /**
* Tests that we can read existing column styles * Tests that we can read existing column styles
*/ */
@Test @Test
public void readColumnStyles() { public void readColumnStyles() throws IOException {
HSSFWorkbook wbNone = HSSFTestDataSamples.openSampleWorkbook("ColumnStyleNone.xls"); HSSFWorkbook wbNone = HSSFTestDataSamples.openSampleWorkbook("ColumnStyleNone.xls");
HSSFWorkbook wbSimple = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dp.xls"); HSSFWorkbook wbSimple = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dp.xls");
HSSFWorkbook wbComplex = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dpColoured.xls"); HSSFWorkbook wbComplex = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dpColoured.xls");
@ -975,26 +1017,31 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(10, cs.getFont(wbComplex).getColor()); assertEquals(10, cs.getFont(wbComplex).getColor());
assertFalse(cs.getFont(wbComplex).getItalic()); assertFalse(cs.getFont(wbComplex).getItalic());
assertEquals(HSSFFont.BOLDWEIGHT_BOLD, cs.getFont(wbComplex).getBoldweight()); assertEquals(HSSFFont.BOLDWEIGHT_BOLD, cs.getFont(wbComplex).getBoldweight());
wbComplex.close();
wbSimple.close();
wbNone.close();
} }
/** /**
* Tests the arabic setting * Tests the arabic setting
*/ */
@Test @Test
public void arabic() { public void arabic() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet(); HSSFSheet s = wb.createSheet();
assertFalse(s.isRightToLeft()); assertFalse(s.isRightToLeft());
s.setRightToLeft(true); s.setRightToLeft(true);
assertTrue(s.isRightToLeft()); assertTrue(s.isRightToLeft());
wb.close();
} }
@Test @Test
public void autoFilter(){ public void autoFilter() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
HSSFSheet sh = wb.createSheet(); HSSFSheet sh = wb1.createSheet();
InternalWorkbook iwb = wb.getWorkbook(); InternalWorkbook iwb = wb1.getWorkbook();
InternalSheet ish = sh.getSheet(); InternalSheet ish = sh.getSheet();
assertNull( iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1) ); assertNull( iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1) );
@ -1029,8 +1076,9 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertNull( ish.findFirstRecordBySid(ObjRecord.sid) ); // ObjRecord will appear after serializetion assertNull( ish.findFirstRecordBySid(ObjRecord.sid) ); // ObjRecord will appear after serializetion
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
sh = wb.getSheetAt(0); wb1.close();
sh = wb2.getSheetAt(0);
ish = sh.getSheet(); ish = sh.getSheet();
ObjRecord objRecord = (ObjRecord)ish.findFirstRecordBySid(ObjRecord.sid); ObjRecord objRecord = (ObjRecord)ish.findFirstRecordBySid(ObjRecord.sid);
List<SubRecord> subRecords = objRecord.getSubRecords(); List<SubRecord> subRecords = objRecord.getSubRecords();
@ -1038,20 +1086,22 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertTrue(subRecords.get(0) instanceof CommonObjectDataSubRecord ); assertTrue(subRecords.get(0) instanceof CommonObjectDataSubRecord );
assertTrue(subRecords.get(1) instanceof FtCblsSubRecord ); // must be present, see Bug 51481 assertTrue(subRecords.get(1) instanceof FtCblsSubRecord ); // must be present, see Bug 51481
assertTrue(subRecords.get(2) instanceof LbsDataSubRecord ); assertTrue(subRecords.get(2) instanceof LbsDataSubRecord );
wb2.close();
} }
@Test @Test
public void getSetColumnHiddenShort() { public void getSetColumnHiddenShort() throws IOException {
Workbook workbook = new HSSFWorkbook(); Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1"); Sheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnHidden((short)2, true); sheet.setColumnHidden((short)2, true);
assertTrue(sheet.isColumnHidden((short)2)); assertTrue(sheet.isColumnHidden((short)2));
workbook.close();
} }
@Test @Test
public void columnWidthShort() { public void columnWidthShort() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb1 = new HSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb1.createSheet();
//default column width measured in characters //default column width measured in characters
sheet.setDefaultColumnWidth((short)10); sheet.setDefaultColumnWidth((short)10);
@ -1092,9 +1142,10 @@ public final class TestHSSFSheet extends BaseTestSheet {
} }
//serialize and read again //serialize and read again
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb.getSheetAt(0); sheet = wb2.getSheetAt(0);
assertEquals(20, sheet.getDefaultColumnWidth()); assertEquals(20, sheet.getDefaultColumnWidth());
//columns A-C have default width //columns A-C have default width
assertEquals(256*20, sheet.getColumnWidth((short)0)); assertEquals(256*20, sheet.getColumnWidth((short)0));
@ -1106,10 +1157,12 @@ public final class TestHSSFSheet extends BaseTestSheet {
assertEquals(w, sheet.getColumnWidth((short)i)); assertEquals(w, sheet.getColumnWidth((short)i));
} }
assertEquals(40000, sheet.getColumnWidth((short)10)); assertEquals(40000, sheet.getColumnWidth((short)10));
wb2.close();
} }
@Test @Test
public void showInPane() { public void showInPane() throws IOException {
Workbook wb = new HSSFWorkbook(); Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
sheet.showInPane(2, 3); sheet.showInPane(2, 3);
@ -1117,10 +1170,11 @@ public final class TestHSSFSheet extends BaseTestSheet {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Maximum row number is 65535"); thrown.expectMessage("Maximum row number is 65535");
sheet.showInPane(Integer.MAX_VALUE, 3); sheet.showInPane(Integer.MAX_VALUE, 3);
wb.close();
} }
@Test @Test
public void drawingRecords() { public void drawingRecords() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(); HSSFSheet sheet = wb.createSheet();
@ -1128,10 +1182,11 @@ public final class TestHSSFSheet extends BaseTestSheet {
sheet.dumpDrawingRecords(false); sheet.dumpDrawingRecords(false);
sheet.dumpDrawingRecords(true);*/ sheet.dumpDrawingRecords(true);*/
assertNull(sheet.getDrawingEscherAggregate()); assertNull(sheet.getDrawingEscherAggregate());
wb.close();
} }
@Test @Test
public void bug55723b() { public void bug55723b() throws IOException {
HSSFWorkbook wb = new HSSFWorkbook(); HSSFWorkbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -1145,5 +1200,6 @@ public final class TestHSSFSheet extends BaseTestSheet {
// stored with a special name // stored with a special name
NameRecord record = wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1); NameRecord record = wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1);
assertNotNull(record); assertNotNull(record);
wb.close();
} }
} }

View File

@ -24,7 +24,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
@ -45,7 +44,7 @@ public abstract class BaseTestCellComment {
} }
@Test @Test
public final void find() { public final void find() throws IOException {
Workbook book = _testDataProvider.createWorkbook(); Workbook book = _testDataProvider.createWorkbook();
Sheet sheet = book.createSheet(); Sheet sheet = book.createSheet();
assertNull(sheet.getCellComment(0, 0)); assertNull(sheet.getCellComment(0, 0));
@ -54,20 +53,21 @@ public abstract class BaseTestCellComment {
Cell cell = row.createCell(0); Cell cell = row.createCell(0);
assertNull(sheet.getCellComment(0, 0)); assertNull(sheet.getCellComment(0, 0));
assertNull(cell.getCellComment()); assertNull(cell.getCellComment());
book.close();
} }
@Test @Test
public final void create() { public final void create() throws IOException {
String cellText = "Hello, World"; String cellText = "Hello, World";
String commentText = "We can set comments in POI"; String commentText = "We can set comments in POI";
String commentAuthor = "Apache Software Foundation"; String commentAuthor = "Apache Software Foundation";
int cellRow = 3; int cellRow = 3;
int cellColumn = 1; int cellColumn = 1;
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb1.getCreationHelper();
Sheet sheet = wb.createSheet(); Sheet sheet = wb1.createSheet();
assertNull(sheet.getCellComment(cellRow, cellColumn)); assertNull(sheet.getCellComment(cellRow, cellColumn));
Cell cell = sheet.createRow(cellRow).createCell(cellColumn); Cell cell = sheet.createRow(cellRow).createCell(cellColumn);
@ -98,8 +98,10 @@ public abstract class BaseTestCellComment {
assertEquals(cellRow, comment.getRow()); assertEquals(cellRow, comment.getRow());
assertEquals(cellColumn, comment.getColumn()); assertEquals(cellColumn, comment.getColumn());
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
cell = sheet.getRow(cellRow).getCell(cellColumn); cell = sheet.getRow(cellRow).getCell(cellColumn);
comment = cell.getCellComment(); comment = cell.getCellComment();
@ -114,9 +116,10 @@ public abstract class BaseTestCellComment {
comment.setString(factory.createRichTextString("New Comment Text")); comment.setString(factory.createRichTextString("New Comment Text"));
comment.setVisible(false); comment.setVisible(false);
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2);
wb2.close();
sheet = wb.getSheetAt(0); sheet = wb3.getSheetAt(0);
cell = sheet.getRow(cellRow).getCell(cellColumn); cell = sheet.getRow(cellRow).getCell(cellColumn);
comment = cell.getCellComment(); comment = cell.getCellComment();
@ -126,13 +129,15 @@ public abstract class BaseTestCellComment {
assertEquals(cellRow, comment.getRow()); assertEquals(cellRow, comment.getRow());
assertEquals(cellColumn, comment.getColumn()); assertEquals(cellColumn, comment.getColumn());
assertFalse(comment.isVisible()); assertFalse(comment.isVisible());
wb3.close();
} }
/** /**
* test that we can read cell comments from an existing workbook. * test that we can read cell comments from an existing workbook.
*/ */
@Test @Test
public final void readComments() { public final void readComments() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); Workbook wb = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension());
@ -163,18 +168,20 @@ public abstract class BaseTestCellComment {
assertEquals(rownum, comment.getRow()); assertEquals(rownum, comment.getRow());
assertEquals(cell.getColumnIndex(), comment.getColumn()); assertEquals(cell.getColumnIndex(), comment.getColumn());
} }
wb.close();
} }
/** /**
* test that we can modify existing cell comments * test that we can modify existing cell comments
*/ */
@Test @Test
public final void modifyComments() { public final void modifyComments() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); Workbook wb1 = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension());
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb1.getCreationHelper();
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb1.getSheetAt(0);
Cell cell; Cell cell;
Row row; Row row;
@ -188,8 +195,9 @@ public abstract class BaseTestCellComment {
comment.setString(factory.createRichTextString("Modified comment at row " + rownum)); comment.setString(factory.createRichTextString("Modified comment at row " + rownum));
} }
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
for (int rownum = 0; rownum < 3; rownum++) { for (int rownum = 0; rownum < 3; rownum++) {
row = sheet.getRow(rownum); row = sheet.getRow(rownum);
@ -199,12 +207,14 @@ public abstract class BaseTestCellComment {
assertEquals("Mofified[" + rownum + "] by Yegor", comment.getAuthor()); assertEquals("Mofified[" + rownum + "] by Yegor", comment.getAuthor());
assertEquals("Modified comment at row " + rownum, comment.getString().getString()); assertEquals("Modified comment at row " + rownum, comment.getString().getString());
} }
wb2.close();
} }
@Test @Test
public final void deleteComments() { public final void deleteComments() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); Workbook wb1 = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension());
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb1.getSheetAt(0);
// Zap from rows 1 and 3 // Zap from rows 1 and 3
assertNotNull(sheet.getRow(0).getCell(1).getCellComment()); assertNotNull(sheet.getRow(0).getCell(1).getCellComment());
@ -220,24 +230,27 @@ public abstract class BaseTestCellComment {
assertNull(sheet.getRow(2).getCell(1).getCellComment()); assertNull(sheet.getRow(2).getCell(1).getCellComment());
// Save and re-load // Save and re-load
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
// Check // Check
assertNull(sheet.getRow(0).getCell(1).getCellComment()); assertNull(sheet.getRow(0).getCell(1).getCellComment());
assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); assertNotNull(sheet.getRow(1).getCell(1).getCellComment());
assertNull(sheet.getRow(2).getCell(1).getCellComment()); assertNull(sheet.getRow(2).getCell(1).getCellComment());
wb2.close();
} }
/** /**
* code from the quick guide * code from the quick guide
*/ */
@Test @Test
public void quickGuide(){ public void quickGuide() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb1.getCreationHelper();
Sheet sheet = wb.createSheet(); Sheet sheet = wb1.createSheet();
Cell cell = sheet.createRow(3).createCell(5); Cell cell = sheet.createRow(3).createCell(5);
cell.setCellValue("F4"); cell.setCellValue("F4");
@ -252,8 +265,9 @@ public abstract class BaseTestCellComment {
//assign the comment to the cell //assign the comment to the cell
cell.setCellComment(comment); cell.setCellComment(comment);
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
cell = sheet.getRow(3).getCell(5); cell = sheet.getRow(3).getCell(5);
comment = cell.getCellComment(); comment = cell.getCellComment();
assertNotNull(comment); assertNotNull(comment);
@ -261,6 +275,8 @@ public abstract class BaseTestCellComment {
assertEquals("Apache POI", comment.getAuthor()); assertEquals("Apache POI", comment.getAuthor());
assertEquals(3, comment.getRow()); assertEquals(3, comment.getRow());
assertEquals(5, comment.getColumn()); assertEquals(5, comment.getColumn());
wb2.close();
} }
@Test @Test
@ -334,5 +350,7 @@ public abstract class BaseTestCellComment {
assertEquals( 3, anchor.getRow2()); assertEquals( 3, anchor.getRow2());
assertEquals(16*EMU_PER_PIXEL, anchor.getDy2()); assertEquals(16*EMU_PER_PIXEL, anchor.getDy2());
} }
wb.close();
} }
} }

View File

@ -19,7 +19,14 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import junit.framework.TestCase; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFConditionalFormatting; import org.apache.poi.hssf.usermodel.HSSFConditionalFormatting;
import org.apache.poi.hssf.usermodel.HSSFConditionalFormattingRule; import org.apache.poi.hssf.usermodel.HSSFConditionalFormattingRule;
@ -27,11 +34,12 @@ import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType;
import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.junit.Test;
/** /**
* Base tests for Conditional Formatting, for both HSSF and XSSF * Base tests for Conditional Formatting, for both HSSF and XSSF
*/ */
public abstract class BaseTestConditionalFormatting extends TestCase { public abstract class BaseTestConditionalFormatting {
private final ITestDataProvider _testDataProvider; private final ITestDataProvider _testDataProvider;
public BaseTestConditionalFormatting(ITestDataProvider testDataProvider){ public BaseTestConditionalFormatting(ITestDataProvider testDataProvider){
@ -40,7 +48,8 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
protected abstract void assertColour(String hexExpected, Color actual); protected abstract void assertColour(String hexExpected, Color actual);
public void testBasic() { @Test
public void testBasic() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting();
@ -96,13 +105,15 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("Number of rules must not exceed 3")); assertTrue(e.getMessage().startsWith("Number of rules must not exceed 3"));
} }
wb.close();
} }
/** /**
* Test format conditions based on a boolean formula * Test format conditions based on a boolean formula
*/ */
@Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testBooleanFormulaConditions() { public void testBooleanFormulaConditions() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting();
@ -135,10 +146,12 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
CellRangeAddress[] ranges2 = sheetCF.getConditionalFormattingAt(formatIndex2).getFormattingRanges(); CellRangeAddress[] ranges2 = sheetCF.getConditionalFormattingAt(formatIndex2).getFormattingRanges();
assertEquals(1, ranges2.length); assertEquals(1, ranges2.length);
assertEquals("B1:B3", ranges2[0].formatAsString()); assertEquals("B1:B3", ranges2[0].formatAsString());
wb.close();
} }
@Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testSingleFormulaConditions() { public void testSingleFormulaConditions() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh = wb.createSheet(); Sheet sh = wb.createSheet();
SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting();
@ -207,10 +220,13 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals("0", rule9.getFormula1()); assertEquals("0", rule9.getFormula1());
assertEquals("5", rule9.getFormula2()); assertEquals("5", rule9.getFormula2());
assertEquals(ComparisonOperator.NOT_BETWEEN, rule9.getComparisonOperation()); assertEquals(ComparisonOperator.NOT_BETWEEN, rule9.getComparisonOperation());
wb.close();
} }
@Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testCopy() { public void testCopy() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet1 = wb.createSheet(); Sheet sheet1 = wb.createSheet();
Sheet sheet2 = wb.createSheet(); Sheet sheet2 = wb.createSheet();
@ -246,9 +262,12 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals("15", sheet2cf.getRule(1).getFormula1()); assertEquals("15", sheet2cf.getRule(1).getFormula1());
assertEquals(ComparisonOperator.NOT_EQUAL, sheet2cf.getRule(1).getComparisonOperation()); assertEquals(ComparisonOperator.NOT_EQUAL, sheet2cf.getRule(1).getComparisonOperation());
assertEquals(ConditionalFormattingRule.CONDITION_TYPE_CELL_VALUE_IS, sheet2cf.getRule(1).getConditionType()); assertEquals(ConditionalFormattingRule.CONDITION_TYPE_CELL_VALUE_IS, sheet2cf.getRule(1).getConditionType());
wb.close();
} }
public void testRemove() { @Test
public void testRemove() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet1 = wb.createSheet(); Sheet sheet1 = wb.createSheet();
SheetConditionalFormatting sheetCF = sheet1.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sheet1.getSheetConditionalFormatting();
@ -287,9 +306,12 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range"));
} }
wb.close();
} }
public void testCreateCF() { @Test
public void testCreateCF() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
String formula = "7"; String formula = "7";
@ -366,9 +388,12 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
rule2 = cf.getRule(1); rule2 = cf.getRule(1);
assertEquals("2",rule2.getFormula2()); assertEquals("2",rule2.getFormula2());
assertEquals("1",rule2.getFormula1()); assertEquals("1",rule2.getFormula1());
workbook.close();
} }
public void testClone() { @Test
public void testClone() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -399,16 +424,19 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
try { try {
wb.cloneSheet(0); wb.cloneSheet(0);
assertEquals(2, wb.getNumberOfSheets());
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (e.getMessage().indexOf("needs to define a clone method") > 0) { if (e.getMessage().indexOf("needs to define a clone method") > 0) {
fail("Indentified bug 45682"); fail("Indentified bug 45682");
} }
throw e; throw e;
} finally {
wb.close();
} }
assertEquals(2, wb.getNumberOfSheets());
} }
public void testShiftRows() { @Test
public void testShiftRows() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -457,9 +485,11 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
cf2 = sheetCF.getConditionalFormattingAt(1); cf2 = sheetCF.getConditionalFormattingAt(1);
assertEquals("SUM(A10:A21)", cf2.getRule(0).getFormula1()); assertEquals("SUM(A10:A21)", cf2.getRule(0).getFormula1());
assertEquals("1+SUM(#REF!)", cf2.getRule(0).getFormula2()); assertEquals("1+SUM(#REF!)", cf2.getRule(0).getFormula2());
wb.close();
} }
protected void testRead(String filename){ protected void testRead(String filename) throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook(filename); Workbook wb = _testDataProvider.openSampleWorkbook(filename);
Sheet sh = wb.getSheet("CF"); Sheet sh = wb.getSheet("CF");
SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting();
@ -542,9 +572,11 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(ComparisonOperator.BETWEEN, rule5.getComparisonOperation()); assertEquals(ComparisonOperator.BETWEEN, rule5.getComparisonOperation());
assertEquals("\"A\"", rule5.getFormula1()); assertEquals("\"A\"", rule5.getFormula1());
assertEquals("\"AAA\"", rule5.getFormula2()); assertEquals("\"AAA\"", rule5.getFormula2());
wb.close();
} }
public void testReadOffice2007(String filename) { public void testReadOffice2007(String filename) throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook(filename); Workbook wb = _testDataProvider.openSampleWorkbook(filename);
Sheet s = wb.getSheet("CF"); Sheet s = wb.getSheet("CF");
ConditionalFormatting cf = null; ConditionalFormatting cf = null;
@ -768,6 +800,8 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
// Mixed icons - Column U // Mixed icons - Column U
// TODO Support EXT formattings // TODO Support EXT formattings
wb.close();
} }
private void assertDataBar(ConditionalFormatting cf, String color) { private void assertDataBar(ConditionalFormatting cf, String color) {
@ -869,7 +903,8 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
} }
} }
public void testCreateFontFormatting() { @Test
public void testCreateFontFormatting() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
@ -934,9 +969,11 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(FontFormatting.U_DOUBLE, r1fp.getUnderlineType()); assertEquals(FontFormatting.U_DOUBLE, r1fp.getUnderlineType());
assertEquals(IndexedColors.BLUE.index, r1fp.getFontColorIndex()); assertEquals(IndexedColors.BLUE.index, r1fp.getFontColorIndex());
workbook.close();
} }
public void testCreatePatternFormatting() { @Test
public void testCreatePatternFormatting() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
@ -979,9 +1016,12 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(IndexedColors.RED.index, r1fp.getFillBackgroundColor()); assertEquals(IndexedColors.RED.index, r1fp.getFillBackgroundColor());
assertEquals(IndexedColors.BLUE.index, r1fp.getFillForegroundColor()); assertEquals(IndexedColors.BLUE.index, r1fp.getFillForegroundColor());
assertEquals(PatternFormatting.BRICKS, r1fp.getFillPattern()); assertEquals(PatternFormatting.BRICKS, r1fp.getFillPattern());
workbook.close();
} }
public void testCreateBorderFormatting() { @Test
public void testCreateBorderFormatting() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
@ -1040,11 +1080,14 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(BorderFormatting.BORDER_THICK, r1fp.getBorderTop()); assertEquals(BorderFormatting.BORDER_THICK, r1fp.getBorderTop());
assertEquals(BorderFormatting.BORDER_THIN, r1fp.getBorderLeft()); assertEquals(BorderFormatting.BORDER_THIN, r1fp.getBorderLeft());
assertEquals(BorderFormatting.BORDER_HAIR, r1fp.getBorderRight()); assertEquals(BorderFormatting.BORDER_HAIR, r1fp.getBorderRight());
workbook.close();
} }
public void testCreateIconFormatting() { @Test
Workbook workbook = _testDataProvider.createWorkbook(); public void testCreateIconFormatting() throws IOException {
Sheet sheet = workbook.createSheet(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = wb1.createSheet();
SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
ConditionalFormattingRule rule1 = ConditionalFormattingRule rule1 =
@ -1068,7 +1111,9 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
sheetCF.addConditionalFormatting(regions, rule1); sheetCF.addConditionalFormatting(regions, rule1);
// Save, re-load and re-check // Save, re-load and re-check
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
sheetCF = sheet.getSheetConditionalFormatting(); sheetCF = sheet.getSheetConditionalFormatting();
assertEquals(1, sheetCF.getNumConditionalFormattings()); assertEquals(1, sheetCF.getNumConditionalFormattings());
@ -1088,14 +1133,17 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(RangeType.PERCENT,iconFmt.getThresholds()[2].getRangeType()); assertEquals(RangeType.PERCENT,iconFmt.getThresholds()[2].getRangeType());
assertEquals(RangeType.MAX, iconFmt.getThresholds()[3].getRangeType()); assertEquals(RangeType.MAX, iconFmt.getThresholds()[3].getRangeType());
assertEquals(null, iconFmt.getThresholds()[0].getValue()); assertEquals(null, iconFmt.getThresholds()[0].getValue());
assertEquals(10d, iconFmt.getThresholds()[1].getValue()); assertEquals(10d, iconFmt.getThresholds()[1].getValue(), 0);
assertEquals(75d, iconFmt.getThresholds()[2].getValue()); assertEquals(75d, iconFmt.getThresholds()[2].getValue(), 0);
assertEquals(null, iconFmt.getThresholds()[3].getValue()); assertEquals(null, iconFmt.getThresholds()[3].getValue());
wb2.close();
} }
public void testCreateColorScaleFormatting() { @Test
Workbook workbook = _testDataProvider.createWorkbook(); public void testCreateColorScaleFormatting() throws IOException {
Sheet sheet = workbook.createSheet(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = wb1.createSheet();
SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
ConditionalFormattingRule rule1 = ConditionalFormattingRule rule1 =
@ -1115,7 +1163,9 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
sheetCF.addConditionalFormatting(regions, rule1); sheetCF.addConditionalFormatting(regions, rule1);
// Save, re-load and re-check // Save, re-load and re-check
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
sheetCF = sheet.getSheetConditionalFormatting(); sheetCF = sheet.getSheetConditionalFormatting();
assertEquals(1, sheetCF.getNumConditionalFormattings()); assertEquals(1, sheetCF.getNumConditionalFormattings());
@ -1133,16 +1183,19 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(RangeType.NUMBER, clrFmt.getThresholds()[1].getRangeType()); assertEquals(RangeType.NUMBER, clrFmt.getThresholds()[1].getRangeType());
assertEquals(RangeType.MAX, clrFmt.getThresholds()[2].getRangeType()); assertEquals(RangeType.MAX, clrFmt.getThresholds()[2].getRangeType());
assertEquals(null, clrFmt.getThresholds()[0].getValue()); assertEquals(null, clrFmt.getThresholds()[0].getValue());
assertEquals(10d, clrFmt.getThresholds()[1].getValue()); assertEquals(10d, clrFmt.getThresholds()[1].getValue(), 0);
assertEquals(null, clrFmt.getThresholds()[2].getValue()); assertEquals(null, clrFmt.getThresholds()[2].getValue());
wb2.close();
} }
public void testCreateDataBarFormatting() { @Test
Workbook workbook = _testDataProvider.createWorkbook(); public void testCreateDataBarFormatting() throws IOException {
Sheet sheet = workbook.createSheet(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = wb1.createSheet();
String colorHex = "FFFFEB84"; String colorHex = "FFFFEB84";
ExtendedColor color = workbook.getCreationHelper().createExtendedColor(); ExtendedColor color = wb1.getCreationHelper().createExtendedColor();
color.setARGBHex(colorHex); color.setARGBHex(colorHex);
SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
ConditionalFormattingRule rule1 = ConditionalFormattingRule rule1 =
@ -1162,7 +1215,9 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
sheetCF.addConditionalFormatting(regions, rule1); sheetCF.addConditionalFormatting(regions, rule1);
// Save, re-load and re-check // Save, re-load and re-check
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
sheetCF = sheet.getSheetConditionalFormatting(); sheetCF = sheet.getSheetConditionalFormatting();
assertEquals(1, sheetCF.getNumConditionalFormattings()); assertEquals(1, sheetCF.getNumConditionalFormattings());
@ -1182,9 +1237,12 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
assertEquals(RangeType.MAX, dbFmt.getMaxThreshold().getRangeType()); assertEquals(RangeType.MAX, dbFmt.getMaxThreshold().getRangeType());
assertEquals(null, dbFmt.getMinThreshold().getValue()); assertEquals(null, dbFmt.getMinThreshold().getValue());
assertEquals(null, dbFmt.getMaxThreshold().getValue()); assertEquals(null, dbFmt.getMaxThreshold().getValue());
wb2.close();
} }
public void testBug55380() { @Test
public void testBug55380() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
CellRangeAddress[] ranges = new CellRangeAddress[] { CellRangeAddress[] ranges = new CellRangeAddress[] {
@ -1192,5 +1250,6 @@ public abstract class BaseTestConditionalFormatting extends TestCase {
}; };
ConditionalFormattingRule rule = sheet.getSheetConditionalFormatting().createConditionalFormattingRule("$A$1>0"); ConditionalFormattingRule rule = sheet.getSheetConditionalFormatting().createConditionalFormattingRule("$A$1>0");
sheet.getSheetConditionalFormatting().addConditionalFormatting(ranges, rule); sheet.getSheetConditionalFormatting().addConditionalFormatting(ranges, rule);
wb.close();
} }
} }

View File

@ -17,17 +17,21 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import junit.framework.AssertionFailedError; import static org.junit.Assert.assertEquals;
import junit.framework.TestCase; import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.junit.Test;
/** /**
* Common superclass for testing implementatiosn of{@link FormulaEvaluator} * Common superclass for testing implementatiosn of{@link FormulaEvaluator}
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public abstract class BaseTestFormulaEvaluator extends TestCase { public abstract class BaseTestFormulaEvaluator {
protected final ITestDataProvider _testDataProvider; protected final ITestDataProvider _testDataProvider;
@ -38,7 +42,8 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
_testDataProvider = testDataProvider; _testDataProvider = testDataProvider;
} }
public void testSimpleArithmetic() { @Test
public void testSimpleArithmetic() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet s = wb.createSheet(); Sheet s = wb.createSheet();
Row r = s.createRow(0); Row r = s.createRow(0);
@ -58,9 +63,12 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
assertEquals(6.0, c1.getNumericCellValue(), 0.0001); assertEquals(6.0, c1.getNumericCellValue(), 0.0001);
assertEquals(5.0, c2.getNumericCellValue(), 0.0001); assertEquals(5.0, c2.getNumericCellValue(), 0.0001);
wb.close();
} }
public void testSumCount() { @Test
public void testSumCount() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet s = wb.createSheet(); Sheet s = wb.createSheet();
Row r = s.createRow(0); Row r = s.createRow(0);
@ -100,9 +108,11 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
assertEquals(17.5, c2.getNumericCellValue(), 0.0001); assertEquals(17.5, c2.getNumericCellValue(), 0.0001);
assertEquals(1, c3.getNumericCellValue(), 0.0001); assertEquals(1, c3.getNumericCellValue(), 0.0001);
assertEquals(4, c4.getNumericCellValue(), 0.0001); assertEquals(4, c4.getNumericCellValue(), 0.0001);
wb.close();
} }
public void baseTestSharedFormulas(String sampleFile){ public void baseTestSharedFormulas(String sampleFile) throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile); Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile);
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb.getSheetAt(0);
@ -125,12 +135,15 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
cell = sheet.getRow(4).getCell(0); cell = sheet.getRow(4).getCell(0);
assertEquals("B5", cell.getCellFormula()); assertEquals("B5", cell.getCellFormula());
assertEquals("UniqueDocumentNumberID", evaluator.evaluate(cell).getStringValue()); assertEquals("UniqueDocumentNumberID", evaluator.evaluate(cell).getStringValue());
wb.close();
} }
/** /**
* Test creation / evaluation of formulas with sheet-level names * Test creation / evaluation of formulas with sheet-level names
*/ */
public void testSheetLevelFormulas(){ @Test
public void testSheetLevelFormulas() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Row row; Row row;
@ -161,9 +174,12 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0); assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0);
assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0); assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0);
wb.close();
} }
public void testFullColumnRefs() { @Test
public void testFullColumnRefs() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet("Sheet1"); Sheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -192,9 +208,12 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
assertEquals(26.0, fe.evaluate(cell0).getNumberValue(), 0.0); assertEquals(26.0, fe.evaluate(cell0).getNumberValue(), 0.0);
assertEquals(56.0, fe.evaluate(cell1).getNumberValue(), 0.0); assertEquals(56.0, fe.evaluate(cell1).getNumberValue(), 0.0);
wb.close();
} }
public void testRepeatedEvaluation() { @Test
public void testRepeatedEvaluation() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.createSheet("Sheet1"); Sheet sheet = wb.createSheet("Sheet1");
@ -230,6 +249,8 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
fe.clearAllCachedResultValues(); fe.clearAllCachedResultValues();
cellValue = fe.evaluate(c); cellValue = fe.evaluate(c);
assertEquals(40455.0, cellValue.getNumberValue(), 0.0); assertEquals(40455.0, cellValue.getNumberValue(), 0.0);
wb.close();
} }
private static void setValue(Sheet sheet, int rowIndex, int colIndex, double value) { private static void setValue(Sheet sheet, int rowIndex, int colIndex, double value) {
@ -244,19 +265,22 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
* {@link FormulaEvaluator#evaluate(org.apache.poi.ss.usermodel.Cell)} should behave the same whether the cell * {@link FormulaEvaluator#evaluate(org.apache.poi.ss.usermodel.Cell)} should behave the same whether the cell
* is <code>null</code> or blank. * is <code>null</code> or blank.
*/ */
public void testEvaluateBlank() { @Test
public void testEvaluateBlank() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
assertNull(fe.evaluate(null)); assertNull(fe.evaluate(null));
Sheet sheet = wb.createSheet("Sheet1"); Sheet sheet = wb.createSheet("Sheet1");
Cell cell = sheet.createRow(0).createCell(0); Cell cell = sheet.createRow(0).createCell(0);
assertNull(fe.evaluate(cell)); assertNull(fe.evaluate(cell));
wb.close();
} }
/** /**
* Test for bug due to attempt to convert a cached formula error result to a boolean * Test for bug due to attempt to convert a cached formula error result to a boolean
*/ */
public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() { @Test
public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet("Sheet1"); Sheet sheet = wb.createSheet("Sheet1");
@ -275,14 +299,16 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
fe.evaluateInCell(cellB1); fe.evaluateInCell(cellB1);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
if (e.getMessage().equals("Cannot get a numeric value from a error formula cell")) { if (e.getMessage().equals("Cannot get a numeric value from a error formula cell")) {
throw new AssertionFailedError("Identified bug 46479a"); fail("Identified bug 46479a");
} }
} }
assertEquals(3.5, cellB1.getNumericCellValue(), 0.0); assertEquals(3.5, cellB1.getNumericCellValue(), 0.0);
wb.close();
} }
@Test
public void testRounding_bug51339() { public void testRounding_bug51339() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet("Sheet1"); Sheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -299,5 +325,7 @@ public abstract class BaseTestFormulaEvaluator extends TestCase {
assertEquals(2162.62, fe.evaluateInCell(cellB1).getNumericCellValue(), 0.0); assertEquals(2162.62, fe.evaluateInCell(cellB1).getNumericCellValue(), 0.0);
assertEquals(2162.62, fe.evaluateInCell(cellC1).getNumericCellValue(), 0.0); assertEquals(2162.62, fe.evaluateInCell(cellC1).getNumericCellValue(), 0.0);
assertEquals(2162.61, fe.evaluateInCell(cellD1).getNumericCellValue(), 0.0); assertEquals(2162.61, fe.evaluateInCell(cellD1).getNumericCellValue(), 0.0);
wb.close();
} }
} }

View File

@ -49,7 +49,7 @@ public abstract class BaseTestSheet {
} }
@Test @Test
public void createRow() { public void createRow() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
assertEquals(0, sheet.getPhysicalNumberOfRows()); assertEquals(0, sheet.getPhysicalNumberOfRows());
@ -86,36 +86,38 @@ public abstract class BaseTestSheet {
Row row2_ovrewritten_ref = it2.next(); Row row2_ovrewritten_ref = it2.next();
assertSame(row2_ovrewritten, row2_ovrewritten_ref); assertSame(row2_ovrewritten, row2_ovrewritten_ref);
assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0); assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0);
workbook.close();
} }
@Test @Test(expected=IllegalArgumentException.class)
public void createRowBeforeFirstRow() { public void createRowBeforeFirstRow() throws IOException {
final Workbook workbook = _testDataProvider.createWorkbook(); final Workbook workbook = _testDataProvider.createWorkbook();
final Sheet sh = workbook.createSheet(); final Sheet sh = workbook.createSheet();
sh.createRow(0); sh.createRow(0);
try { try {
// Negative rows not allowed
sh.createRow(-1); sh.createRow(-1);
fail("Negative rows not allowed"); } finally {
} catch (final IllegalArgumentException e) { workbook.close();
// expected
} }
} }
protected void createRowAfterLastRow(SpreadsheetVersion version) { protected void createRowAfterLastRow(SpreadsheetVersion version) throws IOException {
final Workbook workbook = _testDataProvider.createWorkbook(); final Workbook workbook = _testDataProvider.createWorkbook();
final Sheet sh = workbook.createSheet(); final Sheet sh = workbook.createSheet();
sh.createRow(version.getLastRowIndex()); sh.createRow(version.getLastRowIndex());
try { try {
// Row number must be between 0 and last row
sh.createRow(version.getLastRowIndex() + 1); sh.createRow(version.getLastRowIndex() + 1);
fail("Row number must be between 0 and " + version.getLastColumnIndex()); } finally {
} catch (final IllegalArgumentException e) { workbook.close();
// expected
} }
} }
@Test @Test
public void removeRow() { public void removeRow() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet1 = workbook.createSheet(); Sheet sheet1 = workbook.createSheet();
assertEquals(0, sheet1.getPhysicalNumberOfRows()); assertEquals(0, sheet1.getPhysicalNumberOfRows());
@ -152,10 +154,12 @@ public abstract class BaseTestSheet {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Specified row does not belong to this sheet"); thrown.expectMessage("Specified row does not belong to this sheet");
sheet2.removeRow(row3); sheet2.removeRow(row3);
workbook.close();
} }
@Test @Test
public void cloneSheet() { public void cloneSheet() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
CreationHelper factory = workbook.getCreationHelper(); CreationHelper factory = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Test Clone"); Sheet sheet = workbook.createSheet("Test Clone");
@ -182,13 +186,15 @@ public abstract class BaseTestSheet {
} }
assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)"); assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)");
workbook.close();
} }
/** tests that the sheet name for multiple clones of the same sheet is unique /** tests that the sheet name for multiple clones of the same sheet is unique
* BUG 37416 * BUG 37416
*/ */
@Test @Test
public void cloneSheetMultipleTimes() { public void cloneSheetMultipleTimes() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
CreationHelper factory = workbook.getCreationHelper(); CreationHelper factory = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Test Clone"); Sheet sheet = workbook.createSheet("Test Clone");
@ -210,16 +216,18 @@ public abstract class BaseTestSheet {
workbook.createSheet("abc ( 123)"); workbook.createSheet("abc ( 123)");
workbook.cloneSheet(0); workbook.cloneSheet(0);
assertEquals("abc (124)", workbook.getSheetName(1)); assertEquals("abc (124)", workbook.getSheetName(1));
workbook.close();
} }
/** /**
* Setting landscape and portrait stuff on new sheets * Setting landscape and portrait stuff on new sheets
*/ */
@Test @Test
public void printSetupLandscapeNew() { public void printSetupLandscapeNew() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheetL = workbook.createSheet("LandscapeS"); Sheet sheetL = wb1.createSheet("LandscapeS");
Sheet sheetP = workbook.createSheet("LandscapeP"); Sheet sheetP = wb1.createSheet("LandscapeP");
// Check two aspects of the print setup // Check two aspects of the print setup
assertFalse(sheetL.getPrintSetup().getLandscape()); assertFalse(sheetL.getPrintSetup().getLandscape());
@ -238,14 +246,16 @@ public abstract class BaseTestSheet {
assertEquals(3, sheetP.getPrintSetup().getCopies()); assertEquals(3, sheetP.getPrintSetup().getCopies());
// Save and re-load, and check still there // Save and re-load, and check still there
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheetL = workbook.getSheet("LandscapeS"); wb1.close();
sheetP = workbook.getSheet("LandscapeP"); sheetL = wb2.getSheet("LandscapeS");
sheetP = wb2.getSheet("LandscapeP");
assertTrue(sheetL.getPrintSetup().getLandscape()); assertTrue(sheetL.getPrintSetup().getLandscape());
assertFalse(sheetP.getPrintSetup().getLandscape()); assertFalse(sheetP.getPrintSetup().getLandscape());
assertEquals(1, sheetL.getPrintSetup().getCopies()); assertEquals(1, sheetL.getPrintSetup().getCopies());
assertEquals(3, sheetP.getPrintSetup().getCopies()); assertEquals(3, sheetP.getPrintSetup().getCopies());
wb2.close();
} }
/** /**
@ -254,7 +264,7 @@ public abstract class BaseTestSheet {
* *
*/ */
@Test @Test
public void addMerged() { public void addMerged() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
assertEquals(0, sheet.getNumMergedRegions()); assertEquals(0, sheet.getNumMergedRegions());
@ -286,6 +296,8 @@ public abstract class BaseTestSheet {
assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), e.getMessage()); assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), e.getMessage());
} }
assertEquals(1, sheet.getNumMergedRegions()); assertEquals(1, sheet.getNumMergedRegions());
wb.close();
} }
/** /**
@ -293,7 +305,7 @@ public abstract class BaseTestSheet {
* *
*/ */
@Test @Test
public void removeMerged() { public void removeMerged() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
@ -325,10 +337,12 @@ public abstract class BaseTestSheet {
assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions()); assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions());
region = sheet.getMergedRegion(0); region = sheet.getMergedRegion(0);
assertEquals("the merged row to doesnt match the one we put in ", 4, region.getLastRow()); assertEquals("the merged row to doesnt match the one we put in ", 4, region.getLastRow());
wb.close();
} }
@Test @Test
public void shiftMerged() { public void shiftMerged() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb.getCreationHelper();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -347,16 +361,17 @@ public abstract class BaseTestSheet {
region = sheet.getMergedRegion(0); region = sheet.getMergedRegion(0);
assertEquals("Merged region not moved over to row 2", 2, region.getFirstRow()); assertEquals("Merged region not moved over to row 2", 2, region.getFirstRow());
wb.close();
} }
/** /**
* Tests the display of gridlines, formulas, and rowcolheadings. * Tests the display of gridlines, formulas, and rowcolheadings.
* @author Shawn Laubach (slaubach at apache dot org)
*/ */
@Test @Test
public void displayOptions() { public void displayOptions() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb1.createSheet();
assertEquals(sheet.isDisplayGridlines(), true); assertEquals(sheet.isDisplayGridlines(), true);
assertEquals(sheet.isDisplayRowColHeadings(), true); assertEquals(sheet.isDisplayRowColHeadings(), true);
@ -368,19 +383,22 @@ public abstract class BaseTestSheet {
sheet.setDisplayFormulas(true); sheet.setDisplayFormulas(true);
sheet.setDisplayZeros(false); sheet.setDisplayZeros(false);
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
assertEquals(sheet.isDisplayGridlines(), false); assertEquals(sheet.isDisplayGridlines(), false);
assertEquals(sheet.isDisplayRowColHeadings(), false); assertEquals(sheet.isDisplayRowColHeadings(), false);
assertEquals(sheet.isDisplayFormulas(), true); assertEquals(sheet.isDisplayFormulas(), true);
assertEquals(sheet.isDisplayZeros(), false); assertEquals(sheet.isDisplayZeros(), false);
wb2.close();
} }
@Test @Test
public void columnWidth() { public void columnWidth() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb1.createSheet();
//default column width measured in characters //default column width measured in characters
sheet.setDefaultColumnWidth(10); sheet.setDefaultColumnWidth(10);
@ -421,9 +439,10 @@ public abstract class BaseTestSheet {
} }
//serialize and read again //serialize and read again
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb.getSheetAt(0); sheet = wb2.getSheetAt(0);
assertEquals(20, sheet.getDefaultColumnWidth()); assertEquals(20, sheet.getDefaultColumnWidth());
//columns A-C have default width //columns A-C have default width
assertEquals(256*20, sheet.getColumnWidth(0)); assertEquals(256*20, sheet.getColumnWidth(0));
@ -435,11 +454,13 @@ public abstract class BaseTestSheet {
assertEquals(w, sheet.getColumnWidth(i)); assertEquals(w, sheet.getColumnWidth(i));
} }
assertEquals(40000, sheet.getColumnWidth(10)); assertEquals(40000, sheet.getColumnWidth(10));
wb2.close();
} }
@Test @Test
public void defaultRowHeight() { public void defaultRowHeight() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
sheet.setDefaultRowHeightInPoints(15); sheet.setDefaultRowHeightInPoints(15);
@ -464,11 +485,13 @@ public abstract class BaseTestSheet {
sheet.setDefaultRowHeightInPoints(17.5f); sheet.setDefaultRowHeightInPoints(17.5f);
assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F); assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F);
assertEquals((short)(17.5f*20), sheet.getDefaultRowHeight()); assertEquals((short)(17.5f*20), sheet.getDefaultRowHeight());
workbook.close();
} }
/** cell with formula becomes null on cloning a sheet*/ /** cell with formula becomes null on cloning a sheet*/
@Test @Test
public void bug35084() { public void bug35084() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet s = wb.createSheet("Sheet1"); Sheet s = wb.createSheet("Sheet1");
Row r = s.createRow(0); Row r = s.createRow(0);
@ -479,11 +502,12 @@ public abstract class BaseTestSheet {
assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check
assertNotNull(r.getCell(1)); assertNotNull(r.getCell(1));
assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2"); assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2");
wb.close();
} }
/** test that new default column styles get applied */ /** test that new default column styles get applied */
@Test @Test
public void defaultColumnStyle() { public void defaultColumnStyle() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
CellStyle style = wb.createCellStyle(); CellStyle style = wb.createCellStyle();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -496,13 +520,14 @@ public abstract class BaseTestSheet {
CellStyle style2 = cell.getCellStyle(); CellStyle style2 = cell.getCellStyle();
assertNotNull(style2); assertNotNull(style2);
assertEquals("style should match", style.getIndex(), style2.getIndex()); assertEquals("style should match", style.getIndex(), style2.getIndex());
wb.close();
} }
@Test @Test
public void outlineProperties() { public void outlineProperties() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb1.createSheet();
//TODO defaults are different in HSSF and XSSF //TODO defaults are different in HSSF and XSSF
//assertTrue(sheet.getRowSumsBelow()); //assertTrue(sheet.getRowSumsBelow());
@ -520,17 +545,19 @@ public abstract class BaseTestSheet {
assertTrue(sheet.getRowSumsBelow()); assertTrue(sheet.getRowSumsBelow());
assertTrue(sheet.getRowSumsRight()); assertTrue(sheet.getRowSumsRight());
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
assertTrue(sheet.getRowSumsBelow()); assertTrue(sheet.getRowSumsBelow());
assertTrue(sheet.getRowSumsRight()); assertTrue(sheet.getRowSumsRight());
wb2.close();
} }
/** /**
* Test basic display properties * Test basic display properties
*/ */
@Test @Test
public void sheetProperties() { public void sheetProperties() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -580,9 +607,11 @@ public abstract class BaseTestSheet {
assertTrue(sheet.getFitToPage()); assertTrue(sheet.getFitToPage());
sheet.setFitToPage(false); sheet.setFitToPage(false);
assertFalse(sheet.getFitToPage()); assertFalse(sheet.getFitToPage());
wb.close();
} }
public void baseTestGetSetMargin(double[] defaultMargins) { public void baseTestGetSetMargin(double[] defaultMargins) throws IOException {
double marginLeft = defaultMargins[0]; double marginLeft = defaultMargins[0];
double marginRight = defaultMargins[1]; double marginRight = defaultMargins[1];
double marginTop = defaultMargins[2]; double marginTop = defaultMargins[2];
@ -615,10 +644,12 @@ public abstract class BaseTestSheet {
thrown.expect(IllegalArgumentException.class); thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Unknown margin constant: 65"); thrown.expectMessage("Unknown margin constant: 65");
sheet.setMargin((short) 65, 15); sheet.setMargin((short) 65, 15);
workbook.close();
} }
@Test @Test
public void rowBreaks() { public void rowBreaks() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
//Sheet#getRowBreaks() returns an empty array if no row breaks are defined //Sheet#getRowBreaks() returns an empty array if no row breaks are defined
@ -644,10 +675,12 @@ public abstract class BaseTestSheet {
assertFalse(sheet.isRowBroken(1)); assertFalse(sheet.isRowBroken(1));
assertFalse(sheet.isRowBroken(15)); assertFalse(sheet.isRowBroken(15));
workbook.close();
} }
@Test @Test
public void columnBreaks() { public void columnBreaks() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
assertNotNull(sheet.getColumnBreaks()); assertNotNull(sheet.getColumnBreaks());
@ -672,10 +705,11 @@ public abstract class BaseTestSheet {
assertFalse(sheet.isColumnBroken(11)); assertFalse(sheet.isColumnBroken(11));
assertFalse(sheet.isColumnBroken(12)); assertFalse(sheet.isColumnBroken(12));
workbook.close();
} }
@Test @Test
public void getFirstLastRowNum() { public void getFirstLastRowNum() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1"); Sheet sheet = workbook.createSheet("Sheet 1");
sheet.createRow(9); sheet.createRow(9);
@ -683,27 +717,30 @@ public abstract class BaseTestSheet {
sheet.createRow(1); sheet.createRow(1);
assertEquals(0, sheet.getFirstRowNum()); assertEquals(0, sheet.getFirstRowNum());
assertEquals(9, sheet.getLastRowNum()); assertEquals(9, sheet.getLastRowNum());
workbook.close();
} }
@Test @Test
public void getFooter() { public void getFooter() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1"); Sheet sheet = workbook.createSheet("Sheet 1");
assertNotNull(sheet.getFooter()); assertNotNull(sheet.getFooter());
sheet.getFooter().setCenter("test center footer"); sheet.getFooter().setCenter("test center footer");
assertEquals("test center footer", sheet.getFooter().getCenter()); assertEquals("test center footer", sheet.getFooter().getCenter());
workbook.close();
} }
@Test @Test
public void getSetColumnHidden() { public void getSetColumnHidden() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1"); Sheet sheet = workbook.createSheet("Sheet 1");
sheet.setColumnHidden(2, true); sheet.setColumnHidden(2, true);
assertTrue(sheet.isColumnHidden(2)); assertTrue(sheet.isColumnHidden(2));
workbook.close();
} }
@Test @Test
public void protectSheet() { public void protectSheet() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
assertFalse(sheet.getProtect()); assertFalse(sheet.getProtect());
@ -711,11 +748,11 @@ public abstract class BaseTestSheet {
assertTrue(sheet.getProtect()); assertTrue(sheet.getProtect());
sheet.protectSheet(null); sheet.protectSheet(null);
assertFalse(sheet.getProtect()); assertFalse(sheet.getProtect());
wb.close();
} }
@Test @Test
public void createFreezePane() { public void createFreezePane() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
// create a workbook // create a workbook
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -762,11 +799,13 @@ public abstract class BaseTestSheet {
sheet.createFreezePane(0, 0); sheet.createFreezePane(0, 0);
// If both colSplit and rowSplit are zero then the existing freeze pane is removed // If both colSplit and rowSplit are zero then the existing freeze pane is removed
assertNull(sheet.getPaneInformation()); assertNull(sheet.getPaneInformation());
wb.close();
} }
@Test @Test
public void getRepeatingRowsAndColumns() { public void getRepeatingRowsAndColumns() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook( Workbook wb = _testDataProvider.openSampleWorkbook(
"RepeatingRowsCols." "RepeatingRowsCols."
+ _testDataProvider.getStandardFileNameExtension()); + _testDataProvider.getStandardFileNameExtension());
@ -775,11 +814,12 @@ public abstract class BaseTestSheet {
checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null); checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null);
checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A"); checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A");
checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B"); checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B");
wb.close();
} }
@Test @Test
public void setRepeatingRowsAndColumnsBug47294(){ public void setRepeatingRowsAndColumnsBug47294() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet1 = wb.createSheet(); Sheet sheet1 = wb.createSheet();
sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
@ -789,14 +829,15 @@ public abstract class BaseTestSheet {
Sheet sheet2 = wb.createSheet("My' Sheet"); Sheet sheet2 = wb.createSheet("My' Sheet");
sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4")); sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); assertEquals("1:4", sheet2.getRepeatingRows().formatAsString());
wb.close();
} }
@Test @Test
public void setRepeatingRowsAndColumns() { public void setRepeatingRowsAndColumns() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet1 = wb.createSheet("Sheet1"); Sheet sheet1 = wb1.createSheet("Sheet1");
Sheet sheet2 = wb.createSheet("Sheet2"); Sheet sheet2 = wb1.createSheet("Sheet2");
Sheet sheet3 = wb.createSheet("Sheet3"); Sheet sheet3 = wb1.createSheet("Sheet3");
checkRepeatingRowsAndColumns(sheet1, null, null); checkRepeatingRowsAndColumns(sheet1, null, null);
@ -810,10 +851,11 @@ public abstract class BaseTestSheet {
checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A");
// write out, read back, and test refrain... // write out, read back, and test refrain...
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet1 = wb.getSheetAt(0); wb1.close();
sheet2 = wb.getSheetAt(1); sheet1 = wb2.getSheetAt(0);
sheet3 = wb.getSheetAt(2); sheet2 = wb2.getSheetAt(1);
sheet3 = wb2.getSheetAt(2);
checkRepeatingRowsAndColumns(sheet1, "4:5", null); checkRepeatingRowsAndColumns(sheet1, "4:5", null);
checkRepeatingRowsAndColumns(sheet2, null, "A:C"); checkRepeatingRowsAndColumns(sheet2, null, "A:C");
@ -825,6 +867,7 @@ public abstract class BaseTestSheet {
sheet3.setRepeatingColumns(null); sheet3.setRepeatingColumns(null);
checkRepeatingRowsAndColumns(sheet3, null, null); checkRepeatingRowsAndColumns(sheet3, null, null);
wb2.close();
} }
private void checkRepeatingRowsAndColumns( private void checkRepeatingRowsAndColumns(
@ -842,23 +885,25 @@ public abstract class BaseTestSheet {
} }
@Test @Test
public void baseZoom() { public void baseZoom() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
// here we can only verify that setting some zoom values works, range-checking is different between the implementations // here we can only verify that setting some zoom values works, range-checking is different between the implementations
sheet.setZoom(3,4); sheet.setZoom(3,4);
wb.close();
} }
@Test @Test
public void baseShowInPane() { public void baseShowInPane() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
sheet.showInPane(2, 3); sheet.showInPane(2, 3);
wb.close();
} }
@Test @Test
public void bug55723(){ public void bug55723() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
@ -871,6 +916,7 @@ public abstract class BaseTestSheet {
filter = sheet.setAutoFilter(range); filter = sheet.setAutoFilter(range);
assertNotNull(filter); assertNotNull(filter);
// there seems to be currently no generic way to check the setting... // there seems to be currently no generic way to check the setting...
wb.close();
} }
@Test @Test
@ -956,9 +1002,9 @@ public abstract class BaseTestSheet {
} }
@Test @Test
public void showInPaneManyRowsBug55248() { public void showInPaneManyRowsBug55248() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("Sheet 1"); Sheet sheet = wb1.createSheet("Sheet 1");
sheet.showInPane(0, 0); sheet.showInPane(0, 0);
@ -971,8 +1017,11 @@ public abstract class BaseTestSheet {
int i = 0; int i = 0;
sheet.showInPane(i, i); sheet.showInPane(i, i);
Workbook wb = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
checkRowCount(wb); checkRowCount(wb2);
wb2.close();
wb1.close();
} }
private void checkRowCount(Workbook wb) { private void checkRowCount(Workbook wb) {