}
public static long toBookSheetColumn(int bookIndex, int sheetIndex, int columnIndex) {
- return ((bookIndex & 0xFFFFl) << 48) +
- ((sheetIndex & 0xFFFFl) << 32) +
- ((columnIndex & 0xFFFFl) << 0);
+ return ((bookIndex & 0xFFFFL) << 48) +
+ ((sheetIndex & 0xFFFFL) << 32) +
+ ((columnIndex & 0xFFFFL) << 0);
}
public Loc(long bookSheetColumn, int rowIndex) {
public PlainCellCache() {
_plainValueEntriesByLoc = new HashMap<>();
}
+
public void put(Loc key, PlainValueCellCacheEntry cce) {
_plainValueEntriesByLoc.put(key, cce);
}
+
public void clear() {
_plainValueEntriesByLoc.clear();
}
+
public PlainValueCellCacheEntry get(Loc key) {
return _plainValueEntriesByLoc.get(key);
}
+
public void remove(Loc key) {
_plainValueEntriesByLoc.remove(key);
}
package org.apache.poi.xssf.usermodel;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+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;
+
public final class TestXSSFTable {
@Test
public void bug56274() throws IOException {
// read sample file
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56274.xlsx");
-
- // read the original sheet header order
- XSSFRow row = wb1.getSheetAt(0).getRow(0);
- List<String> headers = new ArrayList<>();
- for (Cell cell : row) {
- headers.add(cell.getStringCellValue());
+ try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56274.xlsx")) {
+
+ // read the original sheet header order
+ XSSFRow row = wb1.getSheetAt(0).getRow(0);
+ List<String> headers = new ArrayList<>();
+ for (Cell cell : row) {
+ headers.add(cell.getStringCellValue());
+ }
+
+ // save the worksheet as-is using SXSSF
+ File outputFile = TempFile.createTempFile("poi-56274", ".xlsx");
+ SXSSFWorkbook outputWorkbook = new SXSSFWorkbook(wb1);
+ FileOutputStream fos = new FileOutputStream(outputFile);
+ outputWorkbook.write(fos);
+ fos.close();
+ outputWorkbook.close();
+
+ // re-read the saved file and make sure headers in the xml are in the original order
+ FileInputStream fis = new FileInputStream(outputFile);
+ XSSFWorkbook wb2 = new XSSFWorkbook(fis);
+ fis.close();
+ CTTable ctTable = wb2.getSheetAt(0).getTables().get(0).getCTTable();
+ CTTableColumn[] ctTableColumnArray = ctTable.getTableColumns().getTableColumnArray();
+
+ assertEquals("number of headers in xml table should match number of header cells in worksheet",
+ headers.size(), ctTableColumnArray.length);
+ for (int i = 0; i < headers.size(); i++) {
+ assertEquals("header name in xml table should match number of header cells in worksheet",
+ headers.get(i), ctTableColumnArray[i].getName());
+ }
+ assertTrue(outputFile.delete());
+ wb2.close();
}
-
- // save the worksheet as-is using SXSSF
- File outputFile = TempFile.createTempFile("poi-56274", ".xlsx");
- SXSSFWorkbook outputWorkbook = new SXSSFWorkbook(wb1);
- FileOutputStream fos = new FileOutputStream(outputFile);
- outputWorkbook.write(fos);
- fos.close();
- outputWorkbook.close();
-
- // re-read the saved file and make sure headers in the xml are in the original order
- FileInputStream fis = new FileInputStream(outputFile);
- XSSFWorkbook wb2 = new XSSFWorkbook(fis);
- fis.close();
- CTTable ctTable = wb2.getSheetAt(0).getTables().get(0).getCTTable();
- CTTableColumn[] ctTableColumnArray = ctTable.getTableColumns().getTableColumnArray();
-
- assertEquals("number of headers in xml table should match number of header cells in worksheet",
- headers.size(), ctTableColumnArray.length);
- for (int i = 0; i < headers.size(); i++) {
- assertEquals("header name in xml table should match number of header cells in worksheet",
- headers.get(i), ctTableColumnArray[i].getName());
- }
- assertTrue(outputFile.delete());
- wb2.close();
- wb1.close();
}
@Test
@Test
public void findColumnIndex() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
-
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertNotNull(table);
- assertEquals("column header has special escaped characters",
- 0, table.findColumnIndex("calc='#*'#"));
- assertEquals(1, table.findColumnIndex("Name"));
- assertEquals(2, table.findColumnIndex("Number"));
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
- assertEquals("case insensitive", 2, table.findColumnIndex("NuMbEr"));
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertNotNull(table);
+ assertEquals("column header has special escaped characters",
+ 0, table.findColumnIndex("calc='#*'#"));
+ assertEquals(1, table.findColumnIndex("Name"));
+ assertEquals(2, table.findColumnIndex("Number"));
- // findColumnIndex should return -1 if no column header name matches
- assertEquals(-1, table.findColumnIndex(null));
- assertEquals(-1, table.findColumnIndex(""));
- assertEquals(-1, table.findColumnIndex("one"));
+ assertEquals("case insensitive", 2, table.findColumnIndex("NuMbEr"));
- wb.close();
+ // findColumnIndex should return -1 if no column header name matches
+ assertEquals(-1, table.findColumnIndex(null));
+ assertEquals(-1, table.findColumnIndex(""));
+ assertEquals(-1, table.findColumnIndex("one"));
+ }
}
@Test
public void findColumnIndexIsRelativeToTableNotSheet() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("DataTableCities.xlsx");
- XSSFTable table = wb.getTable("SmallCity");
-
- // Make sure that XSSFTable.findColumnIndex returns the column index relative to the first
- // column in the table, not the column number in the sheet
- assertEquals(0, table.findColumnIndex("City")); // column I in worksheet but 0th column in table
- assertEquals(1, table.findColumnIndex("Latitude"));
- assertEquals(2, table.findColumnIndex("Longitude"));
- assertEquals(3, table.findColumnIndex("Population"));
-
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("DataTableCities.xlsx")) {
+ XSSFTable table = wb.getTable("SmallCity");
+
+ // Make sure that XSSFTable.findColumnIndex returns the column index relative to the first
+ // column in the table, not the column number in the sheet
+ assertEquals(0, table.findColumnIndex("City")); // column I in worksheet but 0th column in table
+ assertEquals(1, table.findColumnIndex("Latitude"));
+ assertEquals(2, table.findColumnIndex("Longitude"));
+ assertEquals(3, table.findColumnIndex("Population"));
+ }
}
@Test
public void getSheetName() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals("Table", table.getSheetName());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals("Table", table.getSheetName());
+ }
}
@Test
public void isHasTotalsRow() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertFalse(table.getTotalsRowCount() > 0);
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertFalse(table.getTotalsRowCount() > 0);
+ }
}
@Test
public void getStartColIndex() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(0, table.getStartColIndex());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(0, table.getStartColIndex());
+ }
}
@Test
public void getEndColIndex() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(2, table.getEndColIndex());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(2, table.getEndColIndex());
+ }
}
@Test
public void getStartRowIndex() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(0, table.getStartRowIndex());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(0, table.getStartRowIndex());
+ }
}
@Test
public void getEndRowIndex() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(6, table.getEndRowIndex());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(6, table.getEndRowIndex());
+ }
}
@Test
public void getStartCellReference() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(new CellReference("A1"), table.getStartCellReference());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(new CellReference("A1"), table.getStartCellReference());
+ }
}
@Test
public void getEndCellReference() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(new CellReference("C7"), table.getEndCellReference());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(new CellReference("C7"), table.getEndCellReference());
+ }
}
@Test
public void getNumberOfMappedColumns() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(3, table.getNumberOfMappedColumns());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(3, table.getNumberOfMappedColumns());
+ }
}
@Test
public void getColumnCount() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals(3, table.getColumnCount());
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals(3, table.getColumnCount());
+ }
}
@Test
public void getAndSetDisplayName() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- XSSFTable table = wb.getTable("\\_Prime.1");
- assertEquals("\\_Prime.1", table.getDisplayName());
-
- table.setDisplayName(null);
- assertNull(table.getDisplayName());
- assertEquals("\\_Prime.1", table.getName()); // name and display name are different
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+ XSSFTable table = wb.getTable("\\_Prime.1");
+ assertEquals("\\_Prime.1", table.getDisplayName());
- table.setDisplayName("Display name");
- assertEquals("Display name", table.getDisplayName());
- assertEquals("\\_Prime.1", table.getName()); // name and display name are different
+ table.setDisplayName(null);
+ assertNull(table.getDisplayName());
+ assertEquals("\\_Prime.1", table.getName()); // name and display name are different
- wb.close();
+ table.setDisplayName("Display name");
+ assertEquals("Display name", table.getDisplayName());
+ assertEquals("\\_Prime.1", table.getName()); // name and display name are different
+ }
}
@Test
- public void getCellReferences() {
+ public void getCellReferences() throws IOException {
// make sure that cached start and end cell references
// can be synchronized with the underlying CTTable
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sh = wb.createSheet();
- XSSFTable table = sh.createTable();
- CTTable ctTable = table.getCTTable();
- ctTable.setRef("B2:E8");
-
- assertEquals(new CellReference("B2"), table.getStartCellReference());
- assertEquals(new CellReference("E8"), table.getEndCellReference());
-
- // At this point start and end cell reference are cached
- // and may not follow changes to the underlying CTTable
- ctTable.setRef("C1:M3");
-
- assertEquals(new CellReference("B2"), table.getStartCellReference());
- assertEquals(new CellReference("E8"), table.getEndCellReference());
-
- // Force a synchronization between CTTable and XSSFTable
- // start and end cell references
- table.updateReferences();
-
- assertEquals(new CellReference("C1"), table.getStartCellReference());
- assertEquals(new CellReference("M3"), table.getEndCellReference());
-
- IOUtils.closeQuietly(wb);
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sh = wb.createSheet();
+ XSSFTable table = sh.createTable();
+ CTTable ctTable = table.getCTTable();
+ ctTable.setRef("B2:E8");
+
+ assertEquals(new CellReference("B2"), table.getStartCellReference());
+ assertEquals(new CellReference("E8"), table.getEndCellReference());
+
+ // At this point start and end cell reference are cached
+ // and may not follow changes to the underlying CTTable
+ ctTable.setRef("C1:M3");
+
+ assertEquals(new CellReference("B2"), table.getStartCellReference());
+ assertEquals(new CellReference("E8"), table.getEndCellReference());
+
+ // Force a synchronization between CTTable and XSSFTable
+ // start and end cell references
+ table.updateReferences();
+
+ assertEquals(new CellReference("C1"), table.getStartCellReference());
+ assertEquals(new CellReference("M3"), table.getEndCellReference());
+
+ IOUtils.closeQuietly(wb);
+ }
}
@Test
- public void getRowCount() {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sh = wb.createSheet();
- XSSFTable table = sh.createTable();
- CTTable ctTable = table.getCTTable();
-
- assertEquals(0, table.getRowCount());
-
- ctTable.setRef("B2:B2");
- // update cell references to clear the cache
- table.updateReferences();
- assertEquals(1, table.getRowCount());
-
- ctTable.setRef("B2:B12");
- // update cell references to clear the cache
- table.updateReferences();
- assertEquals(11, table.getRowCount());
-
- IOUtils.closeQuietly(wb);
+ public void getRowCount() throws IOException {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sh = wb.createSheet();
+ XSSFTable table = sh.createTable();
+ CTTable ctTable = table.getCTTable();
+
+ assertEquals(0, table.getRowCount());
+
+ ctTable.setRef("B2:B2");
+ // update cell references to clear the cache
+ table.updateReferences();
+ assertEquals(1, table.getRowCount());
+
+ ctTable.setRef("B2:B12");
+ // update cell references to clear the cache
+ table.updateReferences();
+ assertEquals(11, table.getRowCount());
+
+ IOUtils.closeQuietly(wb);
+ }
}
@Test
- public void testGetDataRowCount() {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sh = wb.createSheet();
- AreaReference tableArea = new AreaReference("B2:B6", wb.getSpreadsheetVersion());
- XSSFTable table = sh.createTable(tableArea);
-
- assertEquals(5, table.getRowCount()); // includes column header
- assertEquals(4, table.getDataRowCount());
-
- table.setArea(new AreaReference("B2:B7", wb.getSpreadsheetVersion()));
-
- assertEquals(6, table.getRowCount());
- assertEquals(5, table.getDataRowCount());
-
- IOUtils.closeQuietly(wb);
+ public void testGetDataRowCount() throws IOException {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sh = wb.createSheet();
+ AreaReference tableArea = new AreaReference("B2:B6", wb.getSpreadsheetVersion());
+ XSSFTable table = sh.createTable(tableArea);
+
+ assertEquals(5, table.getRowCount()); // includes column header
+ assertEquals(4, table.getDataRowCount());
+
+ table.setArea(new AreaReference("B2:B7", wb.getSpreadsheetVersion()));
+
+ assertEquals(6, table.getRowCount());
+ assertEquals(5, table.getDataRowCount());
+
+ IOUtils.closeQuietly(wb);
+ }
}
@Test
public void testSetDataRowCount() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sh = wb.createSheet();
-
- // 1 header row + 1 data row
- AreaReference tableArea = new AreaReference("C10:C11", wb.getSpreadsheetVersion());
- XSSFTable table = sh.createTable(tableArea);
-
- assertEquals(2, table.getRowCount()); // includes all data and header/footer rows
-
- assertEquals(1, table.getHeaderRowCount());
- assertEquals(1, table.getDataRowCount());
- assertEquals(0, table.getTotalsRowCount());
-
- table.setDataRowCount(5);
-
- assertEquals(6, table.getRowCount());
-
- assertEquals(1, table.getHeaderRowCount());
- assertEquals(5, table.getDataRowCount());
- assertEquals(0, table.getTotalsRowCount());
-
- assertEquals("C10:C15", table.getArea().formatAsString());
-
-
- IOUtils.closeQuietly(wb);
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sh = wb.createSheet();
+
+ // 1 header row + 1 data row
+ AreaReference tableArea = new AreaReference("C10:C11", wb.getSpreadsheetVersion());
+ XSSFTable table = sh.createTable(tableArea);
+
+ assertEquals(2, table.getRowCount()); // includes all data and header/footer rows
+
+ assertEquals(1, table.getHeaderRowCount());
+ assertEquals(1, table.getDataRowCount());
+ assertEquals(0, table.getTotalsRowCount());
+
+ table.setDataRowCount(5);
+
+ assertEquals(6, table.getRowCount());
+
+ assertEquals(1, table.getHeaderRowCount());
+ assertEquals(5, table.getDataRowCount());
+ assertEquals(0, table.getTotalsRowCount());
+
+ assertEquals("C10:C15", table.getArea().formatAsString());
+
+ IOUtils.closeQuietly(wb);
+ }
}
@Test
@Test
public void testDifferentHeaderTypes() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TablesWithDifferentHeaders.xlsx");
- assertEquals(3, wb.getNumberOfSheets());
- XSSFSheet s;
- XSSFTable t;
-
- // TODO Nicer column fetching
-
- s = wb.getSheet("IntHeaders");
- assertEquals(1, s.getTables().size());
- t = s.getTables().get(0);
- assertEquals("A1:B2", t.getCellReferences().formatAsString());
- assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
- assertEquals("34", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
-
- s = wb.getSheet("FloatHeaders");
- assertEquals(1, s.getTables().size());
- t = s.getTables().get(0);
- assertEquals("A1:B2", t.getCellReferences().formatAsString());
- assertEquals("12.34", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
- assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
-
- s = wb.getSheet("NoExplicitHeaders");
- assertEquals(1, s.getTables().size());
- t = s.getTables().get(0);
- assertEquals("A1:B3", t.getCellReferences().formatAsString());
- assertEquals("Column1", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
- assertEquals("Column2", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TablesWithDifferentHeaders.xlsx")) {
+ assertEquals(3, wb.getNumberOfSheets());
+ XSSFSheet s;
+ XSSFTable t;
+
+ // TODO Nicer column fetching
+
+ s = wb.getSheet("IntHeaders");
+ assertEquals(1, s.getTables().size());
+ t = s.getTables().get(0);
+ assertEquals("A1:B2", t.getCellReferences().formatAsString());
+ assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
+ assertEquals("34", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
+
+ s = wb.getSheet("FloatHeaders");
+ assertEquals(1, s.getTables().size());
+ t = s.getTables().get(0);
+ assertEquals("A1:B2", t.getCellReferences().formatAsString());
+ assertEquals("12.34", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
+ assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
+
+ s = wb.getSheet("NoExplicitHeaders");
+ assertEquals(1, s.getTables().size());
+ t = s.getTables().get(0);
+ assertEquals("A1:B3", t.getCellReferences().formatAsString());
+ assertEquals("Column1", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
+ assertEquals("Column2", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
+ }
}
/**
*/
@Test
public void testNumericCellsInTable() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet s = wb.createSheet();
-
- // Create some cells, some numeric, some not
- Cell c1 = s.createRow(0).createCell(0);
- Cell c2 = s.getRow(0).createCell(1);
- Cell c3 = s.getRow(0).createCell(2);
- Cell c4 = s.createRow(1).createCell(0);
- Cell c5 = s.getRow(1).createCell(1);
- Cell c6 = s.getRow(1).createCell(2);
- c1.setCellValue(12);
- c2.setCellValue(34.56);
- c3.setCellValue("ABCD");
- c4.setCellValue("AB");
- c5.setCellValue("CD");
- c6.setCellValue("EF");
-
- // Setting up the table
- XSSFTable t = s.createTable(new AreaReference("A1:C3", wb.getSpreadsheetVersion()));
- t.setName("TableTest");
- t.setDisplayName("CT_Table_Test");
- t.createColumn("Column 1");
- t.createColumn("Column 2");
- t.createColumn("Column 3");
- t.setCellReferences(wb.getCreationHelper().createAreaReference(
- new CellReference(c1), new CellReference(c6)
- ));
-
- // Save and re-load
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb);
- IOUtils.closeQuietly(wb);
- s = wb2.getSheetAt(0);
-
- // Check
- assertEquals(1, s.getTables().size());
- t = s.getTables().get(0);
- assertEquals("A1", t.getStartCellReference().formatAsString());
- assertEquals("C2", t.getEndCellReference().formatAsString());
-
- // TODO Nicer column fetching
- assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
- assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
- assertEquals("ABCD", t.getCTTable().getTableColumns().getTableColumnArray(2).getName());
-
- // Done
- IOUtils.closeQuietly(wb2);
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet s = wb.createSheet();
+
+ // Create some cells, some numeric, some not
+ Cell c1 = s.createRow(0).createCell(0);
+ Cell c2 = s.getRow(0).createCell(1);
+ Cell c3 = s.getRow(0).createCell(2);
+ Cell c4 = s.createRow(1).createCell(0);
+ Cell c5 = s.getRow(1).createCell(1);
+ Cell c6 = s.getRow(1).createCell(2);
+ c1.setCellValue(12);
+ c2.setCellValue(34.56);
+ c3.setCellValue("ABCD");
+ c4.setCellValue("AB");
+ c5.setCellValue("CD");
+ c6.setCellValue("EF");
+
+ // Setting up the table
+ XSSFTable t = s.createTable(new AreaReference("A1:C3", wb.getSpreadsheetVersion()));
+ t.setName("TableTest");
+ t.setDisplayName("CT_Table_Test");
+ t.createColumn("Column 1");
+ t.createColumn("Column 2");
+ t.createColumn("Column 3");
+ t.setCellReferences(wb.getCreationHelper().createAreaReference(
+ new CellReference(c1), new CellReference(c6)
+ ));
+
+ // Save and re-load
+ XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb);
+ IOUtils.closeQuietly(wb);
+ s = wb2.getSheetAt(0);
+
+ // Check
+ assertEquals(1, s.getTables().size());
+ t = s.getTables().get(0);
+ assertEquals("A1", t.getStartCellReference().formatAsString());
+ assertEquals("C2", t.getEndCellReference().formatAsString());
+
+ // TODO Nicer column fetching
+ assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName());
+ assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName());
+ assertEquals("ABCD", t.getCTTable().getTableColumns().getTableColumnArray(2).getName());
+
+ // Done
+ IOUtils.closeQuietly(wb2);
+ }
}
}
package org.apache.poi.xssf.usermodel.charts;
+import java.io.IOException;
import java.util.List;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
axis = chart.createValueAxis(AxisPosition.BOTTOM);
}
- public void testLogBaseIllegalArgument() throws Exception {
+ public void testLogBaseIllegalArgument() {
IllegalArgumentException iae = null;
try {
axis.setLogBase(0.0);
assertNotNull(iae);
}
- public void testLogBaseLegalArgument() throws Exception {
+ public void testLogBaseLegalArgument() {
axis.setLogBase(Math.E);
assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON);
}
- public void testNumberFormat() throws Exception {
+ public void testNumberFormat() {
final String numberFormat = "General";
axis.setNumberFormat(numberFormat);
assertEquals(numberFormat, axis.getNumberFormat());
assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark());
}
- public void testGetChartAxisBug57362() {
+ public void testGetChartAxisBug57362() throws IOException {
//Load existing excel with some chart on it having primary and secondary axis.
- final XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx");
- final XSSFSheet sh = workbook.getSheetAt(0);
- final XSSFDrawing drawing = sh.createDrawingPatriarch();
- final XSSFChart chart = drawing.getCharts().get(0);
-
- final List<? extends XDDFChartAxis> axisList = chart.getAxes();
-
- assertEquals(4, axisList.size());
- assertNotNull(axisList.get(0));
- assertNotNull(axisList.get(1));
- assertNotNull(axisList.get(2));
- assertNotNull(axisList.get(3));
+ try (final XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx")) {
+ final XSSFSheet sh = workbook.getSheetAt(0);
+ final XSSFDrawing drawing = sh.createDrawingPatriarch();
+ final XSSFChart chart = drawing.getCharts().get(0);
+
+ final List<? extends XDDFChartAxis> axisList = chart.getAxes();
+
+ assertEquals(4, axisList.size());
+ assertNotNull(axisList.get(0));
+ assertNotNull(axisList.get(1));
+ assertNotNull(axisList.get(2));
+ assertNotNull(axisList.get(3));
+ }
}
}
XSSFCellFill cellFill = new XSSFCellFill(ctFill, null);
CTPatternFill ctPatternFill = ctFill.addNewPatternFill();
ctPatternFill.setPatternType(STPatternType.SOLID);
- assertEquals(FillPatternType.SOLID_FOREGROUND.ordinal(), cellFill.getPatternType().intValue()-1);
+ STPatternType.Enum patternType = cellFill.getPatternType();
+ assertNotNull(patternType);
+ assertEquals(FillPatternType.SOLID_FOREGROUND.ordinal(), patternType.intValue()-1);
}
@Test
XSSFCellFill cellFill = new XSSFCellFill(ctFill, null);
CTPatternFill ctPatternFill = ctFill.addNewPatternFill();
ctPatternFill.setPatternType(STPatternType.DARK_DOWN);
- assertEquals(8, cellFill.getPatternType().intValue());
+ STPatternType.Enum patternType = cellFill.getPatternType();
+ assertNotNull(patternType);
+ assertEquals(8, patternType.intValue());
}
@Test
public void testColorFromTheme() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx");
- XSSFCell cellWithThemeColor = wb.getSheetAt(0).getRow(10).getCell(0);
- //color RGB will be extracted from theme
- XSSFColor foregroundColor = cellWithThemeColor.getCellStyle().getFillForegroundXSSFColor();
- byte[] rgb = foregroundColor.getRGB();
- byte[] rgbWithTint = foregroundColor.getRGBWithTint();
- // Dk2
- assertEquals(rgb[0],31);
- assertEquals(rgb[1],73);
- assertEquals(rgb[2],125);
- // Dk2, lighter 40% (tint is about 0.39998)
- // 31 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 120.59552 => 120 (byte)
- // 73 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 145.79636 => -111 (byte)
- // 125 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 176.99740 => -80 (byte)
- assertEquals(rgbWithTint[0],120);
- assertEquals(rgbWithTint[1],-111);
- assertEquals(rgbWithTint[2],-80);
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) {
+ XSSFCell cellWithThemeColor = wb.getSheetAt(0).getRow(10).getCell(0);
+ //color RGB will be extracted from theme
+ XSSFColor foregroundColor = cellWithThemeColor.getCellStyle().getFillForegroundXSSFColor();
+ byte[] rgb = foregroundColor.getRGB();
+ byte[] rgbWithTint = foregroundColor.getRGBWithTint();
+ // Dk2
+ assertEquals(rgb[0], 31);
+ assertEquals(rgb[1], 73);
+ assertEquals(rgb[2], 125);
+ // Dk2, lighter 40% (tint is about 0.39998)
+ // 31 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 120.59552 => 120 (byte)
+ // 73 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 145.79636 => -111 (byte)
+ // 125 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 176.99740 => -80 (byte)
+ assertEquals(rgbWithTint[0], 120);
+ assertEquals(rgbWithTint[1], -111);
+ assertEquals(rgbWithTint[2], -80);
+ }
}
@Test
- public void testFillWithoutColors() {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("FillWithoutColor.xlsx");
- XSSFCell cellWithFill = wb.getSheetAt(0).getRow(5).getCell(1);
- XSSFCellStyle style = cellWithFill.getCellStyle();
- assertNotNull(style);
- assertNull("had an empty background color", style.getFillBackgroundColorColor());
- assertNull("had an empty background color", style.getFillBackgroundXSSFColor());
+ public void testFillWithoutColors() throws IOException {
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("FillWithoutColor.xlsx")) {
+ XSSFCell cellWithFill = wb.getSheetAt(0).getRow(5).getCell(1);
+ XSSFCellStyle style = cellWithFill.getCellStyle();
+ assertNotNull(style);
+ assertNull("had an empty background color", style.getFillBackgroundColorColor());
+ assertNull("had an empty background color", style.getFillBackgroundXSSFColor());
+ }
}
}
package org.apache.poi.xwpf;
-import java.io.IOException;
-
-import junit.framework.TestCase;
import org.apache.poi.ooxml.POIXMLProperties.CoreProperties;
import org.apache.poi.openxml4j.opc.PackageProperties;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.junit.Test;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorVariant;
+import java.io.IOException;
+
+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;
+
/**
* Tests if the {@link CoreProperties#getKeywords()} method. This test has been
* submitted because even though the
*
* @author Antoni Mylka
*/
-public final class TestAllExtendedProperties extends TestCase {
+public final class TestAllExtendedProperties {
+ @Test
public void testGetAllExtendedProperties() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");
- CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties();
- assertEquals("Microsoft Office Word", ctProps.getApplication());
- assertEquals("14.0000", ctProps.getAppVersion());
- assertEquals(57, ctProps.getCharacters());
- assertEquals(66, ctProps.getCharactersWithSpaces());
- assertEquals("", ctProps.getCompany());
- assertNull(ctProps.getDigSig());
- assertEquals(0, ctProps.getDocSecurity());
- assertNotNull(ctProps.getDomNode());
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx")) {
+ CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties();
+ assertEquals("Microsoft Office Word", ctProps.getApplication());
+ assertEquals("14.0000", ctProps.getAppVersion());
+ assertEquals(57, ctProps.getCharacters());
+ assertEquals(66, ctProps.getCharactersWithSpaces());
+ assertEquals("", ctProps.getCompany());
+ assertNull(ctProps.getDigSig());
+ assertEquals(0, ctProps.getDocSecurity());
+ assertNotNull(ctProps.getDomNode());
- CTVectorVariant vec = ctProps.getHeadingPairs();
- assertEquals(2, vec.getVector().sizeOfVariantArray());
- assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr());
- assertEquals(1, vec.getVector().getVariantArray(1).getI4());
+ CTVectorVariant vec = ctProps.getHeadingPairs();
+ assertEquals(2, vec.getVector().sizeOfVariantArray());
+ assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr());
+ assertEquals(1, vec.getVector().getVariantArray(1).getI4());
- assertFalse(ctProps.isSetHiddenSlides());
- assertEquals(0, ctProps.getHiddenSlides());
- assertFalse(ctProps.isSetHLinks());
- assertNull(ctProps.getHLinks());
- assertNull(ctProps.getHyperlinkBase());
- assertTrue(ctProps.isSetHyperlinksChanged());
- assertFalse(ctProps.getHyperlinksChanged());
- assertEquals(1, ctProps.getLines());
- assertTrue(ctProps.isSetLinksUpToDate());
- assertFalse(ctProps.getLinksUpToDate());
- assertNull(ctProps.getManager());
- assertFalse(ctProps.isSetMMClips());
- assertEquals(0, ctProps.getMMClips());
- assertFalse(ctProps.isSetNotes());
- assertEquals(0, ctProps.getNotes());
- assertEquals(1, ctProps.getPages());
- assertEquals(1, ctProps.getParagraphs());
- assertNull(ctProps.getPresentationFormat());
- assertTrue(ctProps.isSetScaleCrop());
- assertFalse(ctProps.getScaleCrop());
- assertTrue(ctProps.isSetSharedDoc());
- assertFalse(ctProps.getSharedDoc());
- assertFalse(ctProps.isSetSlides());
- assertEquals(0, ctProps.getSlides());
- assertEquals("Normal.dotm", ctProps.getTemplate());
+ assertFalse(ctProps.isSetHiddenSlides());
+ assertEquals(0, ctProps.getHiddenSlides());
+ assertFalse(ctProps.isSetHLinks());
+ assertNull(ctProps.getHLinks());
+ assertNull(ctProps.getHyperlinkBase());
+ assertTrue(ctProps.isSetHyperlinksChanged());
+ assertFalse(ctProps.getHyperlinksChanged());
+ assertEquals(1, ctProps.getLines());
+ assertTrue(ctProps.isSetLinksUpToDate());
+ assertFalse(ctProps.getLinksUpToDate());
+ assertNull(ctProps.getManager());
+ assertFalse(ctProps.isSetMMClips());
+ assertEquals(0, ctProps.getMMClips());
+ assertFalse(ctProps.isSetNotes());
+ assertEquals(0, ctProps.getNotes());
+ assertEquals(1, ctProps.getPages());
+ assertEquals(1, ctProps.getParagraphs());
+ assertNull(ctProps.getPresentationFormat());
+ assertTrue(ctProps.isSetScaleCrop());
+ assertFalse(ctProps.getScaleCrop());
+ assertTrue(ctProps.isSetSharedDoc());
+ assertFalse(ctProps.getSharedDoc());
+ assertFalse(ctProps.isSetSlides());
+ assertEquals(0, ctProps.getSlides());
+ assertEquals("Normal.dotm", ctProps.getTemplate());
- CTVectorLpstr vec2 = ctProps.getTitlesOfParts();
- assertEquals(1, vec2.getVector().sizeOfLpstrArray());
- assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0));
+ CTVectorLpstr vec2 = ctProps.getTitlesOfParts();
+ assertEquals(1, vec2.getVector().sizeOfLpstrArray());
+ assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0));
- assertEquals(3, ctProps.getTotalTime());
- assertEquals(10, ctProps.getWords());
+ assertEquals(3, ctProps.getTotalTime());
+ assertEquals(10, ctProps.getWords());
- // Check the digital signature part
- // Won't be there in this file, but we
- // need to do this check so that the
- // appropriate parts end up in the
- // smaller ooxml schemas file
- CTDigSigBlob blob = ctProps.getDigSig();
- assertNull(blob);
+ // Check the digital signature part
+ // Won't be there in this file, but we
+ // need to do this check so that the
+ // appropriate parts end up in the
+ // smaller ooxml schemas file
+ CTDigSigBlob blob = ctProps.getDigSig();
+ assertNull(blob);
- blob = CTDigSigBlob.Factory.newInstance();
- blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3});
+ blob = CTDigSigBlob.Factory.newInstance();
+ blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3});
+ }
}
}
*/
public final class TestPackageCorePropertiesGetKeywords extends TestCase {
public void testGetSetKeywords() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");
- String keywords = doc.getProperties().getCoreProperties().getKeywords();
- assertEquals("extractor, test, rdf", keywords);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx")) {
+ String keywords = doc.getProperties().getCoreProperties().getKeywords();
+ assertEquals("extractor, test, rdf", keywords);
- doc.getProperties().getCoreProperties().setKeywords("test, keywords");
- doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
- keywords = doc.getProperties().getCoreProperties().getKeywords();
- assertEquals("test, keywords", keywords);
+ doc.getProperties().getCoreProperties().setKeywords("test, keywords");
+ XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
+ keywords = docBack.getProperties().getCoreProperties().getKeywords();
+ assertEquals("test, keywords", keywords);
+ }
}
}
/**
* Get text out of the simple file
- *
- * @throws IOException
*/
public void testGetSimpleText() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertTrue(text.length() > 0);
+ String text = extractor.getText();
+ assertTrue(text.length() > 0);
- // Check contents
- assertStartsWith(text,
- "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc at risus vel erat tempus posuere. Aenean non ante. Suspendisse vehicula dolor sit amet odio."
- );
- assertEndsWith(text,
- "Phasellus ultricies mi nec leo. Sed tempus. In sit amet lorem at velit faucibus vestibulum.\n"
- );
+ // Check contents
+ assertStartsWith(text,
+ "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc at risus vel erat tempus posuere. Aenean non ante. Suspendisse vehicula dolor sit amet odio."
+ );
+ assertEndsWith(text,
+ "Phasellus ultricies mi nec leo. Sed tempus. In sit amet lorem at velit faucibus vestibulum.\n"
+ );
- // Check number of paragraphs by counting number of newlines
- int numberOfParagraphs = StringUtil.countMatches(text, '\n');
- assertEquals(3, numberOfParagraphs);
+ // Check number of paragraphs by counting number of newlines
+ int numberOfParagraphs = StringUtil.countMatches(text, '\n');
+ assertEquals(3, numberOfParagraphs);
- extractor.close();
+ extractor.close();
+ }
}
/**
* Tests getting the text out of a complex file
- *
- * @throws IOException
*/
public void testGetComplexText() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertTrue(text.length() > 0);
+ String text = extractor.getText();
+ assertTrue(text.length() > 0);
- char euro = '\u20ac';
+ char euro = '\u20ac';
// System.err.println("'"+text.substring(text.length() - 40) + "'");
- // Check contents
- assertStartsWith(text,
- " \n(V) ILLUSTRATIVE CASES\n\n"
- );
- assertContains(text,
- "As well as gaining " + euro + "90 from child benefit increases, he will also receive the early childhood supplement of " + euro + "250 per quarter for Vincent for the full four quarters of the year.\n\n\n\n"// \n\n\n"
- );
- assertEndsWith(text,
- "11.4%\t\t90\t\t\t\t\t250\t\t1,310\t\n\n \n\n\n"
- );
-
- // Check number of paragraphs by counting number of newlines
- int numberOfParagraphs = StringUtil.countMatches(text, '\n');
- assertEquals(134, numberOfParagraphs);
-
- extractor.close();
+ // Check contents
+ assertStartsWith(text,
+ " \n(V) ILLUSTRATIVE CASES\n\n"
+ );
+ assertContains(text,
+ "As well as gaining " + euro + "90 from child benefit increases, he will also receive the early childhood supplement of " + euro + "250 per quarter for Vincent for the full four quarters of the year.\n\n\n\n"// \n\n\n"
+ );
+ assertEndsWith(text,
+ "11.4%\t\t90\t\t\t\t\t250\t\t1,310\t\n\n \n\n\n"
+ );
+
+ // Check number of paragraphs by counting number of newlines
+ int numberOfParagraphs = StringUtil.countMatches(text, '\n');
+ assertEquals(134, numberOfParagraphs);
+
+ extractor.close();
+ }
}
public void testGetWithHyperlinks() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
-
- // Now check contents
- extractor.setFetchHyperlinks(false);
- assertEquals(
- "This is a test document.\nThis bit is in bold and italic\n" +
- "Back to normal\n" +
- "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
- "We have a hyperlink here, and another.\n",
- extractor.getText()
- );
-
- // One hyperlink is a real one, one is just to the top of page
- extractor.setFetchHyperlinks(true);
- assertEquals(
- "This is a test document.\nThis bit is in bold and italic\n" +
- "Back to normal\n" +
- "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
- "We have a hyperlink <http://poi.apache.org/> here, and another.\n",
- extractor.getText()
- );
-
- extractor.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+
+ // Now check contents
+ extractor.setFetchHyperlinks(false);
+ assertEquals(
+ "This is a test document.\nThis bit is in bold and italic\n" +
+ "Back to normal\n" +
+ "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
+ "We have a hyperlink here, and another.\n",
+ extractor.getText()
+ );
+
+ // One hyperlink is a real one, one is just to the top of page
+ extractor.setFetchHyperlinks(true);
+ assertEquals(
+ "This is a test document.\nThis bit is in bold and italic\n" +
+ "Back to normal\n" +
+ "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
+ "We have a hyperlink <http://poi.apache.org/> here, and another.\n",
+ extractor.getText()
+ );
+
+ extractor.close();
+ }
}
public void testHeadersFooters() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ThreeColHeadFoot.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
-
- assertEquals(
- "First header column!\tMid header\tRight header!\n" +
- "This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" +
- "\n" +
- "HEADING TEXT\n" +
- "\n" +
- "More on page one\n" +
- "\n\n" +
- "End of page 1\n\n\n" +
- "This is page two. It also has a three column heading, and a three column footer.\n" +
- "Footer Left\tFooter Middle\tFooter Right\n",
- extractor.getText()
- );
-
- // Now another file, expect multiple headers
- // and multiple footers
- doc = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
- extractor.close();
-
- extractor = new XWPFWordExtractor(doc);
- extractor.close();
-
- extractor =
- new XWPFWordExtractor(doc);
- extractor.getText();
-
- assertEquals(
- "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n" +
- "First header column!\tMid header\tRight header!\n" +
- "This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" +
- "\n" +
- "HEADING TEXT\n" +
- "\n" +
- "More on page one\n" +
- "\n\n" +
- "End of page 1\n\n\n" +
- "This is page two. It also has a three column heading, and a three column footer.\n" +
- "The footer of the first page\n" +
- "Footer Left\tFooter Middle\tFooter Right\n",
- extractor.getText()
- );
-
- extractor.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ThreeColHeadFoot.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+
+ assertEquals(
+ "First header column!\tMid header\tRight header!\n" +
+ "This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" +
+ "\n" +
+ "HEADING TEXT\n" +
+ "\n" +
+ "More on page one\n" +
+ "\n\n" +
+ "End of page 1\n\n\n" +
+ "This is page two. It also has a three column heading, and a three column footer.\n" +
+ "Footer Left\tFooter Middle\tFooter Right\n",
+ extractor.getText()
+ );
+
+ // Now another file, expect multiple headers
+ // and multiple footers
+ XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
+ extractor.close();
+
+ extractor = new XWPFWordExtractor(doc2);
+ extractor.close();
+
+ extractor =
+ new XWPFWordExtractor(doc2);
+ extractor.getText();
+
+ assertEquals(
+ "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n" +
+ "First header column!\tMid header\tRight header!\n" +
+ "This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" +
+ "\n" +
+ "HEADING TEXT\n" +
+ "\n" +
+ "More on page one\n" +
+ "\n\n" +
+ "End of page 1\n\n\n" +
+ "This is page two. It also has a three column heading, and a three column footer.\n" +
+ "The footer of the first page\n" +
+ "Footer Left\tFooter Middle\tFooter Right\n",
+ extractor.getText()
+ );
+
+ extractor.close();
+ }
}
public void testFootnotes() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("footnotes.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertContains(text,"snoska");
- assertContains(text,"Eto ochen prostoy[footnoteRef:1] text so snoskoy");
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("footnotes.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String text = extractor.getText();
+ assertContains(text, "snoska");
+ assertContains(text, "Eto ochen prostoy[footnoteRef:1] text so snoskoy");
- extractor.close();
+ extractor.close();
+ }
}
public void testTableFootnotes() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table_footnotes.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table_footnotes.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- assertContains(extractor.getText(),"snoska");
+ assertContains(extractor.getText(), "snoska");
- extractor.close();
+ extractor.close();
+ }
}
public void testFormFootnotes() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("form_footnotes.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("form_footnotes.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertContains(text,"testdoc");
- assertContains(text,"test phrase");
+ String text = extractor.getText();
+ assertContains(text, "testdoc");
+ assertContains(text, "test phrase");
- extractor.close();
+ extractor.close();
+ }
}
public void testEndnotes() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("endnotes.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertContains(text,"XXX");
- assertContains(text,"tilaka [endnoteRef:2]or 'tika'");
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("endnotes.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String text = extractor.getText();
+ assertContains(text, "XXX");
+ assertContains(text, "tilaka [endnoteRef:2]or 'tika'");
- extractor.close();
+ extractor.close();
+ }
}
public void testInsertedDeletedText() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("delins.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("delins.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- assertContains(extractor.getText(),"pendant worn");
- assertContains(extractor.getText(),"extremely well");
+ assertContains(extractor.getText(), "pendant worn");
+ assertContains(extractor.getText(), "extremely well");
- extractor.close();
+ extractor.close();
+ }
}
public void testParagraphHeader() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Headers.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Headers.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- assertContains(extractor.getText(),"Section 1");
- assertContains(extractor.getText(),"Section 2");
- assertContains(extractor.getText(),"Section 3");
+ assertContains(extractor.getText(), "Section 1");
+ assertContains(extractor.getText(), "Section 2");
+ assertContains(extractor.getText(), "Section 3");
- extractor.close();
+ extractor.close();
+ }
}
/**
* Test that we can open and process .docm
* (macro enabled) docx files (bug #45690)
- *
- * @throws IOException
*/
public void testDOCMFiles() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- assertContains(extractor.getText(),"2004");
- assertContains(extractor.getText(),"2008");
- assertContains(extractor.getText(),"(120 ");
+ assertContains(extractor.getText(), "2004");
+ assertContains(extractor.getText(), "2008");
+ assertContains(extractor.getText(), "(120 ");
- extractor.close();
+ extractor.close();
+ }
}
/**
* Test that we handle things like tabs and
* carriage returns properly in the text that
* we're extracting (bug #49189)
- *
- * @throws IOException
*/
public void testDocTabs() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- // Check bits
- assertContains(extractor.getText(),"a");
- assertContains(extractor.getText(),"\t");
- assertContains(extractor.getText(),"b");
+ // Check bits
+ assertContains(extractor.getText(), "a");
+ assertContains(extractor.getText(), "\t");
+ assertContains(extractor.getText(), "b");
- // Now check the first paragraph in total
- assertContains(extractor.getText(),"a\tb\n");
+ // Now check the first paragraph in total
+ assertContains(extractor.getText(), "a\tb\n");
- extractor.close();
+ extractor.close();
+ }
}
/**
* The output should not contain field codes, e.g. those specified in the
* w:instrText tag (spec sec. 17.16.23)
- *
- * @throws IOException
*/
public void testNoFieldCodes() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertTrue(text.length() > 0);
- assertFalse(text.contains("AUTHOR"));
- assertFalse(text.contains("CREATEDATE"));
-
- extractor.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String text = extractor.getText();
+ assertTrue(text.length() > 0);
+ assertFalse(text.contains("AUTHOR"));
+ assertFalse(text.contains("CREATEDATE"));
+
+ extractor.close();
+ }
}
/**
* The output should contain the values of simple fields, those specified
* with the fldSimple element (spec sec. 17.16.19)
- *
- * @throws IOException
*/
public void testFldSimpleContent() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertTrue(text.length() > 0);
- assertContains(text,"FldSimple.docx");
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String text = extractor.getText();
+ assertTrue(text.length() > 0);
+ assertContains(text, "FldSimple.docx");
- extractor.close();
+ extractor.close();
+ }
}
/**
* NoClassDefFoundError for CTAnchor in XWPFRun
*/
public void testDrawings() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("drawing.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String text = extractor.getText();
- assertTrue(text.length() > 0);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("drawing.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String text = extractor.getText();
+ assertTrue(text.length() > 0);
- extractor.close();
+ extractor.close();
+ }
}
/**
* Test for basic extraction of SDT content
- *
- * @throws IOException
*/
public void testSimpleControlContent() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
- String[] targs = new String[]{
- "header_rich_text",
- "rich_text",
- "rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table",
- "plain_text_no_newlines",
- "plain_text_with_newlines1\nplain_text_with_newlines2\n",
- "watermelon\n",
- "dirt\n",
- "4/16/2013\n",
- "rich_text_in_cell",
- "abc",
- "rich_text_in_paragraph_in_cell",
- "footer_rich_text",
- "footnote_sdt",
- "endnote_sdt"
- };
- XWPFWordExtractor ex = new XWPFWordExtractor(doc);
- String s = ex.getText().toLowerCase(Locale.ROOT);
- int hits = 0;
-
- for (String targ : targs) {
- boolean hit = false;
- if (s.contains(targ)) {
- hit = true;
- hits++;
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) {
+ String[] targs = new String[]{
+ "header_rich_text",
+ "rich_text",
+ "rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table",
+ "plain_text_no_newlines",
+ "plain_text_with_newlines1\nplain_text_with_newlines2\n",
+ "watermelon\n",
+ "dirt\n",
+ "4/16/2013\n",
+ "rich_text_in_cell",
+ "abc",
+ "rich_text_in_paragraph_in_cell",
+ "footer_rich_text",
+ "footnote_sdt",
+ "endnote_sdt"
+ };
+ XWPFWordExtractor ex = new XWPFWordExtractor(doc);
+ String s = ex.getText().toLowerCase(Locale.ROOT);
+ int hits = 0;
+
+ for (String targ : targs) {
+ boolean hit = false;
+ if (s.contains(targ)) {
+ hit = true;
+ hits++;
+ }
+ assertTrue("controlled content loading-" + targ, hit);
}
- assertEquals("controlled content loading-" + targ, true, hit);
- }
- assertEquals("controlled content loading hit count", targs.length, hits);
- ex.close();
-
-
- doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");
- targs = new String[]{
- "bb",
- "test subtitle\n",
- "test user\n",
- };
- ex = new XWPFWordExtractor(doc);
- s = ex.getText().toLowerCase(Locale.ROOT);
-
- //At one point in development there were three copies of the text.
- //This ensures that there is only one copy.
- for (String targ : targs) {
- Matcher m = Pattern.compile(targ).matcher(s);
+ assertEquals("controlled content loading hit count", targs.length, hits);
+ ex.close();
+
+
+ XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");
+ targs = new String[]{
+ "bb",
+ "test subtitle\n",
+ "test user\n",
+ };
+ ex = new XWPFWordExtractor(doc2);
+ s = ex.getText().toLowerCase(Locale.ROOT);
+
+ //At one point in development there were three copies of the text.
+ //This ensures that there is only one copy.
+ for (String targ : targs) {
+ Matcher m = Pattern.compile(targ).matcher(s);
+ int hit = 0;
+ while (m.find()) {
+ hit++;
+ }
+ assertEquals("controlled content loading-" + targ, 1, hit);
+ }
+ //"test\n" appears twice: once as the "title" and once in the text.
+ //This also happens when you save this document as text from MSWord.
+ Matcher m = Pattern.compile("test\n").matcher(s);
int hit = 0;
while (m.find()) {
hit++;
}
- assertEquals("controlled content loading-" + targ, 1, hit);
- }
- //"test\n" appears twice: once as the "title" and once in the text.
- //This also happens when you save this document as text from MSWord.
- Matcher m = Pattern.compile("test\n").matcher(s);
- int hit = 0;
- while (m.find()) {
- hit++;
+ assertEquals("test<N>", 2, hit);
+ ex.close();
}
- assertEquals("test<N>", 2, hit);
- ex.close();
}
/**
* No Header or Footer in document
*/
public void testBug55733() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- // Check it gives text without error
- extractor.getText();
- extractor.close();
+ // Check it gives text without error
+ extractor.getText();
+ extractor.close();
+ }
}
public void testCheckboxes() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
-
- assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" +
- "Or checked: |X|\n\n\n\n\n" +
- "Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
- "In Table:\n|_|\t|X|\n\n\n" +
- "In Sequence:\n|X||_||X|\n", extractor.getText());
- extractor.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+
+ assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" +
+ "Or checked: |X|\n\n\n\n\n" +
+ "Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
+ "In Table:\n|_|\t|X|\n\n\n" +
+ "In Sequence:\n|X||_||X|\n", extractor.getText());
+ extractor.close();
+ }
}
public void testMultipleBodyBug() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("MultipleBodyBug.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- assertEquals("START BODY 1 The quick, brown fox jumps over a lazy dog. END BODY 1.\n"
- + "START BODY 2 The quick, brown fox jumps over a lazy dog. END BODY 2.\n"
- + "START BODY 3 The quick, brown fox jumps over a lazy dog. END BODY 3.\n",
- extractor.getText());
- extractor.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("MultipleBodyBug.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ assertEquals("START BODY 1 The quick, brown fox jumps over a lazy dog. END BODY 1.\n"
+ + "START BODY 2 The quick, brown fox jumps over a lazy dog. END BODY 2.\n"
+ + "START BODY 3 The quick, brown fox jumps over a lazy dog. END BODY 3.\n",
+ extractor.getText());
+ extractor.close();
+ }
}
public void testPhonetic() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61470.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- //expect: baseText (phoneticText)
- assertEquals("\u6771\u4EAC (\u3068\u3046\u304D\u3087\u3046)", extractor.getText().trim());
- extractor.close();
- extractor = new XWPFWordExtractor(doc);
- extractor.setConcatenatePhoneticRuns(false);
- assertEquals("\u6771\u4EAC", extractor.getText().trim());
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61470.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ //expect: baseText (phoneticText)
+ assertEquals("\u6771\u4EAC (\u3068\u3046\u304D\u3087\u3046)", extractor.getText().trim());
+ extractor.close();
+ extractor = new XWPFWordExtractor(doc);
+ extractor.setConcatenatePhoneticRuns(false);
+ assertEquals("\u6771\u4EAC", extractor.getText().trim());
+ }
}
public void testCTPictureBase() throws IOException {
//This forces ctpicturebase to be included in the poi-ooxml-schemas jar
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61991.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String txt = extractor.getText();
- assertContains(txt, "Sequencing data");
- extractor.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61991.docx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String txt = extractor.getText();
+ assertContains(txt, "Sequencing data");
+ extractor.close();
+ }
}
public void testGlossary() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316.dotx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String txt = extractor.getText();
- assertContains(txt, "Getting the perfect");
- //this content appears only in the glossary document
- //once we add processing for this, we can change this to contains
- assertNotContained(txt, "table rows");
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316.dotx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String txt = extractor.getText();
+ assertContains(txt, "Getting the perfect");
+ //this content appears only in the glossary document
+ //once we add processing for this, we can change this to contains
+ assertNotContained(txt, "table rows");
+ }
}
public void testPartsInTemplate() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316b.dotx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
- String txt = extractor.getText();
- assertContains(txt, "header 2");
- assertContains(txt, "footer 1");
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316b.dotx")) {
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ String txt = extractor.getText();
+ assertContains(txt, "header 2");
+ assertContains(txt, "footer 1");
+ }
}
}
import java.io.IOException;
-import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/**
* Tests for the various XWPF decorators
*/
-public class TestXWPFDecorators extends TestCase {
+public class TestXWPFDecorators {
private XWPFDocument simple;
private XWPFDocument hyperlink;
private XWPFDocument comments;
- @Override
- protected void setUp() throws IOException {
+ @Before
+ public void setUp() throws IOException {
simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx");
}
+ @After
+ public void tearDown() throws IOException {
+ simple.close();
+ hyperlink.close();
+ comments.close();
+ }
+
+ @Test
public void testHyperlink() {
XWPFParagraph ps;
XWPFParagraph ph;
assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL());
}
+ @Test
public void testComments() {
int numComments = 0;
for (XWPFParagraph p : comments.getParagraphs()) {
"\nK\u0131rm\u0131z\u0131 don,\n" +
"\ngel bizim bah\u00e7eye kon,\n" +
"\nsar\u0131 limon";
- XWPFDocument doc = new XWPFDocument();
- XWPFRun run = doc.createParagraph().createRun();
+ try (XWPFDocument doc = new XWPFDocument()) {
+ XWPFRun run = doc.createParagraph().createRun();
- for (String str : blabla.split("\n")) {
- run.setText(str);
- run.addBreak();
- }
+ for (String str : blabla.split("\n")) {
+ run.setText(str);
+ run.addBreak();
+ }
- run.setFontFamily("Times New Roman");
- run.setFontSize(20);
- assertEquals(run.getFontFamily(), "Times New Roman");
- assertEquals(run.getFontFamily(FontCharRange.cs), "Times New Roman");
- assertEquals(run.getFontFamily(FontCharRange.eastAsia), "Times New Roman");
- assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Times New Roman");
- run.setFontFamily("Arial", FontCharRange.hAnsi);
- assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial");
-
- doc.close();
+ run.setFontFamily("Times New Roman");
+ run.setFontSize(20);
+ assertEquals(run.getFontFamily(), "Times New Roman");
+ assertEquals(run.getFontFamily(FontCharRange.cs), "Times New Roman");
+ assertEquals(run.getFontFamily(FontCharRange.eastAsia), "Times New Roman");
+ assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Times New Roman");
+ run.setFontFamily("Arial", FontCharRange.hAnsi);
+ assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial");
+ }
}
@Test
public void bug57312_NullPointException() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx");
- assertNotNull(doc);
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx")) {
+ assertNotNull(doc);
- for (IBodyElement bodyElement : doc.getBodyElements()) {
- BodyElementType elementType = bodyElement.getElementType();
+ for (IBodyElement bodyElement : doc.getBodyElements()) {
+ BodyElementType elementType = bodyElement.getElementType();
- if (elementType == BodyElementType.PARAGRAPH) {
- XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
+ if (elementType == BodyElementType.PARAGRAPH) {
+ XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
- for (IRunElement iRunElem : paragraph.getIRuns()) {
+ for (IRunElement iRunElem : paragraph.getIRuns()) {
- if (iRunElem instanceof XWPFRun) {
- XWPFRun runElement = (XWPFRun) iRunElem;
+ if (iRunElem instanceof XWPFRun) {
+ XWPFRun runElement = (XWPFRun) iRunElem;
- UnderlinePatterns underline = runElement.getUnderline();
- assertNotNull(underline);
+ UnderlinePatterns underline = runElement.getUnderline();
+ assertNotNull(underline);
- //System.out.println("Found: " + underline + ": " + runElement.getText(0));
+ //System.out.println("Found: " + underline + ": " + runElement.getText(0));
+ }
}
}
}
}
- doc.close();
}
@Test
public void bug57495_getTableArrayInDoc() throws IOException {
- XWPFDocument doc =new XWPFDocument();
- //let's create a few tables for the test
- for(int i=0;i<3;i++) {
- doc.createTable(2, 2);
+ try (XWPFDocument doc = new XWPFDocument()) {
+ //let's create a few tables for the test
+ for (int i = 0; i < 3; i++) {
+ doc.createTable(2, 2);
+ }
+ XWPFTable table = doc.getTableArray(0);
+ assertNotNull(table);
+ //let's check also that returns the correct table
+ XWPFTable same = doc.getTables().get(0);
+ assertEquals(table, same);
}
- XWPFTable table = doc.getTableArray(0);
- assertNotNull(table);
- //let's check also that returns the correct table
- XWPFTable same = doc.getTables().get(0);
- assertEquals(table, same);
- doc.close();
}
@Test
public void bug57495_getParagraphArrayInTableCell() throws IOException {
- XWPFDocument doc =new XWPFDocument();
- //let's create a table for the test
- XWPFTable table = doc.createTable(2, 2);
- assertNotNull(table);
- XWPFParagraph p = table.getRow(0).getCell(0).getParagraphArray(0);
- assertNotNull(p);
- //let's check also that returns the correct paragraph
- XWPFParagraph same = table.getRow(0).getCell(0).getParagraphs().get(0);
- assertEquals(p, same);
- doc.close();
+ try (XWPFDocument doc = new XWPFDocument()) {
+ //let's create a table for the test
+ XWPFTable table = doc.createTable(2, 2);
+ assertNotNull(table);
+ XWPFParagraph p = table.getRow(0).getCell(0).getParagraphArray(0);
+ assertNotNull(p);
+ //let's check also that returns the correct paragraph
+ XWPFParagraph same = table.getRow(0).getCell(0).getParagraphs().get(0);
+ assertEquals(p, same);
+ }
}
@Test
@Test
public void test56392() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx");
- assertNotNull(doc);
- doc.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx")) {
+ assertNotNull(doc);
+ }
}
/**
*/
@Test
public void test57829() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
- assertNotNull(doc);
- assertEquals(3, doc.getParagraphs().size());
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) {
+ assertNotNull(doc);
+ assertEquals(3, doc.getParagraphs().size());
- for (XWPFParagraph paragraph : doc.getParagraphs()) {
- paragraph.removeRun(0);
- assertNotNull(paragraph.getText());
+ for (XWPFParagraph paragraph : doc.getParagraphs()) {
+ paragraph.removeRun(0);
+ assertNotNull(paragraph.getText());
+ }
}
- doc.close();
}
/**
*/
@Test
public void test58618() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58618.docx");
- XWPFParagraph para = (XWPFParagraph)doc.getBodyElements().get(0);
- assertNotNull(para);
- assertEquals("Some text some hyper links link link and some text.....", para.getText());
- XWPFRun run = para.insertNewRun(para.getRuns().size());
- run.setText("New Text");
- assertEquals("Some text some hyper links link link and some text.....New Text", para.getText());
- para.removeRun(para.getRuns().size() -2);
- assertEquals("Some text some hyper links link linkNew Text", para.getText());
- doc.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58618.docx")) {
+ XWPFParagraph para = (XWPFParagraph) doc.getBodyElements().get(0);
+ assertNotNull(para);
+ assertEquals("Some text some hyper links link link and some text.....", para.getText());
+ XWPFRun run = para.insertNewRun(para.getRuns().size());
+ run.setText("New Text");
+ assertEquals("Some text some hyper links link link and some text.....New Text", para.getText());
+ para.removeRun(para.getRuns().size() - 2);
+ assertEquals("Some text some hyper links link linkNew Text", para.getText());
+ }
}
@Test
public void test59378() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("59378.docx");
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- doc.write(out);
- out.close();
+ try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("59378.docx")) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.write(out);
+ out.close();
- XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()));
- doc2.close();
+ XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()));
+ doc2.close();
- XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
- docBack.close();
+ XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
+ docBack.close();
+ }
}
}