Close file-resources in unit-tests, fix IDE warnings

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1865208 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2019-08-15 07:54:58 +00:00
parent 0619e7ebfb
commit ba66108653
15 changed files with 1819 additions and 1736 deletions

View File

@ -18,9 +18,13 @@
package org.apache.poi.xssf.model;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
@ -70,7 +74,9 @@ public class TestThemesTable {
XSSFWorkbook simpleRS = XSSFTestDataSamples.writeOutAndReadBack(simple);
XSSFWorkbook complexRS = XSSFTestDataSamples.writeOutAndReadBack(complex);
// Fetch fresh copies to test with
simple.close();
simple = XSSFTestDataSamples.openSampleWorkbook(testFileSimple);
complex.close();
complex = XSSFTestDataSamples.openSampleWorkbook(testFileComplex);
// Files and descriptions
Map<String,XSSFWorkbook> workbooks = new LinkedHashMap<>();
@ -111,13 +117,13 @@ public class TestThemesTable {
XSSFFont font = cell.getCellStyle().getFont();
CTColor ctColor = font.getCTFont().getColorArray(0);
assertNotNull(ctColor);
assertEquals(true, ctColor.isSetTheme());
assertTrue(ctColor.isSetTheme());
assertEquals(themeElem.idx, ctColor.getTheme());
// Get the colour, via the theme
XSSFColor color = font.getXSSFColor();
// Theme colours aren't tinted
assertEquals(false, color.hasTint());
assertFalse(color.hasTint());
// Check the RGB part (no tint)
assertEquals(
"Wrong theme colour " + themeElem.name + " on " + whatWorkbook,
@ -141,6 +147,11 @@ public class TestThemesTable {
fos.close();
}
}
simpleRS.close();
simple.close();
complexRS.close();
complex.close();
}
/**
@ -155,80 +166,78 @@ public class TestThemesTable {
* Note - Grey Row has an odd way of doing the styling...
*/
@Test
public void themedAndNonThemedColours() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFileComplex);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFCellStyle style;
XSSFColor color;
XSSFCell cell;
String[] names = {"White","Black","Grey","Dark Blue","Blue","Red","Green"};
String[] explicitFHexes = { "FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060",
"FF0070C0", "FFFF0000", "FF00B050" };
String[] explicitBHexes = { "FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060",
"FF0000FF", "FFFF0000", "FF00FF00" };
assertEquals(7, names.length);
// Check the non-CF colours in Columns A, B, C and E
for (int rn=1; rn<8; rn++) {
int idx = rn-1;
XSSFRow row = sheet.getRow(rn);
assertNotNull("Missing row " + rn, row);
// Theme cells come first
XSSFCell themeCell = row.getCell(0);
ThemeElement themeElem = ThemeElement.byId(idx);
assertCellContents(themeElem.name, themeCell);
public void themedAndNonThemedColours() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFileComplex)) {
XSSFSheet sheet = wb.getSheetAt(0);
// Sanity check names
assertCellContents(names[idx], row.getCell(1));
assertCellContents(names[idx], row.getCell(2));
assertCellContents(names[idx], row.getCell(4));
// Check the colours
// A: Theme Based, Foreground
style = themeCell.getCellStyle();
color = style.getFont().getXSSFColor();
assertEquals(true, color.isThemed());
assertEquals(idx, color.getTheme());
assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB()));
// B: Theme Based, Foreground
cell = row.getCell(1);
style = cell.getCellStyle();
color = style.getFont().getXSSFColor();
assertEquals(true, color.isThemed());
if (idx != 2) {
String[] names = {"White", "Black", "Grey", "Dark Blue", "Blue", "Red", "Green"};
String[] explicitFHexes = {"FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060",
"FF0070C0", "FFFF0000", "FF00B050"};
String[] explicitBHexes = {"FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060",
"FF0000FF", "FFFF0000", "FF00FF00"};
assertEquals(7, names.length);
// Check the non-CF colours in Columns A, B, C and E
for (int rn = 1; rn < 8; rn++) {
int idx = rn - 1;
XSSFRow row = sheet.getRow(rn);
assertNotNull("Missing row " + rn, row);
// Theme cells come first
XSSFCell themeCell = row.getCell(0);
ThemeElement themeElem = ThemeElement.byId(idx);
assertCellContents(themeElem.name, themeCell);
// Sanity check names
assertCellContents(names[idx], row.getCell(1));
assertCellContents(names[idx], row.getCell(2));
assertCellContents(names[idx], row.getCell(4));
// Check the colours
// A: Theme Based, Foreground
XSSFCellStyle style = themeCell.getCellStyle();
XSSFColor color = style.getFont().getXSSFColor();
assertTrue(color.isThemed());
assertEquals(idx, color.getTheme());
assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB()));
} else {
assertEquals(1, color.getTheme());
assertEquals(0.50, color.getTint(), 0.001);
// B: Theme Based, Foreground
XSSFCell cell = row.getCell(1);
style = cell.getCellStyle();
color = style.getFont().getXSSFColor();
assertTrue(color.isThemed());
if (idx != 2) {
assertEquals(idx, color.getTheme());
assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB()));
} else {
assertEquals(1, color.getTheme());
assertEquals(0.50, color.getTint(), 0.001);
}
// C: Explicit, Foreground
cell = row.getCell(2);
style = cell.getCellStyle();
color = style.getFont().getXSSFColor();
assertFalse(color.isThemed());
assertEquals(explicitFHexes[idx], color.getARGBHex());
// E: Explicit Background, Foreground all Black
cell = row.getCell(4);
style = cell.getCellStyle();
color = style.getFont().getXSSFColor();
assertTrue(color.isThemed());
assertEquals("FF000000", color.getARGBHex());
color = style.getFillForegroundXSSFColor();
assertFalse(color.isThemed());
assertEquals(explicitBHexes[idx], color.getARGBHex());
color = style.getFillBackgroundColorColor();
assertFalse(color.isThemed());
assertNull(color.getARGBHex());
}
// C: Explicit, Foreground
cell = row.getCell(2);
style = cell.getCellStyle();
color = style.getFont().getXSSFColor();
assertEquals(false, color.isThemed());
assertEquals(explicitFHexes[idx], color.getARGBHex());
// E: Explicit Background, Foreground all Black
cell = row.getCell(4);
style = cell.getCellStyle();
color = style.getFont().getXSSFColor();
assertEquals(true, color.isThemed());
assertEquals("FF000000", color.getARGBHex());
color = style.getFillForegroundXSSFColor();
assertEquals(false, color.isThemed());
assertEquals(explicitBHexes[idx], color.getARGBHex());
color = style.getFillBackgroundColorColor();
assertEquals(false, color.isThemed());
assertEquals(null, color.getARGBHex());
}
// Check the CF colours
@ -242,13 +251,13 @@ public class TestThemesTable {
@Test
@SuppressWarnings("resource")
public void testAddNew() throws Exception {
public void testAddNew() {
XSSFWorkbook wb = new XSSFWorkbook();
wb.createSheet();
assertEquals(null, wb.getTheme());
assertNull(wb.getTheme());
StylesTable styles = wb.getStylesSource();
assertEquals(null, styles.getTheme());
assertNull(styles.getTheme());
styles.ensureThemesTable();

View File

@ -19,14 +19,31 @@ package org.apache.poi.xssf.streaming;
import org.apache.poi.ss.formula.EvaluationSheet;
import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.After;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TestSXSSFEvaluationSheet extends BaseTestXEvaluationSheet {
private List<Workbook> workbooksToClose = new ArrayList<>();
@After
public void closeWorkbooks() throws IOException {
for (Workbook workbook : workbooksToClose) {
workbook.close();
}
}
@Override
protected Map.Entry<Sheet, EvaluationSheet> getInstance() {
SXSSFSheet sheet = new SXSSFWorkbook().createSheet();
SXSSFWorkbook workbook = new SXSSFWorkbook();
workbooksToClose.add(workbook);
SXSSFSheet sheet = workbook.createSheet();
return new AbstractMap.SimpleEntry<>(sheet, new SXSSFEvaluationSheet(sheet));
}
}

View File

@ -20,6 +20,9 @@ package org.apache.poi.xssf.usermodel;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ss.formula.TestMissingWorkbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Before;
import static org.junit.Assert.assertNotNull;
/**
* XSSF Specific version of the Missing Workbooks test
@ -28,12 +31,13 @@ public final class TestMissingWorkbookOnXSSF extends TestMissingWorkbook {
public TestMissingWorkbookOnXSSF() {
super("52575_main.xlsx", "source_dummy.xlsx", "52575_source.xls");
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() {
mainWorkbook = XSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME);
sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME);
assertNotNull(mainWorkbook);
assertNotNull(sourceWorkbook);
}

View File

@ -21,62 +21,70 @@ import org.apache.poi.xssf.XSSFTestDataSamples;
import junit.framework.TestCase;
import java.io.IOException;
public final class TestXSSFChart extends TestCase {
public void testGetAccessors() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx");
XSSFSheet s1 = wb.getSheetAt(0);
XSSFSheet s2 = wb.getSheetAt(1);
XSSFSheet s3 = wb.getSheetAt(2);
public void testGetAccessors() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) {
XSSFSheet s1 = wb.getSheetAt(0);
XSSFSheet s2 = wb.getSheetAt(1);
XSSFSheet s3 = wb.getSheetAt(2);
assertEquals(0, s1.getRelations().size());
assertEquals(1, s2.getRelations().size());
assertEquals(1, s3.getRelations().size());
assertEquals(0, s1.getRelations().size());
assertEquals(1, s2.getRelations().size());
assertEquals(1, s3.getRelations().size());
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
}
}
public void testGetCharts() throws Exception {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx");
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) {
XSSFSheet s1 = wb.getSheetAt(0);
XSSFSheet s2 = wb.getSheetAt(1);
XSSFSheet s3 = wb.getSheetAt(2);
XSSFSheet s1 = wb.getSheetAt(0);
XSSFSheet s2 = wb.getSheetAt(1);
XSSFSheet s3 = wb.getSheetAt(2);
assertEquals(0, s1.createDrawingPatriarch().getCharts().size());
assertEquals(2, s2.createDrawingPatriarch().getCharts().size());
assertEquals(1, s3.createDrawingPatriarch().getCharts().size());
assertEquals(0, s1.createDrawingPatriarch().getCharts().size());
assertEquals(2, s2.createDrawingPatriarch().getCharts().size());
assertEquals(1, s3.createDrawingPatriarch().getCharts().size());
// Check the titles
XSSFChart chart = s2.createDrawingPatriarch().getCharts().get(0);
assertNull(chart.getTitleText());
// Check the titles
XSSFChart chart = s2.createDrawingPatriarch().getCharts().get(0);
assertEquals(null, chart.getTitleText());
chart = s2.createDrawingPatriarch().getCharts().get(1);
XSSFRichTextString title = chart.getTitleText();
assertNotNull(title);
assertEquals("Pie Chart Title Thingy", title.getString());
chart = s2.createDrawingPatriarch().getCharts().get(1);
assertEquals("Pie Chart Title Thingy", chart.getTitleText().getString());
chart = s3.createDrawingPatriarch().getCharts().get(0);
title = chart.getTitleText();
assertNotNull(title);
assertEquals("Sheet 3 Chart with Title", title.getString());
chart = s3.createDrawingPatriarch().getCharts().get(0);
assertEquals("Sheet 3 Chart with Title", chart.getTitleText().getString());
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
}
}
public void testAddChartsToNewWorkbook() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet s1 = wb.createSheet();
XSSFDrawing d1 = s1.createDrawingPatriarch();
XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart c1 = d1.createChart(a1);
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet s1 = wb.createSheet();
XSSFDrawing d1 = s1.createDrawingPatriarch();
XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30);
XSSFChart c1 = d1.createChart(a1);
assertEquals(1, d1.getCharts().size());
assertEquals(1, d1.getCharts().size());
assertNotNull(c1.getGraphicFrame());
assertNotNull(c1.getOrAddLegend());
assertNotNull(c1.getGraphicFrame());
assertNotNull(c1.getOrAddLegend());
XSSFClientAnchor a2 = new XSSFClientAnchor(0, 0, 0, 0, 1, 11, 10, 60);
XSSFChart c2 = d1.createChart(a2);
assertNotNull(c2);
assertEquals(2, d1.getCharts().size());
XSSFClientAnchor a2 = new XSSFClientAnchor(0, 0, 0, 0, 1, 11, 10, 60);
XSSFChart c2 = d1.createChart(a2);
assertNotNull(c2);
assertEquals(2, d1.getCharts().size());
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb));
}
}
}

View File

@ -22,60 +22,65 @@ import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTChartsheet;
import java.io.IOException;
import static org.junit.Assert.*;
public final class TestXSSFChartSheet {
@Test
public void testXSSFFactory() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx");
assertEquals(4, wb.getNumberOfSheets());
public void testXSSFFactory() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) {
assertEquals(4, wb.getNumberOfSheets());
//the third sheet is of type 'chartsheet'
assertEquals("Chart1", wb.getSheetName(2));
assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet);
assertEquals("Chart1", wb.getSheetAt(2).getSheetName());
//the third sheet is of type 'chartsheet'
assertEquals("Chart1", wb.getSheetName(2));
assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet);
assertEquals("Chart1", wb.getSheetAt(2).getSheetName());
final CTChartsheet ctChartsheet = ((XSSFChartSheet) wb.getSheetAt(2)).getCTChartsheet();
assertNotNull(ctChartsheet);
final CTChartsheet ctChartsheet = ((XSSFChartSheet) wb.getSheetAt(2)).getCTChartsheet();
assertNotNull(ctChartsheet);
}
}
@Test
public void testGetAccessors() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx");
XSSFChartSheet sheet = (XSSFChartSheet)wb.getSheetAt(2);
public void testGetAccessors() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) {
XSSFChartSheet sheet = (XSSFChartSheet) wb.getSheetAt(2);
assertFalse("Row iterator for charts sheets should return zero rows",
sheet.iterator().hasNext());
assertFalse("Row iterator for charts sheets should return zero rows",
sheet.iterator().hasNext());
//access to a arbitrary row
assertNull(sheet.getRow(1));
//access to a arbitrary row
assertNull(sheet.getRow(1));
//some basic get* accessors
assertEquals(0, sheet.getNumberOfComments());
assertEquals(0, sheet.getNumHyperlinks());
assertEquals(0, sheet.getNumMergedRegions());
assertNull(sheet.getActiveCell());
assertTrue(sheet.getAutobreaks());
assertNull(sheet.getCellComment(new CellAddress(0, 0)));
assertEquals(0, sheet.getColumnBreaks().length);
assertTrue(sheet.getRowSumsBelow());
assertNotNull(sheet.createDrawingPatriarch());
assertNotNull(sheet.getDrawingPatriarch());
assertNotNull(sheet.getCTChartsheet());
//some basic get* accessors
assertEquals(0, sheet.getNumberOfComments());
assertEquals(0, sheet.getNumHyperlinks());
assertEquals(0, sheet.getNumMergedRegions());
assertNull(sheet.getActiveCell());
assertTrue(sheet.getAutobreaks());
assertNull(sheet.getCellComment(new CellAddress(0, 0)));
assertEquals(0, sheet.getColumnBreaks().length);
assertTrue(sheet.getRowSumsBelow());
assertNotNull(sheet.createDrawingPatriarch());
assertNotNull(sheet.getDrawingPatriarch());
assertNotNull(sheet.getCTChartsheet());
}
}
@Test
public void testGetCharts() throws Exception {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx");
XSSFSheet ns = wb.getSheetAt(0);
XSSFChartSheet cs = (XSSFChartSheet)wb.getSheetAt(2);
assertEquals(0, ns.createDrawingPatriarch().getCharts().size());
assertEquals(1, cs.createDrawingPatriarch().getCharts().size());
XSSFChart chart = cs.createDrawingPatriarch().getCharts().get(0);
assertNull(chart.getTitleText());
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) {
XSSFSheet ns = wb.getSheetAt(0);
XSSFChartSheet cs = (XSSFChartSheet) wb.getSheetAt(2);
assertEquals(0, ns.createDrawingPatriarch().getCharts().size());
assertEquals(1, cs.createDrawingPatriarch().getCharts().size());
XSSFChart chart = cs.createDrawingPatriarch().getCharts().get(0);
assertNull(chart.getTitleText());
}
}
}

View File

@ -19,6 +19,7 @@ package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
@ -32,173 +33,169 @@ public final class TestXSSFColor {
@Test
public void testIndexedColour() throws Exception {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx");
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) {
// Check the CTColor is as expected
XSSFColor indexed = wb.getCellStyleAt(1).getFillBackgroundXSSFColor();
assertTrue(indexed.getCTColor().isSetIndexed());
assertEquals(64, indexed.getCTColor().getIndexed());
assertFalse(indexed.getCTColor().isSetRgb());
assertNull(indexed.getCTColor().getRgb());
// Check the CTColor is as expected
XSSFColor indexed = wb.getCellStyleAt(1).getFillBackgroundXSSFColor();
assertEquals(true, indexed.getCTColor().isSetIndexed());
assertEquals(64, indexed.getCTColor().getIndexed());
assertEquals(false, indexed.getCTColor().isSetRgb());
assertEquals(null, indexed.getCTColor().getRgb());
// Now check the XSSFColor
// Note - 64 is a special "auto" one with no rgb equiv
assertEquals(64, indexed.getIndexed());
assertNull(indexed.getRGB());
assertNull(indexed.getRGBWithTint());
assertNull(indexed.getARGBHex());
assertFalse(indexed.hasAlpha());
assertFalse(indexed.hasTint());
// Now check the XSSFColor
// Note - 64 is a special "auto" one with no rgb equiv
assertEquals(64, indexed.getIndexed());
assertEquals(null, indexed.getRGB());
assertEquals(null, indexed.getRGBWithTint());
assertEquals(null, indexed.getARGBHex());
assertFalse(indexed.hasAlpha());
assertFalse(indexed.hasTint());
// Now move to one with indexed rgb values
indexed.setIndexed(59);
assertTrue(indexed.getCTColor().isSetIndexed());
assertEquals(59, indexed.getCTColor().getIndexed());
assertFalse(indexed.getCTColor().isSetRgb());
assertNull(indexed.getCTColor().getRgb());
// Now move to one with indexed rgb values
indexed.setIndexed(59);
assertEquals(true, indexed.getCTColor().isSetIndexed());
assertEquals(59, indexed.getCTColor().getIndexed());
assertEquals(false, indexed.getCTColor().isSetRgb());
assertEquals(null, indexed.getCTColor().getRgb());
assertEquals(59, indexed.getIndexed());
assertEquals("FF333300", indexed.getARGBHex());
assertEquals(59, indexed.getIndexed());
assertEquals("FF333300", indexed.getARGBHex());
assertEquals(3, indexed.getRGB().length);
assertEquals(0x33, indexed.getRGB()[0]);
assertEquals(0x33, indexed.getRGB()[1]);
assertEquals(0x00, indexed.getRGB()[2]);
assertEquals(3, indexed.getRGB().length);
assertEquals(0x33, indexed.getRGB()[0]);
assertEquals(0x33, indexed.getRGB()[1]);
assertEquals(0x00, indexed.getRGB()[2]);
assertEquals(4, indexed.getARGB().length);
assertEquals(-1, indexed.getARGB()[0]);
assertEquals(0x33, indexed.getARGB()[1]);
assertEquals(0x33, indexed.getARGB()[2]);
assertEquals(0x00, indexed.getARGB()[3]);
assertEquals(4, indexed.getARGB().length);
assertEquals(-1, indexed.getARGB()[0]);
assertEquals(0x33, indexed.getARGB()[1]);
assertEquals(0x33, indexed.getARGB()[2]);
assertEquals(0x00, indexed.getARGB()[3]);
// You don't get tinted indexed colours, sorry...
assertEquals(null, indexed.getRGBWithTint());
wb.close();
// You don't get tinted indexed colours, sorry...
assertNull(indexed.getRGBWithTint());
}
}
@Test
public void testRGBColour() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx");
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) {
// Check the CTColor is as expected
XSSFColor rgb3 = wb.getCellStyleAt((short)25).getFillForegroundXSSFColor();
assertEquals(false, rgb3.getCTColor().isSetIndexed());
assertEquals(0, rgb3.getCTColor().getIndexed());
assertEquals(true, rgb3.getCTColor().isSetTint());
assertEquals(-0.34999, rgb3.getCTColor().getTint(), 0.00001);
assertEquals(true, rgb3.getCTColor().isSetRgb());
assertEquals(3, rgb3.getCTColor().getRgb().length);
// Check the CTColor is as expected
XSSFColor rgb3 = wb.getCellStyleAt((short) 25).getFillForegroundXSSFColor();
assertFalse(rgb3.getCTColor().isSetIndexed());
assertEquals(0, rgb3.getCTColor().getIndexed());
assertTrue(rgb3.getCTColor().isSetTint());
assertEquals(-0.34999, rgb3.getCTColor().getTint(), 0.00001);
assertTrue(rgb3.getCTColor().isSetRgb());
assertEquals(3, rgb3.getCTColor().getRgb().length);
// Now check the XSSFColor
assertEquals(0, rgb3.getIndexed());
assertEquals(-0.34999, rgb3.getTint(), 0.00001);
assertFalse(rgb3.hasAlpha());
assertTrue(rgb3.hasTint());
// Now check the XSSFColor
assertEquals(0, rgb3.getIndexed());
assertEquals(-0.34999, rgb3.getTint(), 0.00001);
assertFalse(rgb3.hasAlpha());
assertTrue(rgb3.hasTint());
assertEquals("FFFFFFFF", rgb3.getARGBHex());
assertEquals(3, rgb3.getRGB().length);
assertEquals(-1, rgb3.getRGB()[0]);
assertEquals(-1, rgb3.getRGB()[1]);
assertEquals(-1, rgb3.getRGB()[2]);
assertEquals("FFFFFFFF", rgb3.getARGBHex());
assertEquals(3, rgb3.getRGB().length);
assertEquals(-1, rgb3.getRGB()[0]);
assertEquals(-1, rgb3.getRGB()[1]);
assertEquals(-1, rgb3.getRGB()[2]);
assertEquals(4, rgb3.getARGB().length);
assertEquals(-1, rgb3.getARGB()[0]);
assertEquals(-1, rgb3.getARGB()[1]);
assertEquals(-1, rgb3.getARGB()[2]);
assertEquals(-1, rgb3.getARGB()[3]);
assertEquals(4, rgb3.getARGB().length);
assertEquals(-1, rgb3.getARGB()[0]);
assertEquals(-1, rgb3.getARGB()[1]);
assertEquals(-1, rgb3.getARGB()[2]);
assertEquals(-1, rgb3.getARGB()[3]);
// Tint doesn't have the alpha
// tint = -0.34999
// 255 * (1 + tint) = 165 truncated
// or (byte) -91 (which is 165 - 256)
assertEquals(3, rgb3.getRGBWithTint().length);
assertEquals(-91, rgb3.getRGBWithTint()[0]);
assertEquals(-91, rgb3.getRGBWithTint()[1]);
assertEquals(-91, rgb3.getRGBWithTint()[2]);
// Tint doesn't have the alpha
// tint = -0.34999
// 255 * (1 + tint) = 165 truncated
// or (byte) -91 (which is 165 - 256)
assertEquals(3, rgb3.getRGBWithTint().length);
assertEquals(-91, rgb3.getRGBWithTint()[0]);
assertEquals(-91, rgb3.getRGBWithTint()[1]);
assertEquals(-91, rgb3.getRGBWithTint()[2]);
// Set the color to black (no theme).
rgb3.setRGB(new byte[] {0, 0, 0});
assertEquals("FF000000", rgb3.getARGBHex());
assertEquals(0, rgb3.getCTColor().getRgb()[0]);
assertEquals(0, rgb3.getCTColor().getRgb()[1]);
assertEquals(0, rgb3.getCTColor().getRgb()[2]);
// Set the color to black (no theme).
rgb3.setRGB(new byte[]{0, 0, 0});
assertEquals("FF000000", rgb3.getARGBHex());
assertEquals(0, rgb3.getCTColor().getRgb()[0]);
assertEquals(0, rgb3.getCTColor().getRgb()[1]);
assertEquals(0, rgb3.getCTColor().getRgb()[2]);
// Set another, is fine
rgb3.setRGB(new byte[] {16,17,18});
assertFalse(rgb3.hasAlpha());
assertEquals("FF101112", rgb3.getARGBHex());
assertEquals(0x10, rgb3.getCTColor().getRgb()[0]);
assertEquals(0x11, rgb3.getCTColor().getRgb()[1]);
assertEquals(0x12, rgb3.getCTColor().getRgb()[2]);
wb.close();
// Set another, is fine
rgb3.setRGB(new byte[]{16, 17, 18});
assertFalse(rgb3.hasAlpha());
assertEquals("FF101112", rgb3.getARGBHex());
assertEquals(0x10, rgb3.getCTColor().getRgb()[0]);
assertEquals(0x11, rgb3.getCTColor().getRgb()[1]);
assertEquals(0x12, rgb3.getCTColor().getRgb()[2]);
}
}
@Test
public void testARGBColour() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx");
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) {
// Check the CTColor is as expected
XSSFColor rgb4 = wb.getCellStyleAt((short)1).getFillForegroundXSSFColor();
assertEquals(false, rgb4.getCTColor().isSetIndexed());
assertEquals(0, rgb4.getCTColor().getIndexed());
assertEquals(true, rgb4.getCTColor().isSetRgb());
assertEquals(4, rgb4.getCTColor().getRgb().length);
// Check the CTColor is as expected
XSSFColor rgb4 = wb.getCellStyleAt((short) 1).getFillForegroundXSSFColor();
assertFalse(rgb4.getCTColor().isSetIndexed());
assertEquals(0, rgb4.getCTColor().getIndexed());
assertTrue(rgb4.getCTColor().isSetRgb());
assertEquals(4, rgb4.getCTColor().getRgb().length);
// Now check the XSSFColor
assertEquals(0, rgb4.getIndexed());
assertEquals(0.0, rgb4.getTint(), 0);
assertFalse(rgb4.hasTint());
assertTrue(rgb4.hasAlpha());
// Now check the XSSFColor
assertEquals(0, rgb4.getIndexed());
assertEquals(0.0, rgb4.getTint(), 0);
assertFalse(rgb4.hasTint());
assertTrue(rgb4.hasAlpha());
assertEquals("FFFF0000", rgb4.getARGBHex());
assertEquals(3, rgb4.getRGB().length);
assertEquals(-1, rgb4.getRGB()[0]);
assertEquals(0, rgb4.getRGB()[1]);
assertEquals(0, rgb4.getRGB()[2]);
assertEquals("FFFF0000", rgb4.getARGBHex());
assertEquals(3, rgb4.getRGB().length);
assertEquals(-1, rgb4.getRGB()[0]);
assertEquals(0, rgb4.getRGB()[1]);
assertEquals(0, rgb4.getRGB()[2]);
assertEquals(4, rgb4.getARGB().length);
assertEquals(-1, rgb4.getARGB()[0]);
assertEquals(-1, rgb4.getARGB()[1]);
assertEquals(0, rgb4.getARGB()[2]);
assertEquals(0, rgb4.getARGB()[3]);
assertEquals(4, rgb4.getARGB().length);
assertEquals(-1, rgb4.getARGB()[0]);
assertEquals(-1, rgb4.getARGB()[1]);
assertEquals(0, rgb4.getARGB()[2]);
assertEquals(0, rgb4.getARGB()[3]);
// Tint doesn't have the alpha
assertEquals(3, rgb4.getRGBWithTint().length);
assertEquals(-1, rgb4.getRGBWithTint()[0]);
assertEquals(0, rgb4.getRGBWithTint()[1]);
assertEquals(0, rgb4.getRGBWithTint()[2]);
// Tint doesn't have the alpha
assertEquals(3, rgb4.getRGBWithTint().length);
assertEquals(-1, rgb4.getRGBWithTint()[0]);
assertEquals(0, rgb4.getRGBWithTint()[1]);
assertEquals(0, rgb4.getRGBWithTint()[2]);
// Turn on tinting, and check it behaves
// TODO These values are suspected to be wrong...
rgb4.setTint(0.4);
assertTrue(rgb4.hasTint());
assertEquals(0.4, rgb4.getTint(), 0);
// Turn on tinting, and check it behaves
// TODO These values are suspected to be wrong...
rgb4.setTint(0.4);
assertTrue(rgb4.hasTint());
assertEquals(0.4, rgb4.getTint(), 0);
assertEquals(3, rgb4.getRGBWithTint().length);
assertEquals(-1, rgb4.getRGBWithTint()[0]);
assertEquals(102, rgb4.getRGBWithTint()[1]);
assertEquals(102, rgb4.getRGBWithTint()[2]);
wb.close();
assertEquals(3, rgb4.getRGBWithTint().length);
assertEquals(-1, rgb4.getRGBWithTint()[0]);
assertEquals(102, rgb4.getRGBWithTint()[1]);
assertEquals(102, rgb4.getRGBWithTint()[2]);
}
}
@Test
public void testCustomIndexedColour() throws Exception {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("customIndexedColors.xlsx");
XSSFCell cell = wb.getSheetAt(1).getRow(0).getCell(0);
XSSFColor color = cell.getCellStyle().getFillForegroundColorColor();
CTColors ctColors = wb.getStylesSource().getCTStylesheet().getColors();
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("customIndexedColors.xlsx")) {
XSSFCell cell = wb.getSheetAt(1).getRow(0).getCell(0);
XSSFColor color = cell.getCellStyle().getFillForegroundColorColor();
CTColors ctColors = wb.getStylesSource().getCTStylesheet().getColors();
CTRgbColor ctRgbColor = ctColors.getIndexedColors()
.getRgbColorList()
.get(color.getIndex());
CTRgbColor ctRgbColor = ctColors.getIndexedColors()
.getRgbColorList()
.get(color.getIndex());
String hexRgb = ctRgbColor.getDomNode().getAttributes().getNamedItem("rgb").getNodeValue();
String hexRgb = ctRgbColor.getDomNode().getAttributes().getNamedItem("rgb").getNodeValue();
assertEquals(hexRgb, color.getARGBHex());
assertEquals(hexRgb, color.getARGBHex());
}
}
}

View File

@ -53,30 +53,29 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
@Test
public void testSharedFormulas_evaluateInCell() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFSheet sheet = wb.getSheetAt(0);
try (XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx")) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFSheet sheet = wb.getSheetAt(0);
double result = 3.0;
double result = 3.0;
// B3 is a master shared formula, C3 and D3 don't have the formula written in their f element.
// Instead, the attribute si for a particular cell is used to figure what the formula expression
// should be based on the cell's relative location to the master formula, e.g.
// B3: <f t="shared" ref="B3:D3" si="0">B1+B2</f>
// C3 and D3: <f t="shared" si="0"/>
// B3 is a master shared formula, C3 and D3 don't have the formula written in their f element.
// Instead, the attribute si for a particular cell is used to figure what the formula expression
// should be based on the cell's relative location to the master formula, e.g.
// B3: <f t="shared" ref="B3:D3" si="0">B1+B2</f>
// C3 and D3: <f t="shared" si="0"/>
// get B3 and evaluate it in the cell
XSSFCell b3 = sheet.getRow(2).getCell(1);
assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0);
// get B3 and evaluate it in the cell
XSSFCell b3 = sheet.getRow(2).getCell(1);
assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0);
//at this point the master formula is gone, but we are still able to evaluate dependent cells
XSSFCell c3 = sheet.getRow(2).getCell(2);
assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0);
//at this point the master formula is gone, but we are still able to evaluate dependent cells
XSSFCell c3 = sheet.getRow(2).getCell(2);
assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0);
XSSFCell d3 = sheet.getRow(2).getCell(3);
assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0);
wb.close();
XSSFCell d3 = sheet.getRow(2).getCell(3);
assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0);
}
}
/**
@ -84,32 +83,31 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
*/
@Test
public void testEvaluateColumnGreaterThan255() throws IOException {
XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx");
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
try (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx")) {
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
/*
* The first row simply contains the numbers 1 - 300.
* The second row simply refers to the cell value above in the first row by a simple formula.
*/
for (int i = 245; i < 265; i++) {
XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i);
XSSFCell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i);
/*
* The first row simply contains the numbers 1 - 300.
* The second row simply refers to the cell value above in the first row by a simple formula.
*/
for (int i = 245; i < 265; i++) {
XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i);
XSSFCell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i);
CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
String fmla = cell_formula.getCellFormula();
// assure that the formula refers to the cell above.
// the check below is 'deep' and involves conversion of the shared formula:
// in the sample file a shared formula in GN1 is spanned in the range GN2:IY2,
assertEquals(ref_noformula.formatAsString(), fmla);
CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex());
String fmla = cell_formula.getCellFormula();
// assure that the formula refers to the cell above.
// the check below is 'deep' and involves conversion of the shared formula:
// in the sample file a shared formula in GN1 is spanned in the range GN2:IY2,
assertEquals(ref_noformula.formatAsString(), fmla);
CellValue cv_noformula = evaluator.evaluate(cell_noformula);
CellValue cv_formula = evaluator.evaluate(cell_formula);
assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(),
cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0);
CellValue cv_noformula = evaluator.evaluate(cell_noformula);
CellValue cv_formula = evaluator.evaluate(cell_formula);
assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(),
cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0);
}
}
wb.close();
}
/**
@ -119,105 +117,110 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
*/
@Test
public void testReferencesToOtherWorkbooks() throws Exception {
XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx");
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFSheet s = wb.getSheetAt(0);
// References to a .xlsx file
Row rXSLX = s.getRow(2);
Cell cXSLX_cell = rXSLX.getCell(4);
Cell cXSLX_sNR = rXSLX.getCell(6);
Cell cXSLX_gNR = rXSLX.getCell(8);
assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula());
assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula());
assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula());
assertEquals("Hello!", cXSLX_cell.getStringCellValue());
assertEquals("Test A1", cXSLX_sNR.getStringCellValue());
assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0);
// References to a .xls file
Row rXSL = s.getRow(4);
Cell cXSL_cell = rXSL.getCell(4);
Cell cXSL_sNR = rXSL.getCell(6);
Cell cXSL_gNR = rXSL.getCell(8);
assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula());
assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula());
assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula());
assertEquals("Hello!", cXSL_cell.getStringCellValue());
assertEquals("Test A1", cXSL_sNR.getStringCellValue());
assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0);
// Try to evaluate without references, won't work
// (At least, not unit we fix bug #56752 that is)
try {
evaluator.evaluate(cXSL_cell);
fail("Without a fix for #56752, shouldn't be able to evaluate a " +
"reference to a non-provided linked workbook");
} catch(Exception e) {
// expected here
}
// Setup the environment
Map<String,FormulaEvaluator> evaluators = new HashMap<>();
evaluators.put("ref2-56737.xlsx", evaluator);
evaluators.put("56737.xlsx",
_testDataProvider.openSampleWorkbook("56737.xlsx").getCreationHelper().createFormulaEvaluator());
evaluators.put("56737.xls",
HSSFTestDataSamples.openSampleWorkbook("56737.xls").getCreationHelper().createFormulaEvaluator());
evaluator.setupReferencedWorkbooks(evaluators);
// Try evaluating all of them, ensure we don't blow up
for(Row r : s) {
for (Cell c : r) {
evaluator.evaluate(c);
}
}
// And evaluate the other way too
evaluator.evaluateAll();
// Static evaluator won't work, as no references passed in
try {
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
fail("Static method lacks references, shouldn't work");
} catch(Exception e) {
// expected here
}
// Evaluate specific cells and check results
assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString());
assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString());
assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString());
try (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx")) {
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFSheet s = wb.getSheetAt(0);
assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString());
assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString());
assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString());
// Add another formula referencing these workbooks
Cell cXSL_cell2 = rXSL.createCell(40);
cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1");
// TODO Shouldn't it become [2] like the others?
assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula());
assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString());
// Now add a formula that refers to yet another (different) workbook
// Won't work without the workbook being linked
Cell cXSLX_nw_cell = rXSLX.createCell(42);
try {
cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1");
fail("New workbook not linked, shouldn't be able to add");
} catch (Exception e) {
// expected here
}
// Link and re-try
try (Workbook alt = new XSSFWorkbook()) {
alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
// TODO Implement the rest of this, see bug #57184
// References to a .xlsx file
Row rXSLX = s.getRow(2);
Cell cXSLX_cell = rXSLX.getCell(4);
Cell cXSLX_sNR = rXSLX.getCell(6);
Cell cXSLX_gNR = rXSLX.getCell(8);
assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula());
assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula());
assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula());
assertEquals("Hello!", cXSLX_cell.getStringCellValue());
assertEquals("Test A1", cXSLX_sNR.getStringCellValue());
assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0);
// References to a .xls file
Row rXSL = s.getRow(4);
Cell cXSL_cell = rXSL.getCell(4);
Cell cXSL_sNR = rXSL.getCell(6);
Cell cXSL_gNR = rXSL.getCell(8);
assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula());
assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula());
assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula());
assertEquals("Hello!", cXSL_cell.getStringCellValue());
assertEquals("Test A1", cXSL_sNR.getStringCellValue());
assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0);
// Try to evaluate without references, won't work
// (At least, not unit we fix bug #56752 that is)
try {
evaluator.evaluate(cXSL_cell);
fail("Without a fix for #56752, shouldn't be able to evaluate a " +
"reference to a non-provided linked workbook");
} catch (Exception e) {
// expected here
}
// Setup the environment
Map<String, FormulaEvaluator> evaluators = new HashMap<>();
evaluators.put("ref2-56737.xlsx", evaluator);
Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx");
evaluators.put("56737.xlsx",
wbEval1.getCreationHelper().createFormulaEvaluator());
Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls");
evaluators.put("56737.xls",
wbEval2.getCreationHelper().createFormulaEvaluator());
evaluator.setupReferencedWorkbooks(evaluators);
// Try evaluating all of them, ensure we don't blow up
for (Row r : s) {
for (Cell c : r) {
evaluator.evaluate(c);
}
}
// And evaluate the other way too
evaluator.evaluateAll();
// Static evaluator won't work, as no references passed in
try {
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
fail("Static method lacks references, shouldn't work");
} catch (Exception e) {
// expected here
}
// Evaluate specific cells and check results
assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString());
assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString());
assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString());
assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString());
assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString());
assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString());
// Add another formula referencing these workbooks
Cell cXSL_cell2 = rXSL.createCell(40);
cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1");
// TODO Shouldn't it become [2] like the others?
assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula());
assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString());
// Now add a formula that refers to yet another (different) workbook
// Won't work without the workbook being linked
Cell cXSLX_nw_cell = rXSLX.createCell(42);
try {
cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1");
fail("New workbook not linked, shouldn't be able to add");
} catch (Exception e) {
// expected here
}
wbEval1.close();
wbEval2.close();
// Link and re-try
try (Workbook alt = new XSSFWorkbook()) {
alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
// TODO Implement the rest of this, see bug #57184
/*
wb.linkExternalWorkbook("alt.xlsx", alt);
@ -238,9 +241,8 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
evaluator.evaluate(cXSLX_nw_cell);
assertEquals("In another workbook", cXSLX_nw_cell.getStringCellValue());
*/
}
}
wb.close();
}
/**
@ -389,63 +391,66 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator {
// FIXME: use junit4 parametrization
private static void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook) throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook);
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
wb.close();
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook)) {
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
}
}
@Test
public void test59736() {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
assertEquals(1, cell.getNumericCellValue(), 0.001);
public void test59736() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx")) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
assertEquals(1, cell.getNumericCellValue(), 0.001);
cell = wb.getSheetAt(0).getRow(1).getCell(0);
CellValue value = evaluator.evaluate(cell);
assertEquals(1, value.getNumberValue(), 0.001);
cell = wb.getSheetAt(0).getRow(1).getCell(0);
CellValue value = evaluator.evaluate(cell);
assertEquals(1, value.getNumberValue(), 0.001);
cell = wb.getSheetAt(0).getRow(2).getCell(0);
value = evaluator.evaluate(cell);
assertEquals(1, value.getNumberValue(), 0.001);
cell = wb.getSheetAt(0).getRow(2).getCell(0);
value = evaluator.evaluate(cell);
assertEquals(1, value.getNumberValue(), 0.001);
}
}
@Test
public void evaluateInCellReturnsSameDataType() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
wb.createSheet().createRow(0).createCell(0);
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
XSSFCell same = evaluator.evaluateInCell(cell);
assertSame(cell, same);
wb.close();
try (XSSFWorkbook wb = new XSSFWorkbook()) {
wb.createSheet().createRow(0).createCell(0);
XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
XSSFCell same = evaluator.evaluateInCell(cell);
assertSame(cell, same);
}
}
@Test
public void testBug61468() {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell = wb.getSheetAt(0).getRow(8).getCell(4);
assertEquals(3750, cell.getNumericCellValue(), 0.001);
public void testBug61468() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx")) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell = wb.getSheetAt(0).getRow(8).getCell(4);
assertEquals(3750, cell.getNumericCellValue(), 0.001);
CellValue value = evaluator.evaluate(cell);
assertEquals(3750, value.getNumberValue(), 0.001);
CellValue value = evaluator.evaluate(cell);
assertEquals(3750, value.getNumberValue(), 0.001);
}
}
@Test
@Ignore // this is from an open bug/discussion over handling localization for number formats
public void testBug61495() {
Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell = wb.getSheetAt(0).getRow(0).getCell(1);
public void testBug61495() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm")) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell = wb.getSheetAt(0).getRow(0).getCell(1);
// assertEquals("D 67.10", cell.getStringCellValue());
CellValue value = evaluator.evaluate(cell);
assertEquals("D 67.10",
value.getStringValue());
assertEquals("D 0,068",
evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(1)).getStringValue());
CellValue value = evaluator.evaluate(cell);
assertEquals("D 67.10",
value.getStringValue());
assertEquals("D 0,068",
evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(1)).getStringValue());
}
}

View File

@ -39,15 +39,16 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink {
}
@Test
public void testLoadExisting() {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx");
assertEquals(3, workbook.getNumberOfSheets());
public void testLoadExisting() throws IOException {
try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) {
assertEquals(3, workbook.getNumberOfSheets());
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet sheet = workbook.getSheetAt(0);
// Check the hyperlinks
assertEquals(4, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
// Check the hyperlinks
assertEquals(4, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
}
}
@Test
@ -117,73 +118,74 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink {
}
@Test
public void testLoadSave() {
XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx");
CreationHelper createHelper = workbook.getCreationHelper();
assertEquals(3, workbook.getNumberOfSheets());
XSSFSheet sheet = workbook.getSheetAt(0);
public void testLoadSave() throws IOException {
try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) {
CreationHelper createHelper = workbook.getCreationHelper();
assertEquals(3, workbook.getNumberOfSheets());
XSSFSheet sheet = workbook.getSheetAt(0);
// Check hyperlinks
assertEquals(4, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
// Check hyperlinks
assertEquals(4, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
// Write out, and check
// Write out, and check
// Load up again, check all links still there
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertEquals(3, wb2.getNumberOfSheets());
assertNotNull(wb2.getSheetAt(0));
assertNotNull(wb2.getSheetAt(1));
assertNotNull(wb2.getSheetAt(2));
// Load up again, check all links still there
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook);
assertEquals(3, wb2.getNumberOfSheets());
assertNotNull(wb2.getSheetAt(0));
assertNotNull(wb2.getSheetAt(1));
assertNotNull(wb2.getSheetAt(2));
sheet = wb2.getSheetAt(0);
sheet = wb2.getSheetAt(0);
// Check hyperlinks again
assertEquals(4, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
// Check hyperlinks again
assertEquals(4, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
// Add one more, and re-check
Row r17 = sheet.createRow(17);
Cell r17c = r17.createCell(2);
// Add one more, and re-check
Row r17 = sheet.createRow(17);
Cell r17c = r17.createCell(2);
Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("http://poi.apache.org/spreadsheet/");
hyperlink.setLabel("POI SS Link");
r17c.setHyperlink(hyperlink);
Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("http://poi.apache.org/spreadsheet/");
hyperlink.setLabel("POI SS Link");
r17c.setHyperlink(hyperlink);
assertEquals(5, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
assertEquals(5, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
assertEquals(HyperlinkType.URL,
sheet.getRow(17).getCell(2).getHyperlink().getType());
assertEquals("POI SS Link",
sheet.getRow(17).getCell(2).getHyperlink().getLabel());
assertEquals("http://poi.apache.org/spreadsheet/",
sheet.getRow(17).getCell(2).getHyperlink().getAddress());
assertEquals(HyperlinkType.URL,
sheet.getRow(17).getCell(2).getHyperlink().getType());
assertEquals("POI SS Link",
sheet.getRow(17).getCell(2).getHyperlink().getLabel());
assertEquals("http://poi.apache.org/spreadsheet/",
sheet.getRow(17).getCell(2).getHyperlink().getAddress());
// Save and re-load once more
// Save and re-load once more
XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
assertEquals(3, wb3.getNumberOfSheets());
assertNotNull(wb3.getSheetAt(0));
assertNotNull(wb3.getSheetAt(1));
assertNotNull(wb3.getSheetAt(2));
XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
assertEquals(3, wb3.getNumberOfSheets());
assertNotNull(wb3.getSheetAt(0));
assertNotNull(wb3.getSheetAt(1));
assertNotNull(wb3.getSheetAt(2));
sheet = wb3.getSheetAt(0);
sheet = wb3.getSheetAt(0);
assertEquals(5, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
assertEquals(5, sheet.getNumHyperlinks());
doTestHyperlinkContents(sheet);
assertEquals(HyperlinkType.URL,
sheet.getRow(17).getCell(2).getHyperlink().getType());
assertEquals("POI SS Link",
sheet.getRow(17).getCell(2).getHyperlink().getLabel());
assertEquals("http://poi.apache.org/spreadsheet/",
sheet.getRow(17).getCell(2).getHyperlink().getAddress());
assertEquals(HyperlinkType.URL,
sheet.getRow(17).getCell(2).getHyperlink().getType());
assertEquals("POI SS Link",
sheet.getRow(17).getCell(2).getHyperlink().getLabel());
assertEquals("http://poi.apache.org/spreadsheet/",
sheet.getRow(17).getCell(2).getHyperlink().getAddress());
}
}
/**
@ -198,8 +200,7 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink {
// First is a link to poi
assertEquals(HyperlinkType.URL,
sheet.getRow(3).getCell(2).getHyperlink().getType());
assertEquals(null,
sheet.getRow(3).getCell(2).getHyperlink().getLabel());
assertNull(sheet.getRow(3).getCell(2).getHyperlink().getLabel());
assertEquals("http://poi.apache.org/",
sheet.getRow(3).getCell(2).getHyperlink().getAddress());
@ -214,60 +215,63 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink {
// Next is a file
assertEquals(HyperlinkType.FILE,
sheet.getRow(15).getCell(2).getHyperlink().getType());
assertEquals(null,
sheet.getRow(15).getCell(2).getHyperlink().getLabel());
assertNull(sheet.getRow(15).getCell(2).getHyperlink().getLabel());
assertEquals("WithVariousData.xlsx",
sheet.getRow(15).getCell(2).getHyperlink().getAddress());
// Last is a mailto
assertEquals(HyperlinkType.EMAIL,
sheet.getRow(16).getCell(2).getHyperlink().getType());
assertEquals(null,
sheet.getRow(16).getCell(2).getHyperlink().getLabel());
assertNull(sheet.getRow(16).getCell(2).getHyperlink().getLabel());
assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks",
sheet.getRow(16).getCell(2).getHyperlink().getAddress());
}
@Test
public void test52716() {
XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("52716.xlsx");
XSSFSheet sh1 = wb1.getSheetAt(0);
public void test52716() throws IOException {
try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("52716.xlsx")) {
XSSFSheet sh1 = wb1.getSheetAt(0);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
XSSFSheet sh2 = wb2.getSheetAt(0);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
XSSFSheet sh2 = wb2.getSheetAt(0);
assertEquals(sh1.getNumberOfComments(), sh2.getNumberOfComments());
XSSFHyperlink l1 = sh1.getHyperlink(0, 1);
assertEquals(HyperlinkType.DOCUMENT, l1.getType());
assertEquals("B1", l1.getCellRef());
assertEquals("Sort on Titel", l1.getTooltip());
assertEquals(sh1.getNumberOfComments(), sh2.getNumberOfComments());
XSSFHyperlink l1 = sh1.getHyperlink(0, 1);
assertEquals(HyperlinkType.DOCUMENT, l1.getType());
assertEquals("B1", l1.getCellRef());
assertEquals("Sort on Titel", l1.getTooltip());
XSSFHyperlink l2 = sh2.getHyperlink(0, 1);
assertEquals(l1.getTooltip(), l2.getTooltip());
assertEquals(HyperlinkType.DOCUMENT, l2.getType());
assertEquals("B1", l2.getCellRef());
XSSFHyperlink l2 = sh2.getHyperlink(0, 1);
assertEquals(l1.getTooltip(), l2.getTooltip());
assertEquals(HyperlinkType.DOCUMENT, l2.getType());
assertEquals("B1", l2.getCellRef());
}
}
@Test
public void test53734() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53734.xlsx");
XSSFHyperlink link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink();
assertEquals("javascript:///", link.getAddress());
public void test53734() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53734.xlsx")) {
Hyperlink link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink();
assertEquals("javascript:///", link.getAddress());
wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink();
assertEquals("javascript:///", link.getAddress());
try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
link = wb2.getSheetAt(0).getRow(0).getCell(0).getHyperlink();
assertEquals("javascript:///", link.getAddress());
}
}
}
@Test
public void test53282() {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53282.xlsx");
XSSFHyperlink link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress());
public void test53282() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53282.xlsx")) {
Hyperlink link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress());
wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress());
try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
link = wb2.getSheetAt(0).getRow(0).getCell(14).getHyperlink();
assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress());
}
}
}
@Override

View File

@ -20,7 +20,7 @@ package org.apache.poi.xssf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Iterator;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.XSSFTestDataSamples;
@ -32,13 +32,17 @@ import org.junit.Test;
public final class TestXSSFShape {
@Test
public void test58325_one() {
check58325(XSSFTestDataSamples.openSampleWorkbook("58325_lt.xlsx"), 1);
public void test58325_one() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58325_lt.xlsx")) {
check58325(wb, 1);
}
}
@Test
public void test58325_three() {
check58325(XSSFTestDataSamples.openSampleWorkbook("58325_db.xlsx"), 3);
public void test58325_three() throws IOException {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58325_db.xlsx")) {
check58325(wb, 3);
}
}
private void check58325(XSSFWorkbook wb, int expectedShapes) {
@ -46,21 +50,19 @@ public final class TestXSSFShape {
assertNotNull(sheet);
StringBuilder str = new StringBuilder();
str.append("sheet " + sheet.getSheetName() + " - ");
str.append("sheet ").append(sheet.getSheetName()).append(" - ");
XSSFDrawing drawing = sheet.getDrawingPatriarch();
//drawing = ((XSSFSheet)sheet).createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
str.append("drawing.getShapes().size() = " + shapes.size());
Iterator<XSSFShape> it = shapes.iterator();
while(it.hasNext()) {
XSSFShape shape = it.next();
str.append(", " + shape);
str.append(", Col1:"+((XSSFClientAnchor)shape.getAnchor()).getCol1());
str.append(", Col2:"+((XSSFClientAnchor)shape.getAnchor()).getCol2());
str.append(", Row1:"+((XSSFClientAnchor)shape.getAnchor()).getRow1());
str.append(", Row2:"+((XSSFClientAnchor)shape.getAnchor()).getRow2());
str.append("drawing.getShapes().size() = ").append(shapes.size());
for (XSSFShape shape : shapes) {
str.append(", ").append(shape);
str.append(", Col1:").append(((XSSFClientAnchor) shape.getAnchor()).getCol1());
str.append(", Col2:").append(((XSSFClientAnchor) shape.getAnchor()).getCol2());
str.append(", Row1:").append(((XSSFClientAnchor) shape.getAnchor()).getRow1());
str.append(", Row2:").append(((XSSFClientAnchor) shape.getAnchor()).getRow2());
}
assertEquals("Having shapes: " + str,

View File

@ -34,7 +34,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
//private int o_groupsNumber = 0;
public void test55640() throws IOException {
public void test55640() {
//long startTime = System.currentTimeMillis();
Workbook wb = new XSSFWorkbook();
fillData(wb);
@ -78,7 +78,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
return Math.random() > 0.5d;
}
private void writeToFile(Workbook p_wb) throws IOException {
private void writeToFile(Workbook p_wb) {
// FileOutputStream fileOut = new FileOutputStream("/tmp/55640.xlsx");
// try {
// p_wb.write(fileOut);
@ -88,7 +88,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(p_wb));
}
public void test55640reduce1() throws IOException {
public void test55640reduce1() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
sheet.setRowSumsBelow(false);
@ -117,7 +117,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
}
public void test55640_VerifyCases() throws IOException {
public void test55640_VerifyCases() {
// NOTE: This is currently based on current behavior of POI, somehow
// what POI returns in the calls to collapsed/hidden is not fully matching
// the examples in the spec or I did not fully understand how POI stores the data internally...
@ -210,7 +210,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
private void verifyGroupCollapsed(boolean level1, boolean level2, boolean level3,
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException {
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
@ -282,7 +282,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
}
private void verifyGroupCollapsedSpec(boolean level1, boolean level2, boolean level3,
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException {
Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
@ -301,7 +301,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel);
}
private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException {
private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) {
printWorkbook(wb);
Sheet sheet = wb.getSheetAt(0);
@ -327,7 +327,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
}
public void test55640working() throws IOException {
public void test55640working() {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet123");
@ -366,50 +366,51 @@ public final class TestXSSFSheetRowGrouping extends TestCase {
}
public void testGroupingTest() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx");
assertEquals(31, wb.getSheetAt(0).getLastRowNum());
// NOTE: This is currently based on current behavior of POI, somehow
// what POI returns in the calls to collapsed/hidden is not fully matching
// the examples in the spec or I did not fully understand how POI stores the data internally...
checkWorkbookGrouping(wb,
new Boolean [] {
// 0-4
false, false, false, false, false, null, null,
// 7-11
false, false, true, true, true, null, null,
// 14-18
false, false, true, false, false, null,
// 20-24
false, false, true, true, false, null, null,
// 27-31
false, false, false, true, false },
new boolean[] {
// 0-4
false, false, false, false, false, false, false,
// 7-11
true, true, true, true, false, false, false,
// 14-18
true, true, false, false, false, false,
// 20-24
true, true, true, false, false, false, false,
// 27-31
true, true, true, true, false },
// outlineLevel
new int[] {
// 0-4
3, 3, 2, 1, 0, 0, 0,
// 7-11
3, 3, 2, 1, 0, 0, 0,
// 14-18
3, 3, 2, 1, 0, 0,
// 20-24
3, 3, 2, 1, 0, 0, 0,
// 27-31
3, 3, 2, 1, 0,
}
);
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx")) {
assertEquals(31, wb.getSheetAt(0).getLastRowNum());
// NOTE: This is currently based on current behavior of POI, somehow
// what POI returns in the calls to collapsed/hidden is not fully matching
// the examples in the spec or I did not fully understand how POI stores the data internally...
checkWorkbookGrouping(wb,
new Boolean[]{
// 0-4
false, false, false, false, false, null, null,
// 7-11
false, false, true, true, true, null, null,
// 14-18
false, false, true, false, false, null,
// 20-24
false, false, true, true, false, null, null,
// 27-31
false, false, false, true, false},
new boolean[]{
// 0-4
false, false, false, false, false, false, false,
// 7-11
true, true, true, true, false, false, false,
// 14-18
true, true, false, false, false, false,
// 20-24
true, true, true, false, false, false, false,
// 27-31
true, true, true, true, false},
// outlineLevel
new int[]{
// 0-4
3, 3, 2, 1, 0, 0, 0,
// 7-11
3, 3, 2, 1, 0, 0, 0,
// 14-18
3, 3, 2, 1, 0, 0,
// 20-24
3, 3, 2, 1, 0, 0, 0,
// 27-31
3, 3, 2, 1, 0,
}
);
}
/*
Row: 0: Level: 3 Collapsed: false Hidden: false
Row: 1: Level: 3 Collapsed: false Hidden: false

View File

@ -20,6 +20,7 @@ package org.apache.poi.xwpf.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.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@ -28,6 +29,7 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ooxml.POIXMLDocumentPart;
@ -96,7 +98,7 @@ public final class TestXWPFDocument {
assertEquals(1315, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters());
assertEquals(10, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines());
assertEquals(null, xml.getProperties().getCoreProperties().getTitle());
assertNull(xml.getProperties().getCoreProperties().getTitle());
assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent());
}
}
@ -112,7 +114,9 @@ public final class TestXWPFDocument {
assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines());
assertEquals(" ", xml.getProperties().getCoreProperties().getTitle());
assertEquals(" ", xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().get());
Optional<String> subjectProperty = xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty();
assertTrue(subjectProperty.isPresent());
assertEquals(" ", subjectProperty.get());
xml.close();
}
@ -153,7 +157,9 @@ public final class TestXWPFDocument {
byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg");
String relationId = doc.addPictureData(jpeg, Document.PICTURE_TYPE_JPEG);
byte[] newJpeg = ((XWPFPictureData) doc.getRelationById(relationId)).getData();
XWPFPictureData relationById = (XWPFPictureData) doc.getRelationById(relationId);
assertNotNull(relationById);
byte[] newJpeg = relationById.getData();
assertEquals(newJpeg.length, jpeg.length);
for (int i = 0; i < jpeg.length; i++) {
assertEquals(newJpeg[i], jpeg[i]);
@ -187,225 +193,225 @@ public final class TestXWPFDocument {
@Test
public void testAddHyperlink() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
XWPFParagraph p = doc.createParagraph();
XWPFHyperlinkRun h = p.createHyperlinkRun("http://poi.apache.org/");
h.setText("Apache POI");
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) {
XWPFParagraph p = doc.createParagraph();
XWPFHyperlinkRun h = p.createHyperlinkRun("http://poi.apache.org/");
h.setText("Apache POI");
assertEquals("http://poi.apache.org/", h.getHyperlink(doc).getURL());
assertEquals(p.getRuns().size(), 1);
assertEquals(p.getRuns().get(0), h);
assertEquals("http://poi.apache.org/", h.getHyperlink(doc).getURL());
assertEquals(p.getRuns().size(), 1);
assertEquals(p.getRuns().get(0), h);
}
}
@Test
public void testRemoveBodyElement() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
assertEquals(3, doc.getParagraphs().size());
assertEquals(3, doc.getBodyElements().size());
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) {
assertEquals(3, doc.getParagraphs().size());
assertEquals(3, doc.getBodyElements().size());
XWPFParagraph p1 = doc.getParagraphs().get(0);
XWPFParagraph p2 = doc.getParagraphs().get(1);
XWPFParagraph p3 = doc.getParagraphs().get(2);
XWPFParagraph p1 = doc.getParagraphs().get(0);
XWPFParagraph p2 = doc.getParagraphs().get(1);
XWPFParagraph p3 = doc.getParagraphs().get(2);
assertEquals(p1, doc.getBodyElements().get(0));
assertEquals(p1, doc.getParagraphs().get(0));
assertEquals(p2, doc.getBodyElements().get(1));
assertEquals(p2, doc.getParagraphs().get(1));
assertEquals(p3, doc.getBodyElements().get(2));
assertEquals(p3, doc.getParagraphs().get(2));
assertEquals(p1, doc.getBodyElements().get(0));
assertEquals(p1, doc.getParagraphs().get(0));
assertEquals(p2, doc.getBodyElements().get(1));
assertEquals(p2, doc.getParagraphs().get(1));
assertEquals(p3, doc.getBodyElements().get(2));
assertEquals(p3, doc.getParagraphs().get(2));
// Add another
XWPFParagraph p4 = doc.createParagraph();
// Add another
XWPFParagraph p4 = doc.createParagraph();
assertEquals(4, doc.getParagraphs().size());
assertEquals(4, doc.getBodyElements().size());
assertEquals(p1, doc.getBodyElements().get(0));
assertEquals(p1, doc.getParagraphs().get(0));
assertEquals(p2, doc.getBodyElements().get(1));
assertEquals(p2, doc.getParagraphs().get(1));
assertEquals(p3, doc.getBodyElements().get(2));
assertEquals(p3, doc.getParagraphs().get(2));
assertEquals(p4, doc.getBodyElements().get(3));
assertEquals(p4, doc.getParagraphs().get(3));
assertEquals(4, doc.getParagraphs().size());
assertEquals(4, doc.getBodyElements().size());
assertEquals(p1, doc.getBodyElements().get(0));
assertEquals(p1, doc.getParagraphs().get(0));
assertEquals(p2, doc.getBodyElements().get(1));
assertEquals(p2, doc.getParagraphs().get(1));
assertEquals(p3, doc.getBodyElements().get(2));
assertEquals(p3, doc.getParagraphs().get(2));
assertEquals(p4, doc.getBodyElements().get(3));
assertEquals(p4, doc.getParagraphs().get(3));
// Remove the 2nd
assertEquals(true, doc.removeBodyElement(1));
assertEquals(3, doc.getParagraphs().size());
assertEquals(3, doc.getBodyElements().size());
// Remove the 2nd
assertTrue(doc.removeBodyElement(1));
assertEquals(3, doc.getParagraphs().size());
assertEquals(3, doc.getBodyElements().size());
assertEquals(p1, doc.getBodyElements().get(0));
assertEquals(p1, doc.getParagraphs().get(0));
assertEquals(p3, doc.getBodyElements().get(1));
assertEquals(p3, doc.getParagraphs().get(1));
assertEquals(p4, doc.getBodyElements().get(2));
assertEquals(p4, doc.getParagraphs().get(2));
assertEquals(p1, doc.getBodyElements().get(0));
assertEquals(p1, doc.getParagraphs().get(0));
assertEquals(p3, doc.getBodyElements().get(1));
assertEquals(p3, doc.getParagraphs().get(1));
assertEquals(p4, doc.getBodyElements().get(2));
assertEquals(p4, doc.getParagraphs().get(2));
// Remove the 1st
assertEquals(true, doc.removeBodyElement(0));
assertEquals(2, doc.getParagraphs().size());
assertEquals(2, doc.getBodyElements().size());
// Remove the 1st
assertTrue(doc.removeBodyElement(0));
assertEquals(2, doc.getParagraphs().size());
assertEquals(2, doc.getBodyElements().size());
assertEquals(p3, doc.getBodyElements().get(0));
assertEquals(p3, doc.getParagraphs().get(0));
assertEquals(p4, doc.getBodyElements().get(1));
assertEquals(p4, doc.getParagraphs().get(1));
assertEquals(p3, doc.getBodyElements().get(0));
assertEquals(p3, doc.getParagraphs().get(0));
assertEquals(p4, doc.getBodyElements().get(1));
assertEquals(p4, doc.getParagraphs().get(1));
// Remove the last
assertEquals(true, doc.removeBodyElement(1));
assertEquals(1, doc.getParagraphs().size());
assertEquals(1, doc.getBodyElements().size());
// Remove the last
assertTrue(doc.removeBodyElement(1));
assertEquals(1, doc.getParagraphs().size());
assertEquals(1, doc.getBodyElements().size());
assertEquals(p3, doc.getBodyElements().get(0));
assertEquals(p3, doc.getParagraphs().get(0));
doc.close();
assertEquals(p3, doc.getBodyElements().get(0));
assertEquals(p3, doc.getParagraphs().get(0));
}
}
@Test
public void testRegisterPackagePictureData() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx");
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) {
/* manually assemble a new image package part*/
OPCPackage opcPkg = doc.getPackage();
XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG;
PackagePartName partName = PackagingURIHelper.createPartName(jpgRelation.getDefaultFileName().replace('#', '2'));
PackagePart newImagePart = opcPkg.createPart(partName, jpgRelation.getContentType());
byte[] nature1 = XWPFTestDataSamples.getImage("abstract4.jpg");
OutputStream os = newImagePart.getOutputStream();
os.write(nature1);
os.close();
XWPFHeader xwpfHeader = doc.getHeaderArray(0);
XWPFPictureData newPicData = new XWPFPictureData(newImagePart);
/* new part is now ready to rumble */
/* manually assemble a new image package part*/
OPCPackage opcPckg = doc.getPackage();
XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG;
PackagePartName partName = PackagingURIHelper.createPartName(jpgRelation.getDefaultFileName().replace('#', '2'));
PackagePart newImagePart = opcPckg.createPart(partName, jpgRelation.getContentType());
byte[] nature1 = XWPFTestDataSamples.getImage("abstract4.jpg");
OutputStream os = newImagePart.getOutputStream();
os.write(nature1);
os.close();
XWPFHeader xwpfHeader = doc.getHeaderArray(0);
XWPFPictureData newPicData = new XWPFPictureData(newImagePart);
/* new part is now ready to rumble */
assertFalse(xwpfHeader.getAllPictures().contains(newPicData));
assertFalse(doc.getAllPictures().contains(newPicData));
assertFalse(doc.getAllPackagePictures().contains(newPicData));
assertFalse(xwpfHeader.getAllPictures().contains(newPicData));
assertFalse(doc.getAllPictures().contains(newPicData));
assertFalse(doc.getAllPackagePictures().contains(newPicData));
doc.registerPackagePictureData(newPicData);
doc.registerPackagePictureData(newPicData);
assertFalse(xwpfHeader.getAllPictures().contains(newPicData));
assertFalse(doc.getAllPictures().contains(newPicData));
assertTrue(doc.getAllPackagePictures().contains(newPicData));
assertFalse(xwpfHeader.getAllPictures().contains(newPicData));
assertFalse(doc.getAllPictures().contains(newPicData));
assertTrue(doc.getAllPackagePictures().contains(newPicData));
doc.getPackage().revert();
opcPckg.close();
doc.close();
doc.getPackage().revert();
opcPkg.close();
}
}
@Test
public void testFindPackagePictureData() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx");
byte[] nature1 = XWPFTestDataSamples.getImage("nature1.gif");
XWPFPictureData part = doc.findPackagePictureData(nature1, Document.PICTURE_TYPE_GIF);
assertNotNull(part);
assertTrue(doc.getAllPictures().contains(part));
assertTrue(doc.getAllPackagePictures().contains(part));
doc.getPackage().revert();
doc.close();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) {
byte[] nature1 = XWPFTestDataSamples.getImage("nature1.gif");
XWPFPictureData part = doc.findPackagePictureData(nature1, Document.PICTURE_TYPE_GIF);
assertNotNull(part);
assertTrue(doc.getAllPictures().contains(part));
assertTrue(doc.getAllPackagePictures().contains(part));
doc.getPackage().revert();
}
}
@Test
public void testGetAllPictures() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx");
List<XWPFPictureData> allPictures = doc.getAllPictures();
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) {
List<XWPFPictureData> allPictures = doc.getAllPictures();
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPictures);
assertEquals(3, allPictures.size());
for (XWPFPictureData xwpfPictureData : allPictures) {
assertTrue(allPackagePictures.contains(xwpfPictureData));
assertNotNull(allPictures);
assertEquals(3, allPictures.size());
for (XWPFPictureData xwpfPictureData : allPictures) {
assertTrue(allPackagePictures.contains(xwpfPictureData));
}
try {
allPictures.add(allPictures.get(0));
fail("This list must be unmodifiable!");
} catch (UnsupportedOperationException e) {
// all ok
}
doc.getPackage().revert();
}
try {
allPictures.add(allPictures.get(0));
fail("This list must be unmodifiable!");
} catch (UnsupportedOperationException e) {
// all ok
}
doc.getPackage().revert();
doc.close();
}
@Test
public void testGetAllPackagePictures() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx");
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) {
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPackagePictures);
assertEquals(5, allPackagePictures.size());
assertNotNull(allPackagePictures);
assertEquals(5, allPackagePictures.size());
try {
allPackagePictures.add(allPackagePictures.get(0));
fail("This list must be unmodifiable!");
} catch (UnsupportedOperationException e) {
// all ok
try {
allPackagePictures.add(allPackagePictures.get(0));
fail("This list must be unmodifiable!");
} catch (UnsupportedOperationException e) {
// all ok
}
doc.getPackage().revert();
}
doc.getPackage().revert();
doc.close();
}
@Test
public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx");
assertEquals(1, doc.getAllPackagePictures().size());
byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg");
String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG);
assertEquals(2, doc.getAllPackagePictures().size());
/* copy data, to avoid instance-equality */
byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length);
String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG);
assertEquals(id1, id2);
doc.getPackage().revert();
doc.close();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) {
assertEquals(1, doc.getAllPackagePictures().size());
byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg");
String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG);
assertEquals(2, doc.getAllPackagePictures().size());
/* copy data, to avoid instance-equality */
byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length);
String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG);
assertEquals(id1, id2);
doc.getPackage().revert();
}
}
@Test
public void testPictureHandlingHeaderDocumentImages() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx");
assertEquals(1, doc.getAllPictures().size());
assertEquals(1, doc.getAllPackagePictures().size());
assertEquals(1, doc.getHeaderArray(0).getAllPictures().size());
doc.getPackage().revert();
doc.close();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx")) {
assertEquals(1, doc.getAllPictures().size());
assertEquals(1, doc.getAllPackagePictures().size());
assertEquals(1, doc.getHeaderArray(0).getAllPictures().size());
doc.getPackage().revert();
}
}
@Test
public void testPictureHandlingComplex() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx");
XWPFHeader xwpfHeader = doc.getHeaderArray(0);
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) {
XWPFHeader xwpfHeader = doc.getHeaderArray(0);
assertEquals(3, doc.getAllPictures().size());
assertEquals(3, xwpfHeader.getAllPictures().size());
assertEquals(5, doc.getAllPackagePictures().size());
assertEquals(3, doc.getAllPictures().size());
assertEquals(3, xwpfHeader.getAllPictures().size());
assertEquals(5, doc.getAllPackagePictures().size());
byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg");
String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG);
POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1");
XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id);
assertSame(part1, part2);
byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg");
String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG);
POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1");
XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id);
assertSame(part1, part2);
doc.getPackage().revert();
doc.close();
doc.getPackage().revert();
}
}
@Test
public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx");
POIXMLProperties properties = doc.getProperties();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx")) {
POIXMLProperties properties = doc.getProperties();
assertNotNull(properties.getCoreProperties());
assertNotNull(properties.getCoreProperties());
XWPFHeader headerArray = doc.getHeaderArray(0);
assertEquals(1, headerArray.getAllPictures().size());
assertEquals("image1.png", headerArray.pictures.get(0).getFileName());
assertEquals("", headerArray.getText());
XWPFHeader headerArray = doc.getHeaderArray(0);
assertEquals(1, headerArray.getAllPictures().size());
assertEquals("image1.png", headerArray.pictures.get(0).getFileName());
assertEquals("", headerArray.getText());
POIXMLProperties.ExtendedProperties extendedProperties = properties.getExtendedProperties();
assertNotNull(extendedProperties);
assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters());
doc.close();
POIXMLProperties.ExtendedProperties extendedProperties = properties.getExtendedProperties();
assertNotNull(extendedProperties);
assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters());
}
}
@Test
@ -414,14 +420,14 @@ public final class TestXWPFDocument {
assertEquals(100, settings.getZoomPercent());
settings.setZoomPercent(50);
assertEquals(50, settings.getZoomPercent());
assertEquals(false, settings.getEvenAndOddHeadings());
settings.setEvenAndOddHeadings(true);
assertEquals(true, settings.getEvenAndOddHeadings());
assertEquals(false, settings.getMirrorMargins());
assertFalse(settings.getEvenAndOddHeadings());
settings.setEvenAndOddHeadings(true);
assertTrue(settings.getEvenAndOddHeadings());
assertFalse(settings.getMirrorMargins());
settings.setMirrorMargins(true);
assertEquals(true, settings.getMirrorMargins());
assertTrue(settings.getMirrorMargins());
XWPFDocument doc = new XWPFDocument();
assertEquals(100, doc.getZoomPercent());
@ -432,13 +438,13 @@ public final class TestXWPFDocument {
doc.setZoomPercent(200);
assertEquals(200, doc.getZoomPercent());
assertEquals(false, doc.getEvenAndOddHeadings());
assertFalse(doc.getEvenAndOddHeadings());
doc.setEvenAndOddHeadings(true);
assertEquals(true, doc.getEvenAndOddHeadings());
assertTrue(doc.getEvenAndOddHeadings());
assertEquals(false, doc.getMirrorMargins());
assertFalse(doc.getMirrorMargins());
doc.setMirrorMargins(true);
assertEquals(true, doc.getMirrorMargins());
assertTrue(doc.getMirrorMargins());
XWPFDocument back = XWPFTestDataSamples.writeOutAndReadBack(doc);
assertEquals(200, back.getZoomPercent());
@ -453,10 +459,10 @@ public final class TestXWPFDocument {
@Test
public void testEnforcedWith() throws IOException {
XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx");
assertTrue(docx.isEnforcedProtection());
docx.close();
}
try (XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx")) {
assertTrue(docx.isEnforcedProtection());
}
}
@Test
@Ignore("XWPF should be able to write to a new Stream when opened Read-Only")
@ -466,14 +472,15 @@ public final class TestXWPFDocument {
PackageAccess.READ
);
XWPFDocument doc = new XWPFDocument(opc);
XWPFWordExtractor ext = new XWPFWordExtractor(doc);
String origText = ext.getText();
doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
ext.close();
ext = new XWPFWordExtractor(doc);
assertEquals(origText, ext.getText());
ext.close();
}
final String origText;
try (XWPFWordExtractor ext = new XWPFWordExtractor(doc)) {
origText = ext.getText();
doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
}
try (XWPFWordExtractor ext = new XWPFWordExtractor(doc)) {
assertEquals(origText, ext.getText());
}
}
}

