findbugs fixes

close resources in tests

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1711712 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2015-11-01 03:23:16 +00:00
parent 944253c786
commit 5fd534c44b
12 changed files with 738 additions and 592 deletions

View File

@ -157,11 +157,13 @@ public class ZipSecureFile extends ZipFile {
* @throws IOException if an I/O error has occurred * @throws IOException if an I/O error has occurred
* @throws IllegalStateException if the zip file has been closed * @throws IllegalStateException if the zip file has been closed
*/ */
@SuppressWarnings("resource")
public InputStream getInputStream(ZipEntry entry) throws IOException { public InputStream getInputStream(ZipEntry entry) throws IOException {
InputStream zipIS = super.getInputStream(entry); InputStream zipIS = super.getInputStream(entry);
return addThreshold(zipIS); return addThreshold(zipIS);
} }
@SuppressWarnings("resource")
public static ThresholdInputStream addThreshold(InputStream zipIS) throws IOException { public static ThresholdInputStream addThreshold(InputStream zipIS) throws IOException {
ThresholdInputStream newInner; ThresholdInputStream newInner;
if (zipIS instanceof InflaterInputStream) { if (zipIS instanceof InflaterInputStream) {
@ -246,7 +248,7 @@ public class ZipSecureFile extends ZipFile {
throw new IOException("Zip bomb detected! The file would exceed the max. ratio of compressed file size to the size of the expanded data. " throw new IOException("Zip bomb detected! The file would exceed the max. ratio of compressed file size to the size of the expanded data. "
+ "This may indicate that the file is used to inflate memory usage and thus could pose a security risk. " + "This may indicate that the file is used to inflate memory usage and thus could pose a security risk. "
+ "You can adjust this limit via ZipSecureFile.setMinInflateRatio() if you need to work with files which exceed this limit. " + "You can adjust this limit via ZipSecureFile.setMinInflateRatio() if you need to work with files which exceed this limit. "
+ "Counter: " + counter + ", cis.counter: " + (cis == null ? 0 : cis.counter) + ", ratio: " + (cis == null ? 0 : ((double)cis.counter)/counter) + "Counter: " + counter + ", cis.counter: " + cis.counter + ", ratio: " + (((double)cis.counter)/counter)
+ "Limits: MIN_INFLATE_RATIO: " + MIN_INFLATE_RATIO); + "Limits: MIN_INFLATE_RATIO: " + MIN_INFLATE_RATIO);
} }

View File

@ -19,9 +19,13 @@
package org.apache.poi.xssf.streaming; package org.apache.poi.xssf.streaming;
import java.io.IOException;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.BaseTestRow; import org.apache.poi.ss.usermodel.BaseTestRow;
import org.apache.poi.xssf.SXSSFITestDataProvider; import org.apache.poi.xssf.SXSSFITestDataProvider;
import org.junit.After;
import org.junit.Test;
/** /**
* Tests for XSSFRow * Tests for XSSFRow
@ -33,16 +37,18 @@ public final class TestSXSSFRow extends BaseTestRow {
} }
@Override @After
public void tearDown(){ public void tearDown() {
SXSSFITestDataProvider.instance.cleanup(); SXSSFITestDataProvider.instance.cleanup();
} }
public void testRowBounds() { @Test
public void testRowBounds() throws IOException {
baseTestRowBounds(SpreadsheetVersion.EXCEL2007.getLastRowIndex()); baseTestRowBounds(SpreadsheetVersion.EXCEL2007.getLastRowIndex());
} }
public void testCellBounds() { @Test
public void testCellBounds() throws IOException {
baseTestCellBounds(SpreadsheetVersion.EXCEL2007.getLastColumnIndex()); baseTestCellBounds(SpreadsheetVersion.EXCEL2007.getLastColumnIndex());
} }

View File

@ -62,7 +62,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
*/ */
@Override @Override
@Test @Test
public void cloneSheet() { public void cloneSheet() throws IOException {
try { try {
super.cloneSheet(); super.cloneSheet();
fail("expected exception"); fail("expected exception");
@ -83,27 +83,27 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
@Test @Test
public void existingWorkbook() throws IOException { public void existingWorkbook() throws IOException {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); XSSFWorkbook xssfWb1 = new XSSFWorkbook();
xssfWorkbook.createSheet("S1"); xssfWb1.createSheet("S1");
SXSSFWorkbook wb = new SXSSFWorkbook(xssfWorkbook); @SuppressWarnings("resource")
try { SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1);
xssfWorkbook = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); XSSFWorkbook xssfWb2 = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1);
assertTrue(wb.dispose()); assertTrue(wb1.dispose());
wb = new SXSSFWorkbook(xssfWorkbook);
assertEquals(1, wb.getNumberOfSheets());
Sheet sheet = wb.getSheetAt(0);
assertNotNull(sheet);
assertEquals("S1", sheet.getSheetName());
} finally {
assertTrue(wb.dispose());
wb.close();
}
@SuppressWarnings("resource")
SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2);
assertEquals(1, wb2.getNumberOfSheets());
Sheet sheet = wb2.getSheetAt(0);
assertNotNull(sheet);
assertEquals("S1", sheet.getSheetName());
assertTrue(wb2.dispose());
xssfWb2.close();
xssfWb1.close();
} }
@Test @Test
public void useSharedStringsTable() throws Exception { public void useSharedStringsTable() throws Exception {
@SuppressWarnings("resource")
SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true); SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true);
Field f = SXSSFWorkbook.class.getDeclaredField("_sharedStringSource"); Field f = SXSSFWorkbook.class.getDeclaredField("_sharedStringSource");
@ -137,44 +137,49 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
cell = row.getCell(2); cell = row.getCell(2);
assertNotNull(cell); assertNotNull(cell);
assertEquals("A", cell.getStringCellValue()); assertEquals("A", cell.getStringCellValue());
xssfWorkbook.close();
} }
@Test @Test
public void addToExistingWorkbook() { public void addToExistingWorkbook() throws IOException {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); XSSFWorkbook xssfWb1 = new XSSFWorkbook();
xssfWorkbook.createSheet("S1"); xssfWb1.createSheet("S1");
Sheet sheet = xssfWorkbook.createSheet("S2"); Sheet sheet = xssfWb1.createSheet("S2");
Row row = sheet.createRow(1); Row row = sheet.createRow(1);
Cell cell = row.createCell(1); Cell cell = row.createCell(1);
cell.setCellValue("value 2_1_1"); cell.setCellValue("value 2_1_1");
SXSSFWorkbook wb = new SXSSFWorkbook(xssfWorkbook); @SuppressWarnings("resource")
xssfWorkbook = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1);
assertTrue(wb.dispose()); XSSFWorkbook xssfWb2 = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1);
assertTrue(wb1.dispose());
wb = new SXSSFWorkbook(xssfWorkbook); xssfWb1.close();
SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2);
// Add a row to the existing empty sheet // Add a row to the existing empty sheet
Sheet sheet1 = wb.getSheetAt(0); Sheet sheet1 = wb2.getSheetAt(0);
Row row1_1 = sheet1.createRow(1); Row row1_1 = sheet1.createRow(1);
Cell cell1_1_1 = row1_1.createCell(1); Cell cell1_1_1 = row1_1.createCell(1);
cell1_1_1.setCellValue("value 1_1_1"); cell1_1_1.setCellValue("value 1_1_1");
// Add a row to the existing non-empty sheet // Add a row to the existing non-empty sheet
Sheet sheet2 = wb.getSheetAt(1); Sheet sheet2 = wb2.getSheetAt(1);
Row row2_2 = sheet2.createRow(2); Row row2_2 = sheet2.createRow(2);
Cell cell2_2_1 = row2_2.createCell(1); Cell cell2_2_1 = row2_2.createCell(1);
cell2_2_1.setCellValue("value 2_2_1"); cell2_2_1.setCellValue("value 2_2_1");
// Add a sheet with one row // Add a sheet with one row
Sheet sheet3 = wb.createSheet("S3"); Sheet sheet3 = wb2.createSheet("S3");
Row row3_1 = sheet3.createRow(1); Row row3_1 = sheet3.createRow(1);
Cell cell3_1_1 = row3_1.createCell(1); Cell cell3_1_1 = row3_1.createCell(1);
cell3_1_1.setCellValue("value 3_1_1"); cell3_1_1.setCellValue("value 3_1_1");
xssfWorkbook = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); XSSFWorkbook xssfWb3 = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2);
assertEquals(3, xssfWorkbook.getNumberOfSheets()); wb2.close();
assertEquals(3, xssfWb3.getNumberOfSheets());
// Verify sheet 1 // Verify sheet 1
sheet1 = xssfWorkbook.getSheetAt(0); sheet1 = xssfWb3.getSheetAt(0);
assertEquals("S1", sheet1.getSheetName()); assertEquals("S1", sheet1.getSheetName());
assertEquals(1, sheet1.getPhysicalNumberOfRows()); assertEquals(1, sheet1.getPhysicalNumberOfRows());
row1_1 = sheet1.getRow(1); row1_1 = sheet1.getRow(1);
@ -183,7 +188,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
assertNotNull(cell1_1_1); assertNotNull(cell1_1_1);
assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); assertEquals("value 1_1_1", cell1_1_1.getStringCellValue());
// Verify sheet 2 // Verify sheet 2
sheet2 = xssfWorkbook.getSheetAt(1); sheet2 = xssfWb3.getSheetAt(1);
assertEquals("S2", sheet2.getSheetName()); assertEquals("S2", sheet2.getSheetName());
assertEquals(2, sheet2.getPhysicalNumberOfRows()); assertEquals(2, sheet2.getPhysicalNumberOfRows());
Row row2_1 = sheet2.getRow(1); Row row2_1 = sheet2.getRow(1);
@ -197,7 +202,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
assertNotNull(cell2_2_1); assertNotNull(cell2_2_1);
assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); assertEquals("value 2_2_1", cell2_2_1.getStringCellValue());
// Verify sheet 3 // Verify sheet 3
sheet3 = xssfWorkbook.getSheetAt(2); sheet3 = xssfWb3.getSheetAt(2);
assertEquals("S3", sheet3.getSheetName()); assertEquals("S3", sheet3.getSheetName());
assertEquals(1, sheet3.getPhysicalNumberOfRows()); assertEquals(1, sheet3.getPhysicalNumberOfRows());
row3_1 = sheet3.getRow(1); row3_1 = sheet3.getRow(1);
@ -205,6 +210,9 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
cell3_1_1 = row3_1.getCell(1); cell3_1_1 = row3_1.getCell(1);
assertNotNull(cell3_1_1); assertNotNull(cell3_1_1);
assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); assertEquals("value 3_1_1", cell3_1_1.getStringCellValue());
xssfWb2.close();
xssfWb3.close();
} }
@Test @Test
@ -239,11 +247,12 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
assertTrue(wb.dispose()); assertTrue(wb.dispose());
wb.close(); wb.close();
xssfWorkbook.close();
} }
@Test @Test
public void gzipSheetdataWriter(){ public void gzipSheetdataWriter() throws IOException {
@SuppressWarnings("resource")
SXSSFWorkbook wb = new SXSSFWorkbook(); SXSSFWorkbook wb = new SXSSFWorkbook();
wb.setCompressTempFiles(true); wb.setCompressTempFiles(true);
int rowNum = 1000; int rowNum = 1000;
@ -282,7 +291,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
} }
assertTrue(wb.dispose()); assertTrue(wb.dispose());
xwb.close();
} }
static void assertWorkbookDispose(SXSSFWorkbook wb) static void assertWorkbookDispose(SXSSFWorkbook wb)
@ -315,33 +324,37 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook {
} }
} }
@SuppressWarnings("resource")
@Test @Test
public void workbookDispose() public void workbookDispose()
{ {
SXSSFWorkbook wb = new SXSSFWorkbook(); SXSSFWorkbook wb1 = new SXSSFWorkbook();
// the underlying writer is SheetDataWriter // the underlying writer is SheetDataWriter
assertWorkbookDispose(wb); assertWorkbookDispose(wb1);
wb = new SXSSFWorkbook(); SXSSFWorkbook wb2 = new SXSSFWorkbook();
wb.setCompressTempFiles(true); wb2.setCompressTempFiles(true);
// the underlying writer is GZIPSheetDataWriter // the underlying writer is GZIPSheetDataWriter
assertWorkbookDispose(wb); assertWorkbookDispose(wb2);
} }
// currently writing the same sheet multiple times is not supported... // currently writing the same sheet multiple times is not supported...
@Ignore @Ignore
public void bug53515() throws Exception { public void bug53515() throws Exception {
Workbook wb = new SXSSFWorkbook(10); Workbook wb1 = new SXSSFWorkbook(10);
populateWorkbook(wb); populateWorkbook(wb1);
saveTwice(wb); saveTwice(wb1);
wb = new XSSFWorkbook(); Workbook wb2 = new XSSFWorkbook();
populateWorkbook(wb); populateWorkbook(wb2);
saveTwice(wb); saveTwice(wb2);
wb2.close();
wb1.close();
} }
// Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files // Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files
// See http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html // See http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html
@SuppressWarnings("resource")
@Ignore @Ignore
public void bug53515a() throws Exception { public void bug53515a() throws Exception {
File out = new File("Test.xlsx"); File out = new File("Test.xlsx");

View File

@ -17,9 +17,12 @@
package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;
import java.io.IOException;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.BaseTestRow; import org.apache.poi.ss.usermodel.BaseTestRow;
import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFITestDataProvider;
import org.junit.Test;
/** /**
* Tests for XSSFRow * Tests for XSSFRow
@ -30,11 +33,13 @@ public final class TestXSSFRow extends BaseTestRow {
super(XSSFITestDataProvider.instance); super(XSSFITestDataProvider.instance);
} }
public void testRowBounds() { @Test
public void testRowBounds() throws IOException {
baseTestRowBounds(SpreadsheetVersion.EXCEL2007.getLastRowIndex()); baseTestRowBounds(SpreadsheetVersion.EXCEL2007.getLastRowIndex());
} }
public void testCellBounds() { @Test
public void testCellBounds() throws IOException {
baseTestCellBounds(SpreadsheetVersion.EXCEL2007.getLastColumnIndex()); baseTestCellBounds(SpreadsheetVersion.EXCEL2007.getLastColumnIndex());
} }
} }

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 org.apache.poi.ss.usermodel.BaseTestSheetShiftRows; import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows;
@ -33,6 +35,7 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellUtil; import org.apache.poi.ss.util.CellUtil;
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.Test;
/** /**
* @author Yegor Kozlov * @author Yegor Kozlov
@ -44,23 +47,27 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
} }
@Override @Override
@Test
public void testShiftRowBreaks() { // disabled test from superclass public void testShiftRowBreaks() { // disabled test from superclass
// TODO - support shifting of page breaks // TODO - support shifting of page breaks
} }
@Test
public void testBug54524() throws IOException { public void testBug54524() throws IOException {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54524.xlsx"); XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54524.xlsx");
XSSFSheet sheet = workbook.getSheetAt(0); XSSFSheet sheet = workbook.getSheetAt(0);
sheet.shiftRows(3, 5, -1); sheet.shiftRows(3, 5, -1);
Cell cell = CellUtil.getCell(sheet.getRow(1), 0); Cell cell = CellUtil.getCell(sheet.getRow(1), 0);
assertEquals(1.0, cell.getNumericCellValue()); assertEquals(1.0, cell.getNumericCellValue(), 0);
cell = CellUtil.getCell(sheet.getRow(2), 0); cell = CellUtil.getCell(sheet.getRow(2), 0);
assertEquals("SUM(A2:A2)", cell.getCellFormula()); assertEquals("SUM(A2:A2)", cell.getCellFormula());
cell = CellUtil.getCell(sheet.getRow(3), 0); cell = CellUtil.getCell(sheet.getRow(3), 0);
assertEquals("X", cell.getStringCellValue()); assertEquals("X", cell.getStringCellValue());
workbook.close();
} }
@Test
public void testBug53798() throws IOException { public void testBug53798() throws IOException {
// NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected // NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx");
@ -88,6 +95,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
//saveReport(wb, new File("/tmp/53798.xlsx")); //saveReport(wb, new File("/tmp/53798.xlsx"));
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close();
assertNotNull(read); assertNotNull(read);
Sheet readSheet = read.getSheetAt(0); Sheet readSheet = read.getSheetAt(0);
@ -100,6 +108,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
verifyCellContent(readSheet, 6, null); verifyCellContent(readSheet, 6, null);
verifyCellContent(readSheet, 7, "6.0"); verifyCellContent(readSheet, 7, "6.0");
verifyCellContent(readSheet, 8, "7.0"); verifyCellContent(readSheet, 8, "7.0");
read.close();
} }
private void verifyCellContent(Sheet readSheet, int row, String expect) { private void verifyCellContent(Sheet readSheet, int row, String expect) {
@ -116,6 +125,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
} }
} }
@Test
public void testBug53798a() throws IOException { public void testBug53798a() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx");
@ -128,6 +138,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
//saveReport(wb, new File("/tmp/53798.xlsx")); //saveReport(wb, new File("/tmp/53798.xlsx"));
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close();
assertNotNull(read); assertNotNull(read);
Sheet readSheet = read.getSheetAt(0); Sheet readSheet = read.getSheetAt(0);
@ -140,8 +151,10 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
verifyCellContent(readSheet, 6, null); verifyCellContent(readSheet, 6, null);
verifyCellContent(readSheet, 7, "6.0"); verifyCellContent(readSheet, 7, "6.0");
verifyCellContent(readSheet, 8, "8.0"); verifyCellContent(readSheet, 8, "8.0");
read.close();
} }
@Test
public void testBug56017() throws IOException { public void testBug56017() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56017.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56017.xlsx");
@ -172,6 +185,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
// } // }
Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close();
assertNotNull(wbBack); assertNotNull(wbBack);
Sheet sheetBack = wbBack.getSheetAt(0); Sheet sheetBack = wbBack.getSheetAt(0);
@ -185,23 +199,28 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
assertNotNull(comment); assertNotNull(comment);
assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs", comment.getAuthor());
assertEquals("Amdocs:\ntest\n", comment.getString().getString()); assertEquals("Amdocs:\ntest\n", comment.getString().getString());
wbBack.close();
} }
public void test57171() throws Exception { @Test
public void test57171() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
assertEquals(5, wb.getActiveSheetIndex()); assertEquals(5, wb.getActiveSheetIndex());
removeAllSheetsBut(5, wb); // 5 is the active / selected sheet removeAllSheetsBut(5, wb); // 5 is the active / selected sheet
assertEquals(0, wb.getActiveSheetIndex()); assertEquals(0, wb.getActiveSheetIndex());
Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
wb.close();
assertEquals(0, wbRead.getActiveSheetIndex()); assertEquals(0, wbRead.getActiveSheetIndex());
wbRead.removeSheetAt(0); wbRead.removeSheetAt(0);
assertEquals(0, wbRead.getActiveSheetIndex()); assertEquals(0, wbRead.getActiveSheetIndex());
//wb.write(new FileOutputStream("/tmp/57171.xls")); //wb.write(new FileOutputStream("/tmp/57171.xls"));
wbRead.close();
} }
@Test
public void test57163() throws IOException { public void test57163() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
assertEquals(5, wb.getActiveSheetIndex()); assertEquals(5, wb.getActiveSheetIndex());
@ -209,9 +228,11 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
assertEquals(4, wb.getActiveSheetIndex()); assertEquals(4, wb.getActiveSheetIndex());
//wb.write(new FileOutputStream("/tmp/57163.xls")); //wb.write(new FileOutputStream("/tmp/57163.xls"));
wb.close();
} }
public void testSetSheetOrderAndAdjustActiveSheet() throws Exception { @Test
public void testSetSheetOrderAndAdjustActiveSheet() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
assertEquals(5, wb.getActiveSheetIndex()); assertEquals(5, wb.getActiveSheetIndex());
@ -256,9 +277,12 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wb.setSheetOrder(wb.getSheetName(0), 5); wb.setSheetOrder(wb.getSheetName(0), 5);
assertEquals(5, wb.getActiveSheetIndex()); assertEquals(5, wb.getActiveSheetIndex());
wb.close();
} }
public void testRemoveSheetAndAdjustActiveSheet() throws Exception { @Test
public void testRemoveSheetAndAdjustActiveSheet() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
assertEquals(5, wb.getActiveSheetIndex()); assertEquals(5, wb.getActiveSheetIndex());
@ -297,10 +321,13 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wb.removeSheetAt(0); wb.removeSheetAt(0);
assertEquals(0, wb.getActiveSheetIndex()); assertEquals(0, wb.getActiveSheetIndex());
wb.close();
} }
// TODO: enable when bug 57165 is fixed // TODO: enable when bug 57165 is fixed
public void disabled_test57165() throws IOException { @Test
public void test57165() throws IOException {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
assertEquals(5, wb.getActiveSheetIndex()); assertEquals(5, wb.getActiveSheetIndex());
removeAllSheetsBut(3, wb); removeAllSheetsBut(3, wb);
@ -312,6 +339,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
assertEquals(0, wb.getActiveSheetIndex()); assertEquals(0, wb.getActiveSheetIndex());
//wb.write(new FileOutputStream("/tmp/57165.xls")); //wb.write(new FileOutputStream("/tmp/57165.xls"));
wb.close();
} }
// public void test57165b() throws IOException { // public void test57165b() throws IOException {
@ -324,8 +352,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
// } // }
// } // }
private static void removeAllSheetsBut(int sheetIndex, Workbook wb) private static void removeAllSheetsBut(int sheetIndex, Workbook wb) {
{
int sheetNb = wb.getNumberOfSheets(); int sheetNb = wb.getNumberOfSheets();
// Move this sheet at the first position // Move this sheet at the first position
wb.setSheetOrder(wb.getSheetName(sheetIndex), 0); wb.setSheetOrder(wb.getSheetName(sheetIndex), 0);
@ -338,6 +365,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
} }
} }
@Test
public void testBug57828_OnlyOneCommentShiftedInRow() throws IOException { public void testBug57828_OnlyOneCommentShiftedInRow() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx");
XSSFSheet sheet = wb.getSheetAt(0); XSSFSheet sheet = wb.getSheetAt(0);
@ -372,6 +400,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows {
wb.close(); wb.close();
} }
@Test
public void testBug46742_shiftHyperlinks() throws IOException { public void testBug46742_shiftHyperlinks() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("test"); Sheet sheet = wb.createSheet("test");

View File

@ -38,6 +38,7 @@ import java.util.zip.CRC32;
import org.apache.poi.POIXMLProperties; import org.apache.poi.POIXMLProperties;
import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.ContentTypes; import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.openxml4j.opc.PackageAccess;
@ -83,36 +84,35 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
* Tests that we can save, and then re-load a new document * Tests that we can save, and then re-load a new document
*/ */
@Test @Test
public void saveLoadNew() throws Exception { public void saveLoadNew() throws IOException, InvalidFormatException {
@SuppressWarnings("resource") XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFWorkbook workbook = new XSSFWorkbook();
//check that the default date system is set to 1900 //check that the default date system is set to 1900
CTWorkbookPr pr = workbook.getCTWorkbook().getWorkbookPr(); CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr();
assertNotNull(pr); assertNotNull(pr);
assertTrue(pr.isSetDate1904()); assertTrue(pr.isSetDate1904());
assertFalse("XSSF must use the 1900 date system", pr.getDate1904()); assertFalse("XSSF must use the 1900 date system", pr.getDate1904());
Sheet sheet1 = workbook.createSheet("sheet1"); Sheet sheet1 = wb1.createSheet("sheet1");
Sheet sheet2 = workbook.createSheet("sheet2"); Sheet sheet2 = wb1.createSheet("sheet2");
workbook.createSheet("sheet3"); wb1.createSheet("sheet3");
RichTextString rts = workbook.getCreationHelper().createRichTextString("hello world"); RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world");
sheet1.createRow(0).createCell((short)0).setCellValue(1.2); sheet1.createRow(0).createCell((short)0).setCellValue(1.2);
sheet1.createRow(1).createCell((short)0).setCellValue(rts); sheet1.createRow(1).createCell((short)0).setCellValue(rts);
sheet2.createRow(0); sheet2.createRow(0);
assertEquals(0, workbook.getSheetAt(0).getFirstRowNum()); assertEquals(0, wb1.getSheetAt(0).getFirstRowNum());
assertEquals(1, workbook.getSheetAt(0).getLastRowNum()); assertEquals(1, wb1.getSheetAt(0).getLastRowNum());
assertEquals(0, workbook.getSheetAt(1).getFirstRowNum()); assertEquals(0, wb1.getSheetAt(1).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(1).getLastRowNum()); assertEquals(0, wb1.getSheetAt(1).getLastRowNum());
assertEquals(0, workbook.getSheetAt(2).getFirstRowNum()); assertEquals(0, wb1.getSheetAt(2).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(2).getLastRowNum()); assertEquals(0, wb1.getSheetAt(2).getLastRowNum());
File file = TempFile.createTempFile("poi-", ".xlsx"); File file = TempFile.createTempFile("poi-", ".xlsx");
OutputStream out = new FileOutputStream(file); OutputStream out = new FileOutputStream(file);
workbook.write(out); wb1.write(out);
out.close(); out.close();
// Check the package contains what we'd expect it to // Check the package contains what we'd expect it to
@ -128,26 +128,27 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
// Links to the three sheets, shared strings and styles // Links to the three sheets, shared strings and styles
assertTrue(wbPart.hasRelationships()); assertTrue(wbPart.hasRelationships());
assertEquals(5, wbPart.getRelationships().size()); assertEquals(5, wbPart.getRelationships().size());
workbook.close(); wb1.close();
// Load back the XSSFWorkbook // Load back the XSSFWorkbook
workbook = new XSSFWorkbook(pkg); @SuppressWarnings("resource")
assertEquals(3, workbook.getNumberOfSheets()); XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
assertNotNull(workbook.getSheetAt(0)); assertEquals(3, wb2.getNumberOfSheets());
assertNotNull(workbook.getSheetAt(1)); assertNotNull(wb2.getSheetAt(0));
assertNotNull(workbook.getSheetAt(2)); assertNotNull(wb2.getSheetAt(1));
assertNotNull(wb2.getSheetAt(2));
assertNotNull(workbook.getSharedStringSource()); assertNotNull(wb2.getSharedStringSource());
assertNotNull(workbook.getStylesSource()); assertNotNull(wb2.getStylesSource());
assertEquals(0, workbook.getSheetAt(0).getFirstRowNum()); assertEquals(0, wb2.getSheetAt(0).getFirstRowNum());
assertEquals(1, workbook.getSheetAt(0).getLastRowNum()); assertEquals(1, wb2.getSheetAt(0).getLastRowNum());
assertEquals(0, workbook.getSheetAt(1).getFirstRowNum()); assertEquals(0, wb2.getSheetAt(1).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(1).getLastRowNum()); assertEquals(0, wb2.getSheetAt(1).getLastRowNum());
assertEquals(0, workbook.getSheetAt(2).getFirstRowNum()); assertEquals(0, wb2.getSheetAt(2).getFirstRowNum());
assertEquals(0, workbook.getSheetAt(2).getLastRowNum()); assertEquals(0, wb2.getSheetAt(2).getLastRowNum());
sheet1 = workbook.getSheetAt(0); sheet1 = wb2.getSheetAt(0);
assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001); assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001);
assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString()); assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString());
@ -171,6 +172,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertEquals(6, wbPart.getRelationships().size()); assertEquals(6, wbPart.getRelationships().size());
pkg.close(); pkg.close();
workbook.close();
} }
@Test @Test
@ -181,7 +183,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
//get default style //get default style
CellStyle cellStyleAt = workbook.getCellStyleAt(i); CellStyle cellStyleAt = workbook.getCellStyleAt(i);
assertNotNull(cellStyleAt); assertNotNull(cellStyleAt);
//get custom style //get custom style
StylesTable styleSource = workbook.getStylesSource(); StylesTable styleSource = workbook.getStylesSource();
XSSFCellStyle customStyle = new XSSFCellStyle(styleSource); XSSFCellStyle customStyle = new XSSFCellStyle(styleSource);
@ -205,7 +207,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
//get default font //get default font
Font fontAt = workbook.getFontAt(i); Font fontAt = workbook.getFontAt(i);
assertNotNull(fontAt); assertNotNull(fontAt);
//get customized font //get customized font
XSSFFont customFont = new XSSFFont(); XSSFFont customFont = new XSSFFont();
customFont.setItalic(true); customFont.setItalic(true);
@ -230,7 +232,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} }
@Test @Test
public void loadSave() { public void loadSave() throws IOException {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
assertEquals(3, workbook.getNumberOfSheets()); assertEquals(3, workbook.getNumberOfSheets());
assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString());
@ -251,13 +253,16 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertEquals("yy/mm/dd", wb2.getSheetAt(0).getRow(4).getCell(0).getRichStringCellValue().getString()); assertEquals("yy/mm/dd", wb2.getSheetAt(0).getRow(4).getCell(0).getRichStringCellValue().getString());
assertNotNull(wb2.getSharedStringSource()); assertNotNull(wb2.getSharedStringSource());
assertNotNull(wb2.getStylesSource()); assertNotNull(wb2.getStylesSource());
workbook.close();
wb2.close();
} }
@Test @Test
public void styles() { public void styles() throws IOException {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
StylesTable ss = workbook.getStylesSource(); StylesTable ss = wb1.getStylesSource();
assertNotNull(ss); assertNotNull(ss);
StylesTable st = ss; StylesTable st = ss;
@ -281,15 +286,17 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
// Save, load back in again, and check // Save, load back in again, and check
workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
ss = workbook.getStylesSource(); ss = wb2.getStylesSource();
assertNotNull(ss); assertNotNull(ss);
assertEquals(10, st._getNumberFormatSize()); assertEquals(10, st._getNumberFormatSize());
assertEquals(2, st.getFonts().size()); assertEquals(2, st.getFonts().size());
assertEquals(2, st.getFills().size()); assertEquals(2, st.getFills().size());
assertEquals(1, st.getBorders().size()); assertEquals(1, st.getBorders().size());
wb2.close();
} }
@Test @Test
@ -300,7 +307,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertEquals(1, sheetId); assertEquals(1, sheetId);
sheetId = (int)wb.createSheet().sheet.getSheetId(); sheetId = (int)wb.createSheet().sheet.getSheetId();
assertEquals(2, sheetId); assertEquals(2, sheetId);
//test file with gaps in the sheetId sequence //test file with gaps in the sheetId sequence
XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm"); XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm");
try { try {
@ -317,7 +324,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
/** /**
* Test setting of core properties such as Title and Author * Test setting of core properties such as Title and Author
* @throws IOException * @throws IOException
*/ */
@Test @Test
public void workbookProperties() throws IOException { public void workbookProperties() throws IOException {
@ -327,19 +334,20 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertNotNull(props); assertNotNull(props);
//the Application property must be set for new workbooks, see Bugzilla #47559 //the Application property must be set for new workbooks, see Bugzilla #47559
assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication());
PackagePropertiesPart opcProps = props.getCoreProperties().getUnderlyingProperties(); PackagePropertiesPart opcProps = props.getCoreProperties().getUnderlyingProperties();
assertNotNull(opcProps); assertNotNull(opcProps);
opcProps.setTitleProperty("Testing Bugzilla #47460"); opcProps.setTitleProperty("Testing Bugzilla #47460");
assertEquals("Apache POI", opcProps.getCreatorProperty().getValue()); assertEquals("Apache POI", opcProps.getCreatorProperty().getValue());
opcProps.setCreatorProperty("poi-dev@poi.apache.org"); opcProps.setCreatorProperty("poi-dev@poi.apache.org");
XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication());
opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties(); opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties();
assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue()); assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue());
assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue()); assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue());
wbBack.close();
} finally { } finally {
workbook.close(); workbook.close();
} }
@ -380,13 +388,14 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
crc1.update(data1); crc1.update(data1);
assertEquals(crc0.getValue(), crc1.getValue()); assertEquals(crc0.getValue(), crc1.getValue());
workbook.close();
} }
/** /**
* When deleting a sheet make sure that we adjust sheet indices of named ranges * When deleting a sheet make sure that we adjust sheet indices of named ranges
*/ */
@Test @Test
public void bug47737() { public void bug47737() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx"); XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx");
assertEquals(2, wb.getNumberOfNames()); assertEquals(2, wb.getNumberOfNames());
assertNotNull(wb.getCalculationChain()); assertNotNull(wb.getCalculationChain());
@ -406,6 +415,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertEquals(0, nm2.getCTName().getLocalSheetId()); assertEquals(0, nm2.getCTName().getLocalSheetId());
//calculation chain is removed as well //calculation chain is removed as well
assertNull(wb.getCalculationChain()); assertNull(wb.getCalculationChain());
wb.close();
} }
@ -413,27 +423,29 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
* Problems with XSSFWorkbook.removeSheetAt when workbook contains charts * Problems with XSSFWorkbook.removeSheetAt when workbook contains charts
*/ */
@Test @Test
public void bug47813() { public void bug47813() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx"); XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx");
assertEquals(3, wb.getNumberOfSheets()); assertEquals(3, wb1.getNumberOfSheets());
assertNotNull(wb.getCalculationChain()); assertNotNull(wb1.getCalculationChain());
assertEquals("Numbers", wb.getSheetName(0)); assertEquals("Numbers", wb1.getSheetName(0));
//the second sheet is of type 'chartsheet' //the second sheet is of type 'chartsheet'
assertEquals("Chart", wb.getSheetName(1)); assertEquals("Chart", wb1.getSheetName(1));
assertTrue(wb.getSheetAt(1) instanceof XSSFChartSheet); assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet);
assertEquals("SomeJunk", wb.getSheetName(2)); assertEquals("SomeJunk", wb1.getSheetName(2));
wb.removeSheetAt(2); wb1.removeSheetAt(2);
assertEquals(2, wb.getNumberOfSheets()); assertEquals(2, wb1.getNumberOfSheets());
assertNull(wb.getCalculationChain()); assertNull(wb1.getCalculationChain());
wb = XSSFTestDataSamples.writeOutAndReadBack(wb); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
assertEquals(2, wb.getNumberOfSheets()); assertEquals(2, wb2.getNumberOfSheets());
assertNull(wb.getCalculationChain()); assertNull(wb2.getCalculationChain());
assertEquals("Numbers", wb.getSheetName(0)); assertEquals("Numbers", wb2.getSheetName(0));
assertEquals("Chart", wb.getSheetName(1)); assertEquals("Chart", wb2.getSheetName(1));
wb2.close();
wb1.close();
} }
/** /**
@ -441,33 +453,33 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
* coming out wrong * coming out wrong
*/ */
@Test @Test
public void bug49702() throws Exception { public void bug49702() throws IOException {
// First try with a new file // First try with a new file
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb1 = new XSSFWorkbook();
// Should have one style // Should have one style
assertEquals(1, wb.getNumCellStyles()); assertEquals(1, wb1.getNumCellStyles());
wb.getCellStyleAt((short)0); wb1.getCellStyleAt((short)0);
try { try {
wb.getCellStyleAt((short)1); wb1.getCellStyleAt((short)1);
fail("Shouldn't be able to get style at 1 that doesn't exist"); fail("Shouldn't be able to get style at 1 that doesn't exist");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
// Add another one // Add another one
CellStyle cs = wb.createCellStyle(); CellStyle cs = wb1.createCellStyle();
cs.setDataFormat((short)11); cs.setDataFormat((short)11);
// Re-check // Re-check
assertEquals(2, wb.getNumCellStyles()); assertEquals(2, wb1.getNumCellStyles());
wb.getCellStyleAt((short)0); wb1.getCellStyleAt((short)0);
wb.getCellStyleAt((short)1); wb1.getCellStyleAt((short)1);
try { try {
wb.getCellStyleAt((short)2); wb1.getCellStyleAt((short)2);
fail("Shouldn't be able to get style at 2 that doesn't exist"); fail("Shouldn't be able to get style at 2 that doesn't exist");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
// Save and reload // Save and reload
XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1);
assertEquals(2, nwb.getNumCellStyles()); assertEquals(2, nwb.getNumCellStyles());
nwb.getCellStyleAt((short)0); nwb.getCellStyleAt((short)0);
nwb.getCellStyleAt((short)1); nwb.getCellStyleAt((short)1);
@ -477,15 +489,19 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
// Now with an existing file // Now with an existing file
wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
assertEquals(3, wb.getNumCellStyles()); assertEquals(3, wb2.getNumCellStyles());
wb.getCellStyleAt((short)0); wb2.getCellStyleAt((short)0);
wb.getCellStyleAt((short)1); wb2.getCellStyleAt((short)1);
wb.getCellStyleAt((short)2); wb2.getCellStyleAt((short)2);
try { try {
wb.getCellStyleAt((short)3); wb2.getCellStyleAt((short)3);
fail("Shouldn't be able to get style at 3 that doesn't exist"); fail("Shouldn't be able to get style at 3 that doesn't exist");
} catch(IndexOutOfBoundsException e) {} } catch(IndexOutOfBoundsException e) {}
wb2.close();
wb1.close();
nwb.close();
} }
@Test @Test
@ -495,20 +511,20 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertFalse(wb.getForceFormulaRecalculation()); assertFalse(wb.getForceFormulaRecalculation());
CTWorkbook ctWorkbook = wb.getCTWorkbook(); CTWorkbook ctWorkbook = wb.getCTWorkbook();
assertFalse(ctWorkbook.isSetCalcPr()); assertFalse(ctWorkbook.isSetCalcPr());
wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero
CTCalcPr calcPr = ctWorkbook.getCalcPr(); CTCalcPr calcPr = ctWorkbook.getCalcPr();
assertNotNull(calcPr); assertNotNull(calcPr);
assertEquals(0, (int) calcPr.getCalcId()); assertEquals(0, (int) calcPr.getCalcId());
calcPr.setCalcId(100); calcPr.setCalcId(100);
assertTrue(wb.getForceFormulaRecalculation()); assertTrue(wb.getForceFormulaRecalculation());
wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero
assertEquals(0, (int) calcPr.getCalcId()); assertEquals(0, (int) calcPr.getCalcId());
assertFalse(wb.getForceFormulaRecalculation()); assertFalse(wb.getForceFormulaRecalculation());
// calcMode="manual" is unset when forceFormulaRecalculation=true // calcMode="manual" is unset when forceFormulaRecalculation=true
calcPr.setCalcMode(STCalcMode.MANUAL); calcPr.setCalcMode(STCalcMode.MANUAL);
wb.setForceFormulaRecalculation(true); wb.setForceFormulaRecalculation(true);
@ -519,7 +535,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} }
@Test @Test
public void changeSheetNameWithSharedFormulas() { public void changeSheetNameWithSharedFormulas() throws IOException {
changeSheetNameWithSharedFormulas("shared_formulas.xlsx"); changeSheetNameWithSharedFormulas("shared_formulas.xlsx");
} }
@ -549,7 +565,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
sheet = workbook.createSheet(); sheet = workbook.createSheet();
sheet.setColumnWidth(4, 5000); sheet.setColumnWidth(4, 5000);
sheet.setColumnWidth(5, 5000); sheet.setColumnWidth(5, 5000);
sheet.groupColumn((short) 4, (short) 5); sheet.groupColumn((short) 4, (short) 5);
accessWorkbook(workbook); accessWorkbook(workbook);
@ -562,6 +578,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} }
accessWorkbook(workbook); accessWorkbook(workbook);
workbook.close();
} }
private void accessWorkbook(XSSFWorkbook workbook) { private void accessWorkbook(XSSFWorkbook workbook) {
@ -573,39 +590,36 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} }
@Test @Test
public void bug48495() { public void bug48495() throws IOException {
try { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx");
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx");
assertSheetOrder(wb, "Sheet1");
Sheet sheet = wb.getSheetAt(0);
sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false);
Row newRow = sheet.getRow(2);
if (newRow == null) newRow = sheet.createRow(2);
newRow.createCell(0).setCellValue(" Another Header");
wb.cloneSheet(0);
assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); assertSheetOrder(wb, "Sheet1");
// FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx"); Sheet sheet = wb.getSheetAt(0);
sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false);
Row newRow = sheet.getRow(2);
if (newRow == null) newRow = sheet.createRow(2);
newRow.createCell(0).setCellValue(" Another Header");
wb.cloneSheet(0);
assertSheetOrder(wb, "Sheet1", "Sheet1 (2)");
// FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx");
// try { // try {
// wb.write(fileOut); // wb.write(fileOut);
// } finally { // } finally {
// fileOut.close(); // fileOut.close();
// } // }
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
assertNotNull(read); assertNotNull(read);
assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); assertSheetOrder(read, "Sheet1", "Sheet1 (2)");
} catch (Exception e) { read.close();
e.printStackTrace(); wb.close();
}
System.out.println("Done");
} }
@Test @Test
public void bug47090a() { public void bug47090a() throws IOException {
Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
assertSheetOrder(workbook, "Sheet1", "Sheet2"); assertSheetOrder(workbook, "Sheet1", "Sheet2");
workbook.removeSheetAt(0); workbook.removeSheetAt(0);
@ -614,10 +628,12 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertSheetOrder(workbook, "Sheet2", "Sheet1"); assertSheetOrder(workbook, "Sheet2", "Sheet1");
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertSheetOrder(read, "Sheet2", "Sheet1"); assertSheetOrder(read, "Sheet2", "Sheet1");
read.close();
workbook.close();
} }
@Test @Test
public void bug47090b() { public void bug47090b() throws IOException {
Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
assertSheetOrder(workbook, "Sheet1", "Sheet2"); assertSheetOrder(workbook, "Sheet1", "Sheet2");
workbook.removeSheetAt(1); workbook.removeSheetAt(1);
@ -626,39 +642,45 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point!
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertSheetOrder(read, "Sheet1", "Sheet0"); assertSheetOrder(read, "Sheet1", "Sheet0");
read.close();
workbook.close();
} }
@Test @Test
public void bug47090c() { public void bug47090c() throws IOException {
Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
assertSheetOrder(workbook, "Sheet1", "Sheet2"); assertSheetOrder(workbook, "Sheet1", "Sheet2");
workbook.removeSheetAt(0); workbook.removeSheetAt(0);
assertSheetOrder(workbook, "Sheet2"); assertSheetOrder(workbook, "Sheet2");
workbook.cloneSheet(0); workbook.cloneSheet(0);
assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)");
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); assertSheetOrder(read, "Sheet2", "Sheet2 (2)");
read.close();
workbook.close();
} }
@Test @Test
public void bug47090d() { public void bug47090d() throws IOException {
Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
assertSheetOrder(workbook, "Sheet1", "Sheet2"); assertSheetOrder(workbook, "Sheet1", "Sheet2");
workbook.createSheet(); workbook.createSheet();
assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0");
workbook.removeSheetAt(0); workbook.removeSheetAt(0);
assertSheetOrder(workbook, "Sheet2", "Sheet0"); assertSheetOrder(workbook, "Sheet2", "Sheet0");
workbook.createSheet(); workbook.createSheet();
assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1");
Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1");
read.close();
workbook.close();
} }
@Test @Test
public void bug51158() throws IOException { public void bug51158() throws IOException {
// create a workbook // create a workbook
final XSSFWorkbook workbook = new XSSFWorkbook(); final XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Test Sheet"); XSSFSheet sheet = wb1.createSheet("Test Sheet");
XSSFRow row = sheet.createRow(2); XSSFRow row = sheet.createRow(2);
XSSFCell cell = row.createCell(3); XSSFCell cell = row.createCell(3);
cell.setCellValue("test1"); cell.setCellValue("test1");
@ -675,52 +697,59 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
// row.createCell(0).setCellStyle(cs); // row.createCell(0).setCellStyle(cs);
// write the first excel file // write the first excel file
XSSFWorkbook readBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
assertNotNull(readBack); assertNotNull(wb2);
assertEquals("test1", readBack.getSheetAt(0).getRow(2).getCell(3).getStringCellValue()); sheet = wb2.getSheetAt(0);
assertNull(readBack.getSheetAt(0).getRow(2).getCell(4)); row = sheet.getRow(2);
assertEquals("test1", row.getCell(3).getStringCellValue());
assertNull(row.getCell(4));
// add a new cell to the sheet // add a new cell to the sheet
cell = row.createCell(4); cell = row.createCell(4);
cell.setCellValue("test2"); cell.setCellValue("test2");
// write the second excel file // write the second excel file
readBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
assertNotNull(readBack); assertNotNull(wb3);
assertEquals("test1", readBack.getSheetAt(0).getRow(2).getCell(3).getStringCellValue()); sheet = wb3.getSheetAt(0);
assertEquals("test2", readBack.getSheetAt(0).getRow(2).getCell(4).getStringCellValue()); row = sheet.getRow(2);
assertEquals("test1", row.getCell(3).getStringCellValue());
assertEquals("test2", row.getCell(4).getStringCellValue());
wb3.close();
wb2.close();
wb1.close();
} }
@Test @Test
public void bug51158a() throws IOException { public void bug51158a() throws IOException {
// create a workbook // create a workbook
final XSSFWorkbook workbook = new XSSFWorkbook(); final XSSFWorkbook workbook = new XSSFWorkbook();
try { try {
workbook.createSheet("Test Sheet"); workbook.createSheet("Test Sheet");
XSSFSheet sheetBack = workbook.getSheetAt(0); XSSFSheet sheetBack = workbook.getSheetAt(0);
// committing twice did add the XML twice without clearing the part in between // committing twice did add the XML twice without clearing the part in between
sheetBack.commit(); sheetBack.commit();
// ensure that a memory based package part does not have lingering data from previous commit() calls // ensure that a memory based package part does not have lingering data from previous commit() calls
if(sheetBack.getPackagePart() instanceof MemoryPackagePart) { if(sheetBack.getPackagePart() instanceof MemoryPackagePart) {
((MemoryPackagePart)sheetBack.getPackagePart()).clear(); ((MemoryPackagePart)sheetBack.getPackagePart()).clear();
} }
sheetBack.commit(); sheetBack.commit();
String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream())); String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()));
System.out.println(str);
assertEquals(1, countMatches(str, "<worksheet")); assertEquals(1, countMatches(str, "<worksheet"));
} finally { } finally {
workbook.close(); workbook.close();
} }
} }
private static final int INDEX_NOT_FOUND = -1; private static final int INDEX_NOT_FOUND = -1;
private static boolean isEmpty(CharSequence cs) { private static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0; return cs == null || cs.length() == 0;
} }
@ -737,7 +766,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} }
return count; return count;
} }
private static int indexOf(CharSequence cs, CharSequence searchChar, int start) { private static int indexOf(CharSequence cs, CharSequence searchChar, int start) {
return cs.toString().indexOf(searchChar.toString(), start); return cs.toString().indexOf(searchChar.toString(), start);
} }
@ -796,7 +825,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
setPivotData(wb); setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut); wb.write(fileOut);
fileOut.close(); fileOut.close();
@ -810,7 +839,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} finally { } finally {
wb2.close(); wb2.close();
} }
assertTrue(file.delete()); assertTrue(file.delete());
} }
@ -821,7 +850,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
XSSFWorkbook wb = new XSSFWorkbook(); XSSFWorkbook wb = new XSSFWorkbook();
try { try {
setPivotData(wb); setPivotData(wb);
FileOutputStream fileOut = new FileOutputStream(file); FileOutputStream fileOut = new FileOutputStream(file);
try { try {
wb.write(fileOut); wb.write(fileOut);
@ -839,29 +868,29 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
} finally { } finally {
wb2.close(); wb2.close();
} }
assertTrue(file.delete()); assertTrue(file.delete());
} }
@Test @Test
public void testSetFirstVisibleTab_57373() throws IOException { public void testSetFirstVisibleTab_57373() throws IOException {
Workbook wb = new XSSFWorkbook(); Workbook wb = new XSSFWorkbook();
try { try {
/*Sheet sheet1 =*/ wb.createSheet(); /*Sheet sheet1 =*/ wb.createSheet();
Sheet sheet2 = wb.createSheet(); Sheet sheet2 = wb.createSheet();
int idx2 = wb.getSheetIndex(sheet2); int idx2 = wb.getSheetIndex(sheet2);
Sheet sheet3 = wb.createSheet(); Sheet sheet3 = wb.createSheet();
int idx3 = wb.getSheetIndex(sheet3); int idx3 = wb.getSheetIndex(sheet3);
// add many sheets so "first visible" is relevant // add many sheets so "first visible" is relevant
for(int i = 0; i < 30;i++) { for(int i = 0; i < 30;i++) {
wb.createSheet(); wb.createSheet();
} }
wb.setFirstVisibleTab(idx2); wb.setFirstVisibleTab(idx2);
wb.setActiveSheet(idx3); wb.setActiveSheet(idx3);
//wb.write(new FileOutputStream(new File("C:\\temp\\test.xlsx"))); //wb.write(new FileOutputStream(new File("C:\\temp\\test.xlsx")));
assertEquals(idx2, wb.getFirstVisibleTab()); assertEquals(idx2, wb.getFirstVisibleTab());
@ -873,6 +902,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
sheet3 = wbBack.getSheetAt(idx3); sheet3 = wbBack.getSheetAt(idx3);
assertEquals(idx2, wb.getFirstVisibleTab()); assertEquals(idx2, wb.getFirstVisibleTab());
assertEquals(idx3, wb.getActiveSheetIndex()); assertEquals(idx3, wb.getActiveSheetIndex());
wbBack.close();
} finally { } finally {
wb.close(); wb.close();
} }
@ -883,175 +913,163 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook {
*/ */
@Test @Test
public void testSetVBAProject() throws Exception { public void testSetVBAProject() throws Exception {
XSSFWorkbook workbook = null;
OutputStream out = null;
File file; File file;
final byte[] allBytes = new byte[256]; final byte[] allBytes = new byte[256];
for (int i = 0; i < 256; i++) { for (int i = 0; i < 256; i++) {
allBytes[i] = (byte) (i - 128); allBytes[i] = (byte) (i - 128);
} }
try {
workbook = new XSSFWorkbook();
workbook.createSheet();
workbook.setVBAProject(new ByteArrayInputStream(allBytes));
file = TempFile.createTempFile("poi-", ".xlsm");
out = new FileOutputStream(file);
workbook.write(out);
}
finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(workbook);
}
try { XSSFWorkbook wb1 = new XSSFWorkbook();
// Check the package contains what we'd expect it to wb1.createSheet();
OPCPackage pkg = OPCPackage.open(file.toString()); wb1.setVBAProject(new ByteArrayInputStream(allBytes));
PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); file = TempFile.createTempFile("poi-", ".xlsm");
assertTrue(wbPart.hasRelationships()); OutputStream out = new FileOutputStream(file);
final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation()); wb1.write(out);
assertEquals(1, relationships.size()); out.close();
assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationships.getRelationship(0).getTargetURI().toString()); wb1.close();
PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName()));
assertNotNull(vbaPart);
assertFalse(vbaPart.isRelationshipPart());
assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType());
final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream());
assertArrayEquals(allBytes, fromFile);
// Load back the XSSFWorkbook just to check nothing explodes // Check the package contains what we'd expect it to
workbook = new XSSFWorkbook(pkg); OPCPackage pkg = OPCPackage.open(file.toString());
assertEquals(1, workbook.getNumberOfSheets()); PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
assertEquals(XSSFWorkbookType.XLSM, workbook.getWorkbookType()); assertTrue(wbPart.hasRelationships());
} final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation());
finally { assertEquals(1, relationships.size());
IOUtils.closeQuietly(workbook); assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationships.getRelationship(0).getTargetURI().toString());
} PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName()));
assertNotNull(vbaPart);
assertFalse(vbaPart.isRelationshipPart());
assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType());
final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream());
assertArrayEquals(allBytes, fromFile);
// Load back the XSSFWorkbook just to check nothing explodes
@SuppressWarnings("resource")
XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
assertEquals(1, wb2.getNumberOfSheets());
assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType());
pkg.close();
} }
@Test @Test
public void testBug54399() throws IOException { public void testBug54399() throws IOException {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54399.xlsx"); XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54399.xlsx");
//System.out.println("sheets:" + workbook.getNumberOfSheets());
for (int i = 0; i < workbook.getNumberOfSheets(); i++) { for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
//System.out.println("i:" + i);
workbook.setSheetName(i, "SheetRenamed" + (i + 1)); workbook.setSheetName(i, "SheetRenamed" + (i + 1));
} }
// FileOutputStream fileOutputStream = new FileOutputStream("/tmp/54399.xlsx"); workbook.close();
// workbook.write(fileOutputStream);
// fileOutputStream.close();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
/** /**
* Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30 * Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30
* and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator * and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator
* *
* In order to make code for looping over sheets in workbooks standard, regardless * In order to make code for looping over sheets in workbooks standard, regardless
* of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously
* available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator
* have been replaced with Iterator<Sheet> {@link #iterator} and * have been replaced with Iterator<Sheet> {@link #iterator} and
* Iterator<Sheet> {@link #sheetIterator}. This makes iterating over sheets in a workbook * Iterator<Sheet> {@link #sheetIterator}. This makes iterating over sheets in a workbook
* similar to iterating over rows in a sheet and cells in a row. * similar to iterating over rows in a sheet and cells in a row.
* *
* Note: this breaks backwards compatibility! Existing codebases will need to * Note: this breaks backwards compatibility! Existing codebases will need to
* upgrade their code with either of the following options presented in this test case. * upgrade their code with either of the following options presented in this test case.
* *
*/ */
public void bug58245_XSSFSheetIterator() { public void bug58245_XSSFSheetIterator() throws IOException {
final XSSFWorkbook wb = new XSSFWorkbook(); final XSSFWorkbook wb = new XSSFWorkbook();
try { wb.createSheet();
wb.createSheet();
// =====================================================================
// ===================================================================== // Case 1: Existing code uses XSSFSheet for-each loop
// Case 1: Existing code uses XSSFSheet for-each loop // =====================================================================
// ===================================================================== // Original code (no longer valid)
// Original code (no longer valid) /*
/* for (XSSFSheet sh : wb) {
for (XSSFSheet sh : wb) { sh.createRow(0);
sh.createRow(0); }
} */
*/
// Option A:
// Option A: for (XSSFSheet sh : (Iterable<XSSFSheet>) (Iterable<? extends Sheet>) wb) {
for (XSSFSheet sh : (Iterable<XSSFSheet>) (Iterable<? extends Sheet>) wb) { sh.createRow(0);
sh.createRow(0); }
}
// Option B (preferred for new code):
// Option B (preferred for new code): for (Sheet sh : wb) {
for (Sheet sh : wb) { sh.createRow(0);
sh.createRow(0); }
}
// =====================================================================
// ===================================================================== // Case 2: Existing code creates an iterator variable
// Case 2: Existing code creates an iterator variable // =====================================================================
// ===================================================================== // Original code (no longer valid)
// Original code (no longer valid) /*
/* Iterator<XSSFSheet> it = wb.iterator();
Iterator<XSSFSheet> it = wb.iterator(); XSSFSheet sh = it.next();
sh.createRow(0);
*/
// Option A:
{
Iterator<XSSFSheet> it = (Iterator<XSSFSheet>) (Iterator<? extends Sheet>) wb.iterator();
XSSFSheet sh = it.next(); XSSFSheet sh = it.next();
sh.createRow(0); sh.createRow(0);
*/
// Option A:
{
Iterator<XSSFSheet> it = (Iterator<XSSFSheet>) (Iterator<? extends Sheet>) wb.iterator();
XSSFSheet sh = it.next();
sh.createRow(0);
}
// Option B:
{
@SuppressWarnings("deprecation")
Iterator<XSSFSheet> it = wb.xssfSheetIterator();
XSSFSheet sh = it.next();
sh.createRow(0);
}
// Option C (preferred for new code):
{
Iterator<Sheet> it = wb.iterator();
Sheet sh = it.next();
sh.createRow(0);
}
} }
finally {
IOUtils.closeQuietly(wb); // Option B:
{
@SuppressWarnings("deprecation")
Iterator<XSSFSheet> it = wb.xssfSheetIterator();
XSSFSheet sh = it.next();
sh.createRow(0);
} }
}
// Option C (preferred for new code):
{
Iterator<Sheet> it = wb.iterator();
Sheet sh = it.next();
sh.createRow(0);
}
wb.close();
}
@Test @Test
public void testBug56957CloseWorkbook() throws Exception { public void testBug56957CloseWorkbook() throws Exception {
File file = TempFile.createTempFile("TestBug56957_", ".xlsx"); File file = TempFile.createTempFile("TestBug56957_", ".xlsx");
final String dateExp = "Sun Nov 09 00:00:00 CET 2014";
try { try {
// as the file is written to, we make a copy before actually working on it // as the file is written to, we make a copy before actually working on it
FileHelper.copyFile(HSSFTestDataSamples.getSampleFile("56957.xlsx"), file); FileHelper.copyFile(HSSFTestDataSamples.getSampleFile("56957.xlsx"), file);
assertTrue(file.exists()); assertTrue(file.exists());
// read-only mode works! // read-only mode works!
Workbook workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ)); Workbook workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ));
System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); String str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString();
assertEquals(dateExp, str);
workbook.close(); workbook.close();
workbook = null; workbook = null;
workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ)); workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ));
System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString();
assertEquals(dateExp, str);
workbook.close(); workbook.close();
workbook = null; workbook = null;
// now check read/write mode // now check read/write mode
workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE)); workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE));
System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString();
assertEquals(dateExp, str);
workbook.close(); workbook.close();
workbook = null; workbook = null;
workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE)); workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE));
System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString();
assertEquals(dateExp, str);
workbook.close(); workbook.close();
workbook = null; workbook = null;
} finally { } finally {

View File

@ -29,13 +29,7 @@ import org.apache.poi.util.Beta;
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/ */
@Beta @Beta
public final class NumberFormatter public final class NumberFormatter {
{
private static final String[] ENGLISH_LETTERS = new String[] { "a", "b",
"c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
private static final String[] ROMAN_LETTERS = { "m", "cm", "d", "cd", "c", private static final String[] ROMAN_LETTERS = { "m", "cm", "d", "cd", "c",
"xc", "l", "xl", "x", "ix", "v", "iv", "i" }; "xc", "l", "xl", "x", "ix", "v", "iv", "i" };
@ -67,55 +61,26 @@ public final class NumberFormatter
return String.valueOf( num ); return String.valueOf( num );
} }
} }
private static String toLetters( int number ) private static String toLetters(int number) {
{ if ( number <= 0 ) {
final int base = 26;
if ( number <= 0 )
throw new IllegalArgumentException( "Unsupported number: " + number ); throw new IllegalArgumentException( "Unsupported number: " + number );
if ( number < base + 1 )
return ENGLISH_LETTERS[number - 1];
long toProcess = number;
StringBuilder stringBuilder = new StringBuilder();
int maxPower = 0;
{
int boundary = 0;
while ( toProcess > boundary )
{
maxPower++;
boundary = boundary * base + base;
if ( boundary > Integer.MAX_VALUE )
throw new IllegalArgumentException( "Unsupported number: "
+ toProcess );
}
} }
maxPower--;
for ( int p = maxPower; p > 0; p-- ) int num = number;
{ final int radix = 26;
long boundary = 0;
long shift = 1;
for ( int i = 0; i < p; i++ )
{
shift *= base;
boundary = boundary * base + base;
}
int count = 0; char buf[] = new char[33];
while ( toProcess > boundary ) int charPos = buf.length;
{
count++; while (num > 0) {
toProcess -= shift; num--; // 1 => a, not 0 => a
} int remainder = num % radix;
stringBuilder.append( ENGLISH_LETTERS[count - 1] ); buf[--charPos] = (char)('a'+remainder);
num = (num - remainder) / radix;
} }
stringBuilder.append( ENGLISH_LETTERS[(int) toProcess - 1] );
return stringBuilder.toString(); return new String(buf, charPos, (buf.length - charPos));
} }
private static String toRoman( int number ) private static String toRoman( int number )

View File

@ -17,15 +17,19 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.io.IOException; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import junit.framework.AssertionFailedError; import java.io.IOException;
import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.record.BlankRecord; import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.RowRecord; import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.ss.usermodel.BaseTestRow;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.BaseTestRow;
import org.junit.Test;
/** /**
* Test HSSFRow is okay. * Test HSSFRow is okay.
@ -38,15 +42,16 @@ public final class TestHSSFRow extends BaseTestRow {
super(HSSFITestDataProvider.instance); super(HSSFITestDataProvider.instance);
} }
public void testRowBounds() { public void testRowBounds() throws IOException {
baseTestRowBounds(SpreadsheetVersion.EXCEL97.getLastRowIndex()); baseTestRowBounds(SpreadsheetVersion.EXCEL97.getLastRowIndex());
} }
public void testCellBounds() { public void testCellBounds() throws IOException {
baseTestCellBounds(SpreadsheetVersion.EXCEL97.getLastColumnIndex()); baseTestCellBounds(SpreadsheetVersion.EXCEL97.getLastColumnIndex());
} }
public void testLastAndFirstColumns_bug46654() { @Test
public void testLastAndFirstColumns_bug46654() throws IOException {
int ROW_IX = 10; int ROW_IX = 10;
int COL_IX = 3; int COL_IX = 3;
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
@ -64,15 +69,18 @@ public final class TestHSSFRow extends BaseTestRow {
HSSFCell cell = row.createCellFromRecord(br); HSSFCell cell = row.createCellFromRecord(br);
if (row.getFirstCellNum() == 2 && row.getLastCellNum() == 5) { if (row.getFirstCellNum() == 2 && row.getLastCellNum() == 5) {
throw new AssertionFailedError("Identified bug 46654a"); fail("Identified bug 46654a");
} }
assertEquals(COL_IX, row.getFirstCellNum()); assertEquals(COL_IX, row.getFirstCellNum());
assertEquals(COL_IX + 1, row.getLastCellNum()); assertEquals(COL_IX + 1, row.getLastCellNum());
row.removeCell(cell); row.removeCell(cell);
assertEquals(-1, row.getFirstCellNum()); assertEquals(-1, row.getFirstCellNum());
assertEquals(-1, row.getLastCellNum()); assertEquals(-1, row.getLastCellNum());
workbook.close();
} }
@Test
public void testMoveCell() throws IOException { public void testMoveCell() throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(); HSSFSheet sheet = workbook.createSheet();
@ -121,6 +129,7 @@ public final class TestHSSFRow extends BaseTestRow {
workbook.close(); workbook.close();
} }
@Test
public void testRowHeight() throws IOException{ public void testRowHeight() throws IOException{
HSSFWorkbook workbook = new HSSFWorkbook(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(); HSSFSheet sheet = workbook.createSheet();

View File

@ -136,68 +136,73 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
} }
@Test @Test
public void readWriteWithCharts() { public void readWriteWithCharts() throws IOException {
HSSFWorkbook b;
HSSFSheet s; HSSFSheet s;
// Single chart, two sheets // Single chart, two sheets
b = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); HSSFWorkbook b1 = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls");
assertEquals(2, b.getNumberOfSheets()); assertEquals(2, b1.getNumberOfSheets());
assertEquals("Graph2", b.getSheetName(1)); assertEquals("Graph2", b1.getSheetName(1));
s = b.getSheetAt(1); s = b1.getSheetAt(1);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
assertEquals(8, s.getLastRowNum()); assertEquals(8, s.getLastRowNum());
// Has chart on 1st sheet?? // Has chart on 1st sheet??
// FIXME // FIXME
assertNotNull(b.getSheetAt(0).getDrawingPatriarch()); assertNotNull(b1.getSheetAt(0).getDrawingPatriarch());
assertNull(b.getSheetAt(1).getDrawingPatriarch()); assertNull(b1.getSheetAt(1).getDrawingPatriarch());
assertFalse(b.getSheetAt(0).getDrawingPatriarch().containsChart()); assertFalse(b1.getSheetAt(0).getDrawingPatriarch().containsChart());
b1.close();
// We've now called getDrawingPatriarch() so // We've now called getDrawingPatriarch() so
// everything will be all screwy // everything will be all screwy
// So, start again // So, start again
b = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); HSSFWorkbook b2 = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls");
b = HSSFTestDataSamples.writeOutAndReadBack(b); HSSFWorkbook b3 = HSSFTestDataSamples.writeOutAndReadBack(b2);
assertEquals(2, b.getNumberOfSheets()); b2.close();
s = b.getSheetAt(1);
assertEquals(2, b3.getNumberOfSheets());
s = b3.getSheetAt(1);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
assertEquals(8, s.getLastRowNum()); assertEquals(8, s.getLastRowNum());
b3.close();
// Two charts, three sheets // Two charts, three sheets
b = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); HSSFWorkbook b4 = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls");
assertEquals(3, b.getNumberOfSheets()); assertEquals(3, b4.getNumberOfSheets());
s = b.getSheetAt(1); s = b4.getSheetAt(1);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
assertEquals(8, s.getLastRowNum()); assertEquals(8, s.getLastRowNum());
s = b.getSheetAt(2); s = b4.getSheetAt(2);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
assertEquals(8, s.getLastRowNum()); assertEquals(8, s.getLastRowNum());
// Has chart on 1st sheet?? // Has chart on 1st sheet??
// FIXME // FIXME
assertNotNull(b.getSheetAt(0).getDrawingPatriarch()); assertNotNull(b4.getSheetAt(0).getDrawingPatriarch());
assertNull(b.getSheetAt(1).getDrawingPatriarch()); assertNull(b4.getSheetAt(1).getDrawingPatriarch());
assertNull(b.getSheetAt(2).getDrawingPatriarch()); assertNull(b4.getSheetAt(2).getDrawingPatriarch());
assertFalse(b.getSheetAt(0).getDrawingPatriarch().containsChart()); assertFalse(b4.getSheetAt(0).getDrawingPatriarch().containsChart());
b4.close();
// We've now called getDrawingPatriarch() so // We've now called getDrawingPatriarch() so
// everything will be all screwy // everything will be all screwy
// So, start again // So, start again
b = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); HSSFWorkbook b5 = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls");
b = HSSFTestDataSamples.writeOutAndReadBack(b); HSSFWorkbook b6 = HSSFTestDataSamples.writeOutAndReadBack(b5);
assertEquals(3, b.getNumberOfSheets()); b5.close();
assertEquals(3, b6.getNumberOfSheets());
s = b.getSheetAt(1); s = b6.getSheetAt(1);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
assertEquals(8, s.getLastRowNum()); assertEquals(8, s.getLastRowNum());
s = b.getSheetAt(2); s = b6.getSheetAt(2);
assertEquals(0, s.getFirstRowNum()); assertEquals(0, s.getFirstRowNum());
assertEquals(8, s.getLastRowNum()); assertEquals(8, s.getLastRowNum());
b6.close();
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -399,7 +404,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
* that point to deleted sheets * that point to deleted sheets
*/ */
@Test @Test
public void namesToDeleteSheets() { public void namesToDeleteSheets() throws IOException {
HSSFWorkbook b = HSSFTestDataSamples.openSampleWorkbook("30978-deleted.xls"); HSSFWorkbook b = HSSFTestDataSamples.openSampleWorkbook("30978-deleted.xls");
assertEquals(3, b.getNumberOfNames()); assertEquals(3, b.getNumberOfNames());
@ -478,6 +483,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
assertEquals("OnSheet3", n.getNameName()); assertEquals("OnSheet3", n.getNameName());
assertEquals("Sheet3", n.getSheetName()); assertEquals("Sheet3", n.getSheetName());
assertEquals("Sheet3!$A$1:$A$2", n.getRefersToFormula()); assertEquals("Sheet3!$A$1:$A$2", n.getRefersToFormula());
b.close();
} }
/** /**
@ -520,30 +527,33 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
* 1-based sheet tab index (not a 1-based extern sheet index) * 1-based sheet tab index (not a 1-based extern sheet index)
*/ */
@Test @Test
public void findBuiltInNameRecord() { public void findBuiltInNameRecord() throws IOException {
// testRRaC has multiple (3) built-in name records // testRRaC has multiple (3) built-in name records
// The second print titles name record has getSheetNumber()==4 // The second print titles name record has getSheetNumber()==4
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testRRaC.xls"); HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("testRRaC.xls");
NameRecord nr; NameRecord nr;
assertEquals(3, wb.getWorkbook().getNumNames()); assertEquals(3, wb1.getWorkbook().getNumNames());
nr = wb.getWorkbook().getNameRecord(2); nr = wb1.getWorkbook().getNameRecord(2);
// TODO - render full row and full column refs properly // TODO - render full row and full column refs properly
assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition())); // 1:1 assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb1, nr.getNameDefinition())); // 1:1
try { try {
wb.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12")); wb1.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12"));
wb.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F")); wb1.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F"));
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (e.getMessage().equals("Builtin (7) already exists for sheet (4)")) { if (e.getMessage().equals("Builtin (7) already exists for sheet (4)")) {
// there was a problem in the code which locates the existing print titles name record // there was a problem in the code which locates the existing print titles name record
throw new RuntimeException("Identified bug 45720b"); fail("Identified bug 45720b");
} }
wb1.close();
throw e; throw e;
} }
wb = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
assertEquals(3, wb.getWorkbook().getNumNames()); wb1.close();
nr = wb.getWorkbook().getNameRecord(2); assertEquals(3, wb2.getWorkbook().getNumNames());
assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition())); // E:F,9:12 nr = wb2.getWorkbook().getNameRecord(2);
assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb2, nr.getNameDefinition())); // E:F,9:12
wb2.close();
} }
/** /**
@ -565,6 +575,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
fs2.close(); fs2.close();
wb.close(); wb.close();
fs1.close();
} }
/** /**
@ -827,20 +838,23 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
EscherBSERecord bse = iwb.getBSERecord(pictureIndex); EscherBSERecord bse = iwb.getBSERecord(pictureIndex);
assertEquals(3, bse.getRef()); assertEquals(3, bse.getRef());
} }
wb.close();
} }
@Test @Test
public void changeSheetNameWithSharedFormulas() { public void changeSheetNameWithSharedFormulas() throws IOException {
changeSheetNameWithSharedFormulas("shared_formulas.xls"); changeSheetNameWithSharedFormulas("shared_formulas.xls");
} }
@Test // Should throw exception about invalid POIFSFileSystem
@Test(expected=IllegalArgumentException.class)
public void emptyDirectoryNode() throws IOException { public void emptyDirectoryNode() throws IOException {
POIFSFileSystem fs = new POIFSFileSystem();
try { try {
assertNotNull(new HSSFWorkbook(new POIFSFileSystem())); new HSSFWorkbook(fs).close();
fail("Should catch exception about invalid POIFSFileSystem"); } finally {
} catch (IllegalArgumentException e) { fs.close();
assertTrue(e.getMessage(), e.getMessage().contains("does not contain a BIFF8"));
} }
} }
@ -1060,6 +1074,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb);
assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received");
read.close();
wb.close();
} }
@Test @Test
@ -1101,6 +1117,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb);
assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest"); assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest");
read.close();
wb.close();
} }
@Test @Test
@ -1140,13 +1158,13 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet");
assertEquals("ASheet!A1", wb.getName(nameName).getRefersToFormula()); assertEquals("ASheet!A1", wb.getName(nameName).getRefersToFormula());
expectName( HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray()));
new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray())), expectName(wb2, nameName, "ASheet!A1");
nameName, "ASheet!A1"); HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray()));
expectName( expectName(wb3, nameName, "ASheet!A1");
new HSSFWorkbook( wb3.close();
new ByteArrayInputStream(stream2.toByteArray())), wb2.close();
nameName, "ASheet!A1"); wb.close();
} }
private void expectName(HSSFWorkbook wb, String name, String expect) { private void expectName(HSSFWorkbook wb, String name, String expect) {
@ -1183,10 +1201,11 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
} }
assertTrue("Should find some images via Client or Child anchors, but did not find any at all", found); assertTrue("Should find some images via Client or Child anchors, but did not find any at all", found);
workbook.close();
} }
@Test @Test
public void testRewriteFileBug58480() throws Exception { public void testRewriteFileBug58480() throws IOException {
final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls");
try { try {
@ -1221,7 +1240,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
} }
private void writeAndCloseWorkbook(Workbook workbook, File file) private void writeAndCloseWorkbook(Workbook workbook, File file)
throws IOException, InterruptedException { throws IOException {
final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
workbook.write(bytesOut); workbook.write(bytesOut);
workbook.close(); workbook.close();

View File

@ -17,18 +17,24 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
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 java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import junit.framework.TestCase;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.junit.Test;
/** /**
* A base class for testing implementations of * A base class for testing implementations of
* {@link org.apache.poi.ss.usermodel.Row} * {@link org.apache.poi.ss.usermodel.Row}
*/ */
public abstract class BaseTestRow extends TestCase { public abstract class BaseTestRow {
private final ITestDataProvider _testDataProvider; private final ITestDataProvider _testDataProvider;
@ -36,7 +42,8 @@ public abstract class BaseTestRow extends TestCase {
_testDataProvider = testDataProvider; _testDataProvider = testDataProvider;
} }
public void testLastAndFirstColumns() { @Test
public void testLastAndFirstColumns() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -58,13 +65,14 @@ public abstract class BaseTestRow extends TestCase {
row.createCell(3); row.createCell(3);
assertEquals(1, row.getFirstCellNum()); assertEquals(1, row.getFirstCellNum());
assertEquals(4, row.getLastCellNum()); assertEquals(4, row.getLastCellNum());
workbook.close();
} }
/** /**
* Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum * Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum
* This test was added in response to bug report 44987. * This test was added in response to bug report 44987.
*/ */
public void testBoundsInMultipleRows() { public void testBoundsInMultipleRows() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
Row rowA = sheet.createRow(0); Row rowA = sheet.createRow(0);
@ -86,12 +94,13 @@ public abstract class BaseTestRow extends TestCase {
assertEquals(51, rowA.getLastCellNum()); assertEquals(51, rowA.getLastCellNum());
assertEquals(31, rowB.getLastCellNum()); assertEquals(31, rowB.getLastCellNum());
workbook.close();
} }
public void testRemoveCell() { public void testRemoveCell() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
{ {
Sheet sheet = workbook.createSheet(); Sheet sheet = wb1.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
assertEquals(0, row.getPhysicalNumberOfCells()); assertEquals(0, row.getPhysicalNumberOfCells());
@ -116,18 +125,21 @@ public abstract class BaseTestRow extends TestCase {
assertEquals(0, row.getPhysicalNumberOfCells()); assertEquals(0, row.getPhysicalNumberOfCells());
} }
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
{ {
Sheet sheet = workbook.getSheetAt(0); Sheet sheet = wb2.getSheetAt(0);
Row row = sheet.getRow(0); Row row = sheet.getRow(0);
assertEquals(-1, row.getLastCellNum()); assertEquals(-1, row.getLastCellNum());
assertEquals(-1, row.getFirstCellNum()); assertEquals(-1, row.getFirstCellNum());
assertEquals(0, row.getPhysicalNumberOfCells()); assertEquals(0, row.getPhysicalNumberOfCells());
} }
wb2.close();
} }
public void baseTestRowBounds(int maxRowNum) { public void baseTestRowBounds(int maxRowNum) throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = workbook.createSheet();
//Test low row bound //Test low row bound
@ -152,11 +164,13 @@ public abstract class BaseTestRow extends TestCase {
// expected during successful test // expected during successful test
assertEquals("Invalid row number ("+(maxRowNum + 1)+") outside allowable range (0.."+maxRowNum+")", e.getMessage()); assertEquals("Invalid row number ("+(maxRowNum + 1)+") outside allowable range (0.."+maxRowNum+")", e.getMessage());
} }
workbook.close();
} }
public void baseTestCellBounds(int maxCellNum) { public void baseTestCellBounds(int maxCellNum) throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = wb1.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
//Test low cell bound //Test low cell bound
@ -180,22 +194,24 @@ public abstract class BaseTestRow extends TestCase {
row.createCell(i); row.createCell(i);
} }
assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); assertEquals(maxCellNum, row.getPhysicalNumberOfCells());
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = workbook.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
row = sheet.getRow(0); row = sheet.getRow(0);
assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); assertEquals(maxCellNum, row.getPhysicalNumberOfCells());
for(int i=0; i < maxCellNum; i++){ for(int i=0; i < maxCellNum; i++){
Cell cell = row.getCell(i); Cell cell = row.getCell(i);
assertEquals(i, cell.getColumnIndex()); assertEquals(i, cell.getColumnIndex());
} }
wb2.close();
} }
/** /**
* Prior to patch 43901, POI was producing files with the wrong last-column * Prior to patch 43901, POI was producing files with the wrong last-column
* number on the row * number on the row
*/ */
public void testLastCellNumIsCorrectAfterAddCell_bug43901(){ public void testLastCellNumIsCorrectAfterAddCell_bug43901() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("test"); Sheet sheet = workbook.createSheet("test");
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -212,12 +228,13 @@ public abstract class BaseTestRow extends TestCase {
assertEquals(1, row.getLastCellNum()); assertEquals(1, row.getLastCellNum());
row.createCell(255); row.createCell(255);
assertEquals(256, row.getLastCellNum()); assertEquals(256, row.getLastCellNum());
workbook.close();
} }
/** /**
* Tests for the missing/blank cell policy stuff * Tests for the missing/blank cell policy stuff
*/ */
public void testGetCellPolicy() { public void testGetCellPolicy() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("test"); Sheet sheet = workbook.createSheet("test");
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -284,11 +301,13 @@ public abstract class BaseTestRow extends TestCase {
assertEquals(null, row.getCell(3)); assertEquals(null, row.getCell(3));
assertEquals(null, row.getCell(4)); assertEquals(null, row.getCell(4));
assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType());
workbook.close();
} }
public void testRowHeight() throws IOException { public void testRowHeight() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = wb1.createSheet();
Row row1 = sheet.createRow(0); Row row1 = sheet.createRow(0);
assertEquals(sheet.getDefaultRowHeight(), row1.getHeight()); assertEquals(sheet.getDefaultRowHeight(), row1.getHeight());
@ -314,8 +333,9 @@ public abstract class BaseTestRow extends TestCase {
row4.setZeroHeight(true); row4.setZeroHeight(true);
assertTrue(row4.getZeroHeight()); assertTrue(row4.getZeroHeight());
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = workbook.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
row1 = sheet.getRow(0); row1 = sheet.getRow(0);
row2 = sheet.getRow(1); row2 = sheet.getRow(1);
@ -334,12 +354,13 @@ public abstract class BaseTestRow extends TestCase {
assertFalse(row2.getZeroHeight()); assertFalse(row2.getZeroHeight());
assertFalse(row3.getZeroHeight()); assertFalse(row3.getZeroHeight());
assertTrue(row4.getZeroHeight()); assertTrue(row4.getZeroHeight());
wb2.close();
} }
/** /**
* Test adding cells to a row in various places and see if we can find them again. * Test adding cells to a row in various places and see if we can find them again.
*/ */
public void testCellIterator() { public void testCellIterator() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -393,11 +414,12 @@ public abstract class BaseTestRow extends TestCase {
assertTrue(it.hasNext()); assertTrue(it.hasNext());
assertTrue(cell2 == it.next()); assertTrue(cell2 == it.next());
assertEquals(Cell.CELL_TYPE_STRING, cell5.getCellType()); assertEquals(Cell.CELL_TYPE_STRING, cell5.getCellType());
wb.close();
} }
public void testRowStyle() { public void testRowStyle() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet("test"); Sheet sheet = wb1.createSheet("test");
Row row1 = sheet.createRow(0); Row row1 = sheet.createRow(0);
Row row2 = sheet.createRow(1); Row row2 = sheet.createRow(1);
@ -408,7 +430,7 @@ public abstract class BaseTestRow extends TestCase {
assertEquals(null, row2.getRowStyle()); assertEquals(null, row2.getRowStyle());
// Style one // Style one
CellStyle style = workbook.createCellStyle(); CellStyle style = wb1.createCellStyle();
style.setDataFormat((short)4); style.setDataFormat((short)4);
row2.setRowStyle(style); row2.setRowStyle(style);
@ -419,17 +441,21 @@ public abstract class BaseTestRow extends TestCase {
assertEquals(style, row2.getRowStyle()); assertEquals(style, row2.getRowStyle());
// Save, load and re-check // Save, load and re-check
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = workbook.getSheetAt(0); wb1.close();
sheet = wb2.getSheetAt(0);
row1 = sheet.getRow(0); row1 = sheet.getRow(0);
row2 = sheet.getRow(1); row2 = sheet.getRow(1);
style = workbook.getCellStyleAt(style.getIndex()); style = wb2.getCellStyleAt(style.getIndex());
assertEquals(false, row1.isFormatted()); assertEquals(false, row1.isFormatted());
assertEquals(true, row2.isFormatted()); assertEquals(true, row2.isFormatted());
assertEquals(null, row1.getRowStyle()); assertEquals(null, row1.getRowStyle());
assertEquals(style, row2.getRowStyle()); assertEquals(style, row2.getRowStyle());
assertEquals(4, style.getDataFormat()); assertEquals(4, style.getDataFormat());
wb2.close();
} }
} }