View File

@ -790,23 +790,23 @@ public class TestXWPFRun {
@Test
public void testGetDepthWidth() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
XWPFParagraph p = hdr.createParagraph();
XWPFRun r = p.createRun();
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) {
XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
XWPFParagraph p = hdr.createParagraph();
XWPFRun r = p.createRun();
assertEquals(0, hdr.getAllPictures().size());
assertEquals(0, r.getEmbeddedPictures().size());
assertEquals(0, hdr.getAllPictures().size());
assertEquals(0, r.getEmbeddedPictures().size());
r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);
r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);
assertEquals(1, hdr.getAllPictures().size());
assertEquals(1, r.getEmbeddedPictures().size());
assertEquals(1, hdr.getAllPictures().size());
assertEquals(1, r.getEmbeddedPictures().size());
XWPFPicture pic = r.getEmbeddedPictures().get(0);
XWPFPicture pic = r.getEmbeddedPictures().get(0);
assertEquals(pic.getWidth(), Units.toPoints(21), 0.0);
assertEquals(pic.getDepth(), Units.toPoints(32), 0.0);
assertEquals(pic.getWidth(), Units.toPoints(21), 0.0);
assertEquals(pic.getDepth(), Units.toPoints(32), 0.0);
}
}
}

View File

@ -19,12 +19,6 @@
package org.apache.poi.ss.formula;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
@ -32,8 +26,20 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestMissingWorkbook extends TestCase {
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TestMissingWorkbook {
protected Workbook mainWorkbook;
protected Workbook sourceWorkbook;
@ -44,6 +50,7 @@ public class TestMissingWorkbook extends TestCase {
public TestMissingWorkbook() {
this("52575_main.xls", "source_dummy.xls", "52575_source.xls");
}
protected TestMissingWorkbook(String MAIN_WORKBOOK_FILENAME,
String SOURCE_DUMMY_WORKBOOK_FILENAME, String SOURCE_WORKBOOK_FILENAME) {
this.MAIN_WORKBOOK_FILENAME = MAIN_WORKBOOK_FILENAME;
@ -51,8 +58,8 @@ public class TestMissingWorkbook extends TestCase {
this.SOURCE_WORKBOOK_FILENAME = SOURCE_WORKBOOK_FILENAME;
}
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME);
sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME);
@ -60,7 +67,19 @@ public class TestMissingWorkbook extends TestCase {
assertNotNull(sourceWorkbook);
}
public void testMissingWorkbookMissing() throws IOException {
@After
public void tearDown() throws Exception {
if(mainWorkbook != null) {
mainWorkbook.close();
}
if(sourceWorkbook != null) {
sourceWorkbook.close();
}
}
@Test
public void testMissingWorkbookMissing() {
FormulaEvaluator evaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator();
Sheet lSheet = mainWorkbook.getSheetAt(0);
@ -71,12 +90,13 @@ public class TestMissingWorkbook extends TestCase {
try {
evaluator.evaluateFormulaCell(lA1Cell);
fail("Missing external workbook reference exception expected!");
}catch(RuntimeException re) {
} catch(RuntimeException re) {
assertTrue("Unexpected exception: " + re, re.getMessage().contains(SOURCE_DUMMY_WORKBOOK_FILENAME));
}
}
public void testMissingWorkbookMissingOverride() throws IOException {
@Test
public void testMissingWorkbookMissingOverride() {
Sheet lSheet = mainWorkbook.getSheetAt(0);
Cell lA1Cell = lSheet.getRow(0).getCell(0);
Cell lB1Cell = lSheet.getRow(1).getCell(0);
@ -89,7 +109,7 @@ public class TestMissingWorkbook extends TestCase {
// Check cached values
assertEquals(10.0d, lA1Cell.getNumericCellValue(), 0.00001d);
assertEquals("POI rocks!", lB1Cell.getStringCellValue());
assertEquals(true, lC1Cell.getBooleanCellValue());
assertTrue(lC1Cell.getBooleanCellValue());
// Evaluate
FormulaEvaluator evaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator();
@ -101,11 +121,11 @@ public class TestMissingWorkbook extends TestCase {
assertEquals(10.0d, lA1Cell.getNumericCellValue(), 0.00001d);
assertEquals("POI rocks!", lB1Cell.getStringCellValue());
assertEquals(true, lC1Cell.getBooleanCellValue());
assertTrue(lC1Cell.getBooleanCellValue());
}
public void testExistingWorkbook() throws IOException {
@Test
public void testExistingWorkbook() {
Sheet lSheet = mainWorkbook.getSheetAt(0);
Cell lA1Cell = lSheet.getRow(0).getCell(0);
Cell lB1Cell = lSheet.getRow(1).getCell(0);
@ -128,6 +148,6 @@ public class TestMissingWorkbook extends TestCase {
assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d);
assertEquals("Apache rocks!", lB1Cell.getStringCellValue());
assertEquals(false, lC1Cell.getBooleanCellValue());
assertFalse(lC1Cell.getBooleanCellValue());
}
}

View File

@ -30,9 +30,11 @@ import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
@ -42,6 +44,7 @@ import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.LocaleUtil;
import org.junit.After;
import org.junit.Test;
/**
@ -1423,7 +1426,17 @@ public abstract class BaseTestCell {
verify(cell).setBlank();
}
private List<Workbook> workbooksToClose = new ArrayList<>();
@After
public void closeWorkbooks() throws IOException {
for (Workbook workbook : workbooksToClose) {
workbook.close();
}
}
private Cell getInstance() {
return _testDataProvider.createWorkbook().createSheet().createRow(0).createCell(0);
Workbook workbookToClose = _testDataProvider.createWorkbook();
workbooksToClose.add(workbookToClose);
return workbookToClose.createSheet().createRow(0).createCell(0);
}
}