View File

@ -17,14 +17,18 @@
package org.apache.poi.ss.usermodel; package org.apache.poi.ss.usermodel;
import java.io.IOException; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import junit.framework.TestCase; import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.junit.Test;
/** /**
* Tests row shifting capabilities. * Tests row shifting capabilities.
@ -32,7 +36,7 @@ import org.apache.poi.ss.util.CellReference;
* @author Shawn Laubach (slaubach at apache dot com) * @author Shawn Laubach (slaubach at apache dot com)
* @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp)
*/ */
public abstract class BaseTestSheetShiftRows extends TestCase { public abstract class BaseTestSheetShiftRows {
private final ITestDataProvider _testDataProvider; private final ITestDataProvider _testDataProvider;
@ -46,20 +50,22 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
* check. This ensures that if some changes code that breaks * check. This ensures that if some changes code that breaks
* writing or what not, they realize it. * writing or what not, they realize it.
*/ */
public final void testShiftRows(){ @Test
public final void testShiftRows() throws IOException {
// Read initial file in // Read initial file in
String sampleName = "SimpleMultiCell." + _testDataProvider.getStandardFileNameExtension(); String sampleName = "SimpleMultiCell." + _testDataProvider.getStandardFileNameExtension();
Workbook wb = _testDataProvider.openSampleWorkbook(sampleName); Workbook wb1 = _testDataProvider.openSampleWorkbook(sampleName);
Sheet s = wb.getSheetAt( 0 ); Sheet s = wb1.getSheetAt( 0 );
// Shift the second row down 1 and write to temp file // Shift the second row down 1 and write to temp file
s.shiftRows( 1, 1, 1 ); s.shiftRows( 1, 1, 1 );
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
// Read from temp file and check the number of cells in each // Read from temp file and check the number of cells in each
// row (in original file each row was unique) // row (in original file each row was unique)
s = wb.getSheetAt( 0 ); s = wb2.getSheetAt( 0 );
assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1); assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1);
confirmEmptyRow(s, 1); confirmEmptyRow(s, 1);
@ -70,10 +76,11 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
// Shift rows 1-3 down 3 in the current one. This tests when // Shift rows 1-3 down 3 in the current one. This tests when
// 1 row is blank. Write to a another temp file // 1 row is blank. Write to a another temp file
s.shiftRows( 0, 2, 3 ); s.shiftRows( 0, 2, 3 );
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2);
wb2.close();
// Read and ensure things are where they should be // Read and ensure things are where they should be
s = wb.getSheetAt(0); s = wb3.getSheetAt(0);
confirmEmptyRow(s, 0); confirmEmptyRow(s, 0);
confirmEmptyRow(s, 1); confirmEmptyRow(s, 1);
confirmEmptyRow(s, 2); confirmEmptyRow(s, 2);
@ -81,19 +88,23 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
confirmEmptyRow(s, 4); confirmEmptyRow(s, 4);
assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2); assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2);
wb3.close();
// Read the first file again // Read the first file again
wb = _testDataProvider.openSampleWorkbook(sampleName); Workbook wb4 = _testDataProvider.openSampleWorkbook(sampleName);
s = wb.getSheetAt( 0 ); s = wb4.getSheetAt( 0 );
// Shift rows 3 and 4 up and write to temp file // Shift rows 3 and 4 up and write to temp file
s.shiftRows( 2, 3, -2 ); s.shiftRows( 2, 3, -2 );
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb5 = _testDataProvider.writeOutAndReadBack(wb4);
s = wb.getSheetAt( 0 ); wb4.close();
s = wb5.getSheetAt( 0 );
assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3); assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3);
assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4); assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4);
confirmEmptyRow(s, 2); confirmEmptyRow(s, 2);
confirmEmptyRow(s, 3); confirmEmptyRow(s, 3);
assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5);
wb5.close();
} }
private static void confirmEmptyRow(Sheet s, int rowIx) { private static void confirmEmptyRow(Sheet s, int rowIx) {
Row row = s.getRow(rowIx); Row row = s.getRow(rowIx);
@ -103,44 +114,51 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
/** /**
* Tests when rows are null. * Tests when rows are null.
*/ */
public final void testShiftRow() { @Test
Workbook b = _testDataProvider.createWorkbook(); public final void testShiftRow() throws IOException {
Sheet s = b.createSheet(); Workbook wb = _testDataProvider.createWorkbook();
Sheet s = wb.createSheet();
s.createRow(0).createCell(0).setCellValue("TEST1"); s.createRow(0).createCell(0).setCellValue("TEST1");
s.createRow(3).createCell(0).setCellValue("TEST2"); s.createRow(3).createCell(0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
wb.close();
} }
/** /**
* Tests when shifting the first row. * Tests when shifting the first row.
*/ */
public final void testActiveCell() { @Test
Workbook b = _testDataProvider.createWorkbook(); public final void testActiveCell() throws IOException {
Sheet s = b.createSheet(); Workbook wb = _testDataProvider.createWorkbook();
Sheet s = wb.createSheet();
s.createRow(0).createCell(0).setCellValue("TEST1"); s.createRow(0).createCell(0).setCellValue("TEST1");
s.createRow(3).createCell(0).setCellValue("TEST2"); s.createRow(3).createCell(0).setCellValue("TEST2");
s.shiftRows(0,4,1); s.shiftRows(0,4,1);
wb.close();
} }
/** /**
* When shifting rows, the page breaks should go with it * When shifting rows, the page breaks should go with it
*/ */
public void testShiftRowBreaks() { // TODO - enable XSSF test @Test
Workbook b = _testDataProvider.createWorkbook(); public void testShiftRowBreaks() throws IOException { // TODO - enable XSSF test
Sheet s = b.createSheet(); Workbook wb = _testDataProvider.createWorkbook();
Sheet s = wb.createSheet();
Row row = s.createRow(4); Row row = s.createRow(4);
row.createCell(0).setCellValue("test"); row.createCell(0).setCellValue("test");
s.setRowBreak(4); s.setRowBreak(4);
s.shiftRows(4, 4, 2); s.shiftRows(4, 4, 2);
assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6)); assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6));
wb.close();
} }
public void testShiftWithComments() { @Test
Workbook wb = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension()); public void testShiftWithComments() throws IOException {
Workbook wb1 = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension());
Sheet sheet = wb.getSheet("Sheet1"); Sheet sheet = wb1.getSheet("Sheet1");
assertEquals(3, sheet.getLastRowNum()); assertEquals(3, sheet.getLastRowNum());
// Verify comments are in the position expected // Verify comments are in the position expected
@ -178,8 +196,10 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
// Write out and read back in again // Write out and read back in again
// Ensure that the changes were persisted // Ensure that the changes were persisted
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = wb.getSheet("Sheet1"); wb1.close();
sheet = wb2.getSheet("Sheet1");
assertEquals(4, sheet.getLastRowNum()); assertEquals(4, sheet.getLastRowNum());
// Verify comments are in the position expected after the shift // Verify comments are in the position expected after the shift
@ -201,7 +221,7 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
// TODO: it seems HSSFSheet does not correctly remove comments from rows that are overwritten // TODO: it seems HSSFSheet does not correctly remove comments from rows that are overwritten
// by shifting rows... // by shifting rows...
if(!(wb instanceof HSSFWorkbook)) { if(!(wb2 instanceof HSSFWorkbook)) {
assertEquals(2, sheet.getLastRowNum()); assertEquals(2, sheet.getLastRowNum());
// Verify comments are in the position expected // Verify comments are in the position expected
@ -215,9 +235,12 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
assertEquals(comment1,"comment top row3 (index2)\n"); assertEquals(comment1,"comment top row3 (index2)\n");
String comment2 = sheet.getCellComment(2,0).getString().getString(); String comment2 = sheet.getCellComment(2,0).getString().getString();
assertEquals(comment2,"comment top row4 (index3)\n"); assertEquals(comment2,"comment top row4 (index3)\n");
wb2.close();
} }
public final void testShiftWithNames() { @Test
public final void testShiftWithNames() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet1 = wb.createSheet("Sheet1"); Sheet sheet1 = wb.createSheet("Sheet1");
wb.createSheet("Sheet2"); wb.createSheet("Sheet2");
@ -257,9 +280,12 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
name4 = wb.getNameAt(3); name4 = wb.getNameAt(3);
assertEquals("A1", name4.getRefersToFormula()); assertEquals("A1", name4.getRefersToFormula());
wb.close();
} }
public final void testShiftWithMergedRegions() { @Test
public final void testShiftWithMergedRegions() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
@ -273,12 +299,14 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
sheet.shiftRows(0, 1, 2); sheet.shiftRows(0, 1, 2);
region = sheet.getMergedRegion(0); region = sheet.getMergedRegion(0);
assertEquals("A3:C3", region.formatAsString()); assertEquals("A3:C3", region.formatAsString());
wb.close();
} }
/** /**
* See bug #34023 * See bug #34023
*/ */
public final void testShiftWithFormulas() { @Test
public final void testShiftWithFormulas() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension()); Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension());
Sheet sheet = wb.getSheet("Sheet1"); Sheet sheet = wb.getSheet("Sheet1");
@ -332,6 +360,7 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
// Note - named ranges formulas have not been updated // Note - named ranges formulas have not been updated
wb.close();
} }
private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC, private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC,
@ -348,7 +377,8 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
assertEquals(expectedFormula, cell.getCellFormula()); assertEquals(expectedFormula, cell.getCellFormula());
} }
public final void testShiftSharedFormulasBug54206() { @Test
public final void testShiftSharedFormulasBug54206() throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension()); Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension());
Sheet sheet = wb.getSheetAt(0); Sheet sheet = wb.getSheetAt(0);
@ -402,21 +432,21 @@ public abstract class BaseTestSheetShiftRows extends TestCase {
assertEquals("SUM(G29:I29)", sheet.getRow(28).getCell(9).getCellFormula()); assertEquals("SUM(G29:I29)", sheet.getRow(28).getCell(9).getCellFormula());
assertEquals("SUM(G30:I30)", sheet.getRow(29).getCell(9).getCellFormula()); assertEquals("SUM(G30:I30)", sheet.getRow(29).getCell(9).getCellFormula());
wb.close();
} }
@Test
public void testBug55280() throws IOException { public void testBug55280() throws IOException {
Workbook w = _testDataProvider.createWorkbook(); Workbook w = _testDataProvider.createWorkbook();
try { Sheet s = w.createSheet();
Sheet s = w.createSheet(); for (int row = 0; row < 5000; ++row)
for (int row = 0; row < 5000; ++row) s.addMergedRegion(new CellRangeAddress(row, row, 0, 3));
s.addMergedRegion(new CellRangeAddress(row, row, 0, 3));
s.shiftRows(0, 4999, 1); // takes a long time... s.shiftRows(0, 4999, 1); // takes a long time...
} finally { w.close();
w.close();
}
} }
@Test
public void test47169() throws IOException { public void test47169() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet = wb.createSheet(); Sheet sheet = wb.createSheet();

View File

@ -34,8 +34,6 @@ import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.junit.Test; import org.junit.Test;
import junit.framework.AssertionFailedError;
/** /**
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
@ -48,7 +46,7 @@ public abstract class BaseTestWorkbook {
} }
@Test @Test
public void sheetIterator_forEach() { public void sheetIterator_forEach() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); final Workbook wb = _testDataProvider.createWorkbook();
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
wb.createSheet("Sheet1"); wb.createSheet("Sheet1");
@ -58,10 +56,16 @@ public abstract class BaseTestWorkbook {
assertEquals("Sheet"+i, sh.getSheetName()); assertEquals("Sheet"+i, sh.getSheetName());
i++; i++;
} }
wb.close();
} }
@Test /**
public void sheetIterator_sheetsReordered() { * Expected ConcurrentModificationException:
* should not be able to advance an iterator when the
* underlying data has been reordered
*/
@Test(expected=ConcurrentModificationException.class)
public void sheetIterator_sheetsReordered() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); final Workbook wb = _testDataProvider.createWorkbook();
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
wb.createSheet("Sheet1"); wb.createSheet("Sheet1");
@ -74,16 +78,18 @@ public abstract class BaseTestWorkbook {
// Iterator order should be fixed when iterator is created // Iterator order should be fixed when iterator is created
try { try {
assertEquals("Sheet1", it.next().getSheetName()); assertEquals("Sheet1", it.next().getSheetName());
fail("Expected ConcurrentModificationException: "+ } finally {
"should not be able to advance an iterator when the "+ wb.close();
"underlying data has been reordered");
} catch (final ConcurrentModificationException e) {
// expected
} }
} }
@Test /**
public void sheetIterator_sheetRemoved() { * Expected ConcurrentModificationException:
* should not be able to advance an iterator when the
* underlying data has been reordered
*/
@Test(expected=ConcurrentModificationException.class)
public void sheetIterator_sheetRemoved() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); final Workbook wb = _testDataProvider.createWorkbook();
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
wb.createSheet("Sheet1"); wb.createSheet("Sheet1");
@ -95,16 +101,17 @@ public abstract class BaseTestWorkbook {
// Iterator order should be fixed when iterator is created // Iterator order should be fixed when iterator is created
try { try {
it.next(); it.next();
fail("Expected ConcurrentModificationException: "+ } finally {
"should not be able to advance an iterator when the "+ wb.close();
"underlying data has been reordered");
} catch (final ConcurrentModificationException e) {
// expected
} }
} }
@Test /**
public void sheetIterator_remove() { * Expected UnsupportedOperationException:
* should not be able to remove sheets from the sheet iterator
*/
@Test(expected=UnsupportedOperationException.class)
public void sheetIterator_remove() throws IOException {
final Workbook wb = _testDataProvider.createWorkbook(); final Workbook wb = _testDataProvider.createWorkbook();
wb.createSheet("Sheet0"); wb.createSheet("Sheet0");
@ -112,16 +119,14 @@ public abstract class BaseTestWorkbook {
it.next(); //Sheet0 it.next(); //Sheet0
try { try {
it.remove(); it.remove();
fail("Expected UnsupportedOperationException: "+ } finally {
"should not be able to remove sheets from the sheet iterator"); wb.close();
} catch (final UnsupportedOperationException e) {
// expected
} }
} }
@Test @Test
public void createSheet() { public void createSheet() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
assertEquals(0, wb.getNumberOfSheets()); assertEquals(0, wb.getNumberOfSheets());
@ -146,7 +151,7 @@ public abstract class BaseTestWorkbook {
Sheet originalSheet = wb.createSheet("Sheet3"); Sheet originalSheet = wb.createSheet("Sheet3");
Sheet fetchedSheet = wb.getSheet("sheet3"); Sheet fetchedSheet = wb.getSheet("sheet3");
if (fetchedSheet == null) { if (fetchedSheet == null) {
throw new AssertionFailedError("Identified bug 44892"); fail("Identified bug 44892");
} }
assertEquals("Sheet3", fetchedSheet.getSheetName()); assertEquals("Sheet3", fetchedSheet.getSheetName());
assertEquals(3, wb.getNumberOfSheets()); assertEquals(3, wb.getNumberOfSheets());
@ -212,11 +217,13 @@ public abstract class BaseTestWorkbook {
assertNull(wb.getSheet("unknown")); assertNull(wb.getSheet("unknown"));
//serialize and read again //serialize and read again
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb);
assertEquals(3, wb.getNumberOfSheets()); wb.close();
assertEquals(0, wb.getSheetIndex("sheet0")); assertEquals(3, wb2.getNumberOfSheets());
assertEquals(1, wb.getSheetIndex("sheet1")); assertEquals(0, wb2.getSheetIndex("sheet0"));
assertEquals(2, wb.getSheetIndex("I changed!")); assertEquals(1, wb2.getSheetIndex("sheet1"));
assertEquals(2, wb2.getSheetIndex("I changed!"));
wb2.close();
} }
/** /**
@ -228,23 +235,23 @@ public abstract class BaseTestWorkbook {
* but for the purpose of uniqueness long sheet names are silently truncated to 31 chars. * but for the purpose of uniqueness long sheet names are silently truncated to 31 chars.
*/ */
@Test @Test
public void createSheetWithLongNames() { public void createSheetWithLongNames() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
String sheetName1 = "My very long sheet name which is longer than 31 chars"; String sheetName1 = "My very long sheet name which is longer than 31 chars";
String truncatedSheetName1 = sheetName1.substring(0, 31); String truncatedSheetName1 = sheetName1.substring(0, 31);
Sheet sh1 = wb.createSheet(sheetName1); Sheet sh1 = wb1.createSheet(sheetName1);
assertEquals(truncatedSheetName1, sh1.getSheetName()); assertEquals(truncatedSheetName1, sh1.getSheetName());
assertSame(sh1, wb.getSheet(truncatedSheetName1)); assertSame(sh1, wb1.getSheet(truncatedSheetName1));
// now via wb.setSheetName // now via wb.setSheetName
wb.setSheetName(0, sheetName1); wb1.setSheetName(0, sheetName1);
assertEquals(truncatedSheetName1, sh1.getSheetName()); assertEquals(truncatedSheetName1, sh1.getSheetName());
assertSame(sh1, wb.getSheet(truncatedSheetName1)); assertSame(sh1, wb1.getSheet(truncatedSheetName1));
String sheetName2 = "My very long sheet name which is longer than 31 chars " + String sheetName2 = "My very long sheet name which is longer than 31 chars " +
"and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)"; "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)";
try { try {
/*Sheet sh2 =*/ wb.createSheet(sheetName2); /*Sheet sh2 =*/ wb1.createSheet(sheetName2);
fail("expected exception"); fail("expected exception");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// expected during successful test // expected during successful test
@ -253,15 +260,17 @@ public abstract class BaseTestWorkbook {
String sheetName3 = "POI allows creating sheets with names longer than 31 characters"; String sheetName3 = "POI allows creating sheets with names longer than 31 characters";
String truncatedSheetName3 = sheetName3.substring(0, 31); String truncatedSheetName3 = sheetName3.substring(0, 31);
Sheet sh3 = wb.createSheet(sheetName3); Sheet sh3 = wb1.createSheet(sheetName3);
assertEquals(truncatedSheetName3, sh3.getSheetName()); assertEquals(truncatedSheetName3, sh3.getSheetName());
assertSame(sh3, wb.getSheet(truncatedSheetName3)); assertSame(sh3, wb1.getSheet(truncatedSheetName3));
//serialize and read again //serialize and read again
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
assertEquals(2, wb.getNumberOfSheets()); wb1.close();
assertEquals(0, wb.getSheetIndex(truncatedSheetName1)); assertEquals(2, wb2.getNumberOfSheets());
assertEquals(1, wb.getSheetIndex(truncatedSheetName3)); assertEquals(0, wb2.getSheetIndex(truncatedSheetName1));
assertEquals(1, wb2.getSheetIndex(truncatedSheetName3));
wb2.close();
} }
@Test @Test
@ -317,16 +326,17 @@ public abstract class BaseTestWorkbook {
} }
@Test @Test
public void defaultValues() { public void defaultValues() throws IOException {
Workbook b = _testDataProvider.createWorkbook(); Workbook b = _testDataProvider.createWorkbook();
assertEquals(0, b.getActiveSheetIndex()); assertEquals(0, b.getActiveSheetIndex());
assertEquals(0, b.getFirstVisibleTab()); assertEquals(0, b.getFirstVisibleTab());
assertEquals(0, b.getNumberOfNames()); assertEquals(0, b.getNumberOfNames());
assertEquals(0, b.getNumberOfSheets()); assertEquals(0, b.getNumberOfSheets());
b.close();
} }
@Test @Test
public void sheetSelection() { public void sheetSelection() throws IOException {
Workbook b = _testDataProvider.createWorkbook(); Workbook b = _testDataProvider.createWorkbook();
b.createSheet("Sheet One"); b.createSheet("Sheet One");
b.createSheet("Sheet Two"); b.createSheet("Sheet Two");
@ -335,10 +345,11 @@ public abstract class BaseTestWorkbook {
b.setFirstVisibleTab(1); b.setFirstVisibleTab(1);
assertEquals(1, b.getActiveSheetIndex()); assertEquals(1, b.getActiveSheetIndex());
assertEquals(1, b.getFirstVisibleTab()); assertEquals(1, b.getFirstVisibleTab());
b.close();
} }
@Test @Test
public void printArea() { public void printArea() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
Sheet sheet1 = workbook.createSheet("Test Print Area"); Sheet sheet1 = workbook.createSheet("Test Print Area");
String sheetName1 = sheet1.getSheetName(); String sheetName1 = sheet1.getSheetName();
@ -355,10 +366,11 @@ public abstract class BaseTestWorkbook {
workbook.removePrintArea(0); workbook.removePrintArea(0);
assertNull(workbook.getPrintArea(0)); assertNull(workbook.getPrintArea(0));
workbook.close();
} }
@Test @Test
public void getSetActiveSheet(){ public void getSetActiveSheet() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook workbook = _testDataProvider.createWorkbook();
assertEquals(0, workbook.getActiveSheetIndex()); assertEquals(0, workbook.getActiveSheetIndex());
@ -373,10 +385,11 @@ public abstract class BaseTestWorkbook {
workbook.setActiveSheet(0); workbook.setActiveSheet(0);
// test if second sheet is set up // test if second sheet is set up
assertEquals(0, workbook.getActiveSheetIndex()); assertEquals(0, workbook.getActiveSheetIndex());
workbook.close();
} }
@Test @Test
public void setSheetOrder() { public void setSheetOrder() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
for (int i=0; i < 10; i++) { for (int i=0; i < 10; i++) {
@ -420,6 +433,7 @@ public abstract class BaseTestWorkbook {
assertEquals(9, wb.getSheetIndex("Sheet 1")); assertEquals(9, wb.getSheetIndex("Sheet 1"));
Workbook wbr = _testDataProvider.writeOutAndReadBack(wb); Workbook wbr = _testDataProvider.writeOutAndReadBack(wb);
wb.close();
assertEquals(0, wbr.getSheetIndex("Sheet 6")); assertEquals(0, wbr.getSheetIndex("Sheet 6"));
assertEquals(1, wbr.getSheetIndex("Sheet 0")); assertEquals(1, wbr.getSheetIndex("Sheet 0"));
@ -439,10 +453,12 @@ public abstract class BaseTestWorkbook {
Sheet s = wbr.getSheetAt(i); Sheet s = wbr.getSheetAt(i);
assertEquals(i, wbr.getSheetIndex(s)); assertEquals(i, wbr.getSheetIndex(s));
} }
wbr.close();
} }
@Test @Test
public void cloneSheet() { public void cloneSheet() throws IOException {
Workbook book = _testDataProvider.createWorkbook(); Workbook book = _testDataProvider.createWorkbook();
Sheet sheet = book.createSheet("TEST"); Sheet sheet = book.createSheet("TEST");
sheet.createRow(0).createCell(0).setCellValue("Test"); sheet.createRow(0).createCell(0).setCellValue("Test");
@ -467,14 +483,14 @@ public abstract class BaseTestWorkbook {
clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2)); clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2));
assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); assertEquals(3, clonedSheet.getPhysicalNumberOfRows());
assertEquals(3, clonedSheet.getNumMergedRegions()); assertEquals(3, clonedSheet.getNumMergedRegions());
book.close();
} }
@Test @Test
public void parentReferences(){ public void parentReferences() throws IOException {
Workbook workbook = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
Sheet sheet = workbook.createSheet(); Sheet sheet = wb1.createSheet();
assertSame(workbook, sheet.getWorkbook()); assertSame(wb1, sheet.getWorkbook());
Row row = sheet.createRow(0); Row row = sheet.createRow(0);
assertSame(sheet, row.getSheet()); assertSame(sheet, row.getSheet());
@ -483,9 +499,10 @@ public abstract class BaseTestWorkbook {
assertSame(sheet, cell.getSheet()); assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow()); assertSame(row, cell.getRow());
workbook = _testDataProvider.writeOutAndReadBack(workbook); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
sheet = workbook.getSheetAt(0); wb1.close();
assertSame(workbook, sheet.getWorkbook()); sheet = wb2.getSheetAt(0);
assertSame(wb2, sheet.getWorkbook());
row = sheet.getRow(0); row = sheet.getRow(0);
assertSame(sheet, row.getSheet()); assertSame(sheet, row.getSheet());
@ -493,6 +510,7 @@ public abstract class BaseTestWorkbook {
cell = row.getCell(1); cell = row.getCell(1);
assertSame(sheet, cell.getSheet()); assertSame(sheet, cell.getSheet());
assertSame(row, cell.getRow()); assertSame(row, cell.getRow());
wb2.close();
} }
@ -505,7 +523,7 @@ public abstract class BaseTestWorkbook {
*/ */
@Deprecated @Deprecated
@Test @Test
public void setRepeatingRowsAnsColumns(){ public void setRepeatingRowsAnsColumns() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sheet1 = wb.createSheet(); Sheet sheet1 = wb.createSheet();
wb.setRepeatingRowsAndColumns(wb.getSheetIndex(sheet1), 0, 0, 0, 3); wb.setRepeatingRowsAndColumns(wb.getSheetIndex(sheet1), 0, 0, 0, 3);
@ -517,22 +535,23 @@ public abstract class BaseTestWorkbook {
wb.setRepeatingRowsAndColumns(wb.getSheetIndex(sheet2), 0, 0, 0, 3); wb.setRepeatingRowsAndColumns(wb.getSheetIndex(sheet2), 0, 0, 0, 3);
assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); assertEquals("1:4", sheet2.getRepeatingRows().formatAsString());
assertEquals("A:A", sheet1.getRepeatingColumns().formatAsString()); assertEquals("A:A", sheet1.getRepeatingColumns().formatAsString());
wb.close();
} }
/** /**
* Tests that all of the unicode capable string fields can be set, written and then read back * Tests that all of the unicode capable string fields can be set, written and then read back
*/ */
@Test @Test
public void unicodeInAll() { public void unicodeInAll() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb1 = _testDataProvider.createWorkbook();
CreationHelper factory = wb.getCreationHelper(); CreationHelper factory = wb1.getCreationHelper();
//Create a unicode dataformat (contains euro symbol) //Create a unicode dataformat (contains euro symbol)
DataFormat df = wb.createDataFormat(); DataFormat df = wb1.createDataFormat();
final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)"; final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)";
short fmt = df.getFormat(formatStr); short fmt = df.getFormat(formatStr);
//Create a unicode sheet name (euro symbol) //Create a unicode sheet name (euro symbol)
Sheet s = wb.createSheet("\u20ac"); Sheet s = wb1.createSheet("\u20ac");
//Set a unicode header (you guessed it the euro symbol) //Set a unicode header (you guessed it the euro symbol)
Header h = s.getHeader(); Header h = s.getHeader();
@ -558,10 +577,11 @@ public abstract class BaseTestWorkbook {
String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; String formulaString = "TEXT(12.34,\"\u20ac###,##\")";
c3.setCellFormula(formulaString); c3.setCellFormula(formulaString);
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
//Test the sheetname //Test the sheetname
s = wb.getSheet("\u20ac"); s = wb2.getSheet("\u20ac");
assertNotNull(s); assertNotNull(s);
//Test the header //Test the header
@ -579,7 +599,7 @@ public abstract class BaseTestWorkbook {
//Test the dataformat //Test the dataformat
r = s.getRow(0); r = s.getRow(0);
c = r.getCell(1); c = r.getCell(1);
df = wb.createDataFormat(); df = wb2.createDataFormat();
assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat())); assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat()));
//Test the cell string value //Test the cell string value
@ -589,9 +609,10 @@ public abstract class BaseTestWorkbook {
//Test the cell formula //Test the cell formula
c3 = r.getCell(3); c3 = r.getCell(3);
assertEquals(c3.getCellFormula(), formulaString); assertEquals(c3.getCellFormula(), formulaString);
wb2.close();
} }
private Workbook newSetSheetNameTestingWorkbook() throws Exception { private Workbook newSetSheetNameTestingWorkbook() throws IOException {
Workbook wb = _testDataProvider.createWorkbook(); Workbook wb = _testDataProvider.createWorkbook();
Sheet sh1 = wb.createSheet("Worksheet"); Sheet sh1 = wb.createSheet("Worksheet");
Sheet sh2 = wb.createSheet("Testing 47100"); Sheet sh2 = wb.createSheet("Testing 47100");
@ -638,15 +659,15 @@ public abstract class BaseTestWorkbook {
* @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=47100">Bugzilla 47100</a> * @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=47100">Bugzilla 47100</a>
*/ */
@Test @Test
public void setSheetName() throws Exception { public void setSheetName() throws IOException {
Workbook wb = newSetSheetNameTestingWorkbook(); Workbook wb1 = newSetSheetNameTestingWorkbook();
Sheet sh1 = wb.getSheetAt(0); Sheet sh1 = wb1.getSheetAt(0);
Name sale_2 = wb.getNameAt(1); Name sale_2 = wb1.getNameAt(1);
Name sale_3 = wb.getNameAt(2); Name sale_3 = wb1.getNameAt(2);
Name sale_4 = wb.getNameAt(3); Name sale_4 = wb1.getNameAt(3);
assertEquals("sale_2", sale_2.getNameName()); assertEquals("sale_2", sale_2.getNameName());
assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula()); assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula());
@ -655,7 +676,7 @@ public abstract class BaseTestWorkbook {
assertEquals("sale_4", sale_4.getNameName()); assertEquals("sale_4", sale_4.getNameName());
assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula()); assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula());
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb1.getCreationHelper().createFormulaEvaluator();
Cell cell0 = sh1.getRow(0).getCell(0); Cell cell0 = sh1.getRow(0).getCell(0);
Cell cell1 = sh1.getRow(1).getCell(0); Cell cell1 = sh1.getRow(1).getCell(0);
@ -669,8 +690,8 @@ public abstract class BaseTestWorkbook {
assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
wb.setSheetName(1, "47100 - First"); wb1.setSheetName(1, "47100 - First");
wb.setSheetName(2, "47100 - Second"); wb1.setSheetName(2, "47100 - Second");
assertEquals("sale_2", sale_2.getNameName()); assertEquals("sale_2", sale_2.getNameName());
assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula()); assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula());
@ -688,13 +709,14 @@ public abstract class BaseTestWorkbook {
assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
wb = _testDataProvider.writeOutAndReadBack(wb); Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
wb1.close();
sh1 = wb.getSheetAt(0); sh1 = wb2.getSheetAt(0);
sale_2 = wb.getNameAt(1); sale_2 = wb2.getNameAt(1);
sale_3 = wb.getNameAt(2); sale_3 = wb2.getNameAt(2);
sale_4 = wb.getNameAt(3); sale_4 = wb2.getNameAt(3);
cell0 = sh1.getRow(0).getCell(0); cell0 = sh1.getRow(0).getCell(0);
cell1 = sh1.getRow(1).getCell(0); cell1 = sh1.getRow(1).getCell(0);
@ -711,13 +733,14 @@ public abstract class BaseTestWorkbook {
assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula()); assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula());
assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula()); assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula());
evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator = wb2.getCreationHelper().createFormulaEvaluator();
assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0);
assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0);
assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0);
wb2.close();
} }
public void changeSheetNameWithSharedFormulas(String sampleFile){ public void changeSheetNameWithSharedFormulas(String sampleFile) throws IOException {
Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile); Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
@ -740,6 +763,7 @@ public abstract class BaseTestWorkbook {
assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue());
} }
wb.close();
} }
protected void assertSheetOrder(Workbook wb, String... sheets) { protected void assertSheetOrder(Workbook wb, String... sheets) {