/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.xssf.usermodel; import static org.hamcrest.core.IsEqual.equalTo; 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.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.List; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.POIDataSamples; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLProperties; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.formula.WorkbookEvaluator; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.functions.Function; import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.FormulaError; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.util.TempFile; import org.apache.poi.xssf.XLSBUnsupportedException; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.CalculationChain; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; import org.junit.Ignore; import org.junit.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl; public final class TestXSSFBugs extends BaseTestBugzillaIssues { public TestXSSFBugs() { super(XSSFITestDataProvider.instance); } /** * test writing a file with large number of unique strings, * open resulting file in Excel to check results! */ @Test public void bug15375_2() { bug15375(1000); } /** * Named ranges had the right reference, but * the wrong sheet name */ @Test public void bug45430() { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx"); assertFalse(wb.isMacroEnabled()); assertEquals(3, wb.getNumberOfNames()); assertEquals(0, wb.getNameAt(0).getCTName().getLocalSheetId()); assertFalse(wb.getNameAt(0).getCTName().isSetLocalSheetId()); assertEquals("SheetA!$A$1", wb.getNameAt(0).getRefersToFormula()); assertEquals("SheetA", wb.getNameAt(0).getSheetName()); assertEquals(0, wb.getNameAt(1).getCTName().getLocalSheetId()); assertFalse(wb.getNameAt(1).getCTName().isSetLocalSheetId()); assertEquals("SheetB!$A$1", wb.getNameAt(1).getRefersToFormula()); assertEquals("SheetB", wb.getNameAt(1).getSheetName()); assertEquals(0, wb.getNameAt(2).getCTName().getLocalSheetId()); assertFalse(wb.getNameAt(2).getCTName().isSetLocalSheetId()); assertEquals("SheetC!$A$1", wb.getNameAt(2).getRefersToFormula()); assertEquals("SheetC", wb.getNameAt(2).getSheetName()); // Save and re-load, still there XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); assertEquals(3, nwb.getNumberOfNames()); assertEquals("SheetA!$A$1", nwb.getNameAt(0).getRefersToFormula()); } /** * We should carry vba macros over after save */ @Test public void bug45431() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm"); OPCPackage pkg = wb.getPackage(); assertTrue(wb.isMacroEnabled()); // Check the various macro related bits can be found PackagePart vba = pkg.getPart( PackagingURIHelper.createPartName("/xl/vbaProject.bin") ); assertNotNull(vba); // And the drawing bit PackagePart drw = pkg.getPart( PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") ); assertNotNull(drw); // Save and re-open, both still there XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); OPCPackage nPkg = nwb.getPackage(); assertTrue(nwb.isMacroEnabled()); vba = nPkg.getPart( PackagingURIHelper.createPartName("/xl/vbaProject.bin") ); assertNotNull(vba); drw = nPkg.getPart( PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") ); assertNotNull(drw); // And again, just to be sure nwb = XSSFTestDataSamples.writeOutAndReadBack(nwb); nPkg = nwb.getPackage(); assertTrue(nwb.isMacroEnabled()); vba = nPkg.getPart( PackagingURIHelper.createPartName("/xl/vbaProject.bin") ); assertNotNull(vba); drw = nPkg.getPart( PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") ); assertNotNull(drw); } @Test public void bug47504() { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx"); assertEquals(1, wb.getNumberOfSheets()); XSSFSheet sh = wb.getSheetAt(0); XSSFDrawing drawing = sh.createDrawingPatriarch(); List rels = drawing.getRelations(); assertEquals(1, rels.size()); assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment()); // And again, just to be sure wb = XSSFTestDataSamples.writeOutAndReadBack(wb); assertEquals(1, wb.getNumberOfSheets()); sh = wb.getSheetAt(0); drawing = sh.createDrawingPatriarch(); rels = drawing.getRelations(); assertEquals(1, rels.size()); assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment()); } /** * Excel will sometimes write a button with a textbox * containing >br< (not closed!). * Clearly Excel shouldn't do this, but test that we can * read the file despite the naughtyness */ @Test public void bug49020() throws Exception { /*XSSFWorkbook wb =*/ XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx"); } /** * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas */ @Test public void bug49325() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx"); CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet(); assertNotNull(sh.getPhoneticPr()); } /** * Names which are defined with a Sheet * should return that sheet index properly */ @Test public void bug48923() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx"); assertEquals(4, wb.getNumberOfNames()); Name b1 = wb.getName("NameB1"); Name b2 = wb.getName("NameB2"); Name sheet2 = wb.getName("NameSheet2"); Name test = wb.getName("Test"); assertNotNull(b1); assertEquals("NameB1", b1.getNameName()); assertEquals("Sheet1", b1.getSheetName()); assertEquals(-1, b1.getSheetIndex()); assertNotNull(b2); assertEquals("NameB2", b2.getNameName()); assertEquals("Sheet1", b2.getSheetName()); assertEquals(-1, b2.getSheetIndex()); assertNotNull(sheet2); assertEquals("NameSheet2", sheet2.getNameName()); assertEquals("Sheet2", sheet2.getSheetName()); assertEquals(-1, sheet2.getSheetIndex()); assertNotNull(test); assertEquals("Test", test.getNameName()); assertEquals("Sheet1", test.getSheetName()); assertEquals(-1, test.getSheetIndex()); } /** * Problem with evaluation formulas due to * NameXPtgs. * Blows up on: * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0)) * * TODO: delete this test case when MROUND and VAR are implemented */ @Test public void bug48539() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx"); assertEquals(3, wb.getNumberOfSheets()); assertEquals(0, wb.getNumberOfNames()); // Try each cell individually XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); for(int i=0; i rels0 = sh0.getRelations(); List rels1 = sh1.getRelations(); assertEquals(1, rels0.size()); assertEquals(1, rels1.size()); assertEquals(rels0.get(0).getPackageRelationship(), rels1.get(0).getPackageRelationship()); } /** * Add comments to Sheet 1, when Sheet 2 already has * comments (so /xl/comments1.xml is taken) */ @Test public void bug51850() { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx"); XSSFSheet sh1 = wb.getSheetAt(0); XSSFSheet sh2 = wb.getSheetAt(1); // Sheet 2 has comments assertNotNull(sh2.getCommentsTable(false)); assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); // Sheet 1 doesn't (yet) assertNull(sh1.getCommentsTable(false)); // Try to add comments to Sheet 1 CreationHelper factory = wb.getCreationHelper(); Drawing drawing = sh1.createDrawingPatriarch(); ClientAnchor anchor = factory.createClientAnchor(); anchor.setCol1(0); anchor.setCol2(4); anchor.setRow1(0); anchor.setRow2(1); Comment comment1 = drawing.createCellComment(anchor); comment1.setString( factory.createRichTextString("I like this cell. It's my favourite.")); comment1.setAuthor("Bob T. Fish"); Comment comment2 = drawing.createCellComment(anchor); comment2.setString( factory.createRichTextString("This is much less fun...")); comment2.setAuthor("Bob T. Fish"); Cell c1 = sh1.getRow(0).createCell(4); c1.setCellValue(2.3); c1.setCellComment(comment1); Cell c2 = sh1.getRow(0).createCell(5); c2.setCellValue(2.1); c2.setCellComment(comment2); // Save and re-load wb = XSSFTestDataSamples.writeOutAndReadBack(wb); sh1 = wb.getSheetAt(0); sh2 = wb.getSheetAt(1); // Check the comments assertNotNull(sh2.getCommentsTable(false)); assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); assertNotNull(sh1.getCommentsTable(false)); assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments()); } /** * Sheet names with a , in them */ @Test public void bug51963() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx"); XSSFSheet sheet = wb.getSheetAt(0); assertEquals("Abc,1", sheet.getSheetName()); Name name = wb.getName("Intekon.ProdCodes"); assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula()); AreaReference ref = new AreaReference(name.getRefersToFormula()); assertEquals(0, ref.getFirstCell().getRow()); assertEquals(0, ref.getFirstCell().getCol()); assertEquals(1, ref.getLastCell().getRow()); assertEquals(0, ref.getLastCell().getCol()); } /** * Sum across multiple workbooks * eg =SUM($Sheet1.C1:$Sheet4.C1) * DISABLED As we can't currently evaluate these */ @Ignore public void bug48703() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx"); XSSFSheet sheet = wb.getSheetAt(0); // Contains two forms, one with a range and one a list XSSFRow r1 = sheet.getRow(0); XSSFRow r2 = sheet.getRow(1); XSSFCell c1 = r1.getCell(1); XSSFCell c2 = r2.getCell(1); assertEquals(20.0, c1.getNumericCellValue(), 0); assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula()); assertEquals(20.0, c2.getNumericCellValue(), 0); assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula()); // Try evaluating both XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); eval.evaluateFormulaCell(c1); eval.evaluateFormulaCell(c2); assertEquals(20.0, c1.getNumericCellValue(), 0); assertEquals(20.0, c2.getNumericCellValue(), 0); } /** * Bugzilla 51710: problems reading shared formuals from .xlsx */ @Test public void bug51710() { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx"); final String[] columns = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"}; final int rowMax = 500; // bug triggers on row index 59 Sheet sheet = wb.getSheetAt(0); // go through all formula cells for (int rInd = 2; rInd <= rowMax; rInd++) { Row row = sheet.getRow(rInd); for (int cInd = 1; cInd <= 12; cInd++) { Cell cell = row.getCell(cInd); String formula = cell.getCellFormula(); CellReference ref = new CellReference(cell); //simulate correct answer String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2"; assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula); } } } /** * Bug 53101: */ @Test public void bug5301(){ Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx"); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); // A1: SUM(B1: IZ1) double a1Value = evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(0)).getNumberValue(); // Assert assertEquals(259.0, a1Value, 0.0); // KY: SUM(B1: IZ1) /*double ky1Value =*/ evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(310)).getNumberValue(); // Assert assertEquals(259.0, a1Value, 0.0); } @Test public void bug54436(){ Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx"); if(!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")){ Function func = new Function() { public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { return ErrorEval.NA; } }; WorkbookEvaluator.registerFunction("GETPIVOTDATA", func); } workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); } /** * Password Protected .xlsx files should give a helpful * error message when called via WorkbookFactory. * (You need to supply a password explicitly for them) */ @Test(expected=EncryptedDocumentException.class) public void bug55692_stream() throws Exception { // Directly on a Stream WorkbookFactory.create(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); } @Test(expected=EncryptedDocumentException.class) public void bug55692_poifs() throws Exception { // Via a POIFSFileSystem POIFSFileSystem fsP = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); WorkbookFactory.create(fsP); } @Test(expected=EncryptedDocumentException.class) public void bug55692_npoifs() throws Exception { // Via a NPOIFSFileSystem NPOIFSFileSystem fsNP = new NPOIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); WorkbookFactory.create(fsNP); } @Test public void bug53282() { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx"); Cell c = wb.getSheetAt(0).getRow(1).getCell(0); assertEquals("#@_#", c.getStringCellValue()); assertEquals("http://invalid.uri", c.getHyperlink().getAddress()); } /** * Was giving NullPointerException * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead * due to a lack of Styles Table */ @Test public void bug56278() throws Exception { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx"); assertEquals(0, wb.getSheetIndex("Market Rates")); // Save and re-check Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); assertEquals(0, nwb.getSheetIndex("Market Rates")); } @Test public void bug56315() { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx"); Cell c = wb.getSheetAt(0).getRow(1).getCell(0); CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c); double rounded = cv.getNumberValue(); assertEquals(0.1, rounded, 0.0); } @Test public void bug56468() throws Exception { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("Hi"); sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0)); ByteArrayOutputStream bos = new ByteArrayOutputStream(8096); wb.write(bos); byte firstSave[] = bos.toByteArray(); bos.reset(); wb.write(bos); byte secondSave[] = bos.toByteArray(); assertThat(firstSave, equalTo(secondSave)); wb.close(); } /** * ISO-8601 style cell formats with a T in them, eg * cell format of "yyyy-MM-ddTHH:mm:ss" */ @Test public void bug54034() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx"); Sheet sheet = wb.getSheet("Sheet1"); Row row = sheet.getRow(1); Cell cell = row.getCell(2); assertTrue(DateUtil.isCellDateFormatted(cell)); DataFormatter fmt = new DataFormatter(); assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); } @Test public void testBug53798XLSX() throws IOException { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx"); File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); bug53798Work(wb, xlsOutput); } @Ignore("Shifting rows is not yet implemented in SXSSFSheet") @Test public void testBug53798XLSXStream() throws IOException { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx"); File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); bug53798Work(new SXSSFWorkbook(wb), xlsOutput); } @Test public void testBug53798XLS() throws IOException { Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls"); File xlsOutput = TempFile.createTempFile("testBug53798", ".xls"); bug53798Work(wb, xlsOutput); } /** * SUMIF was throwing a NPE on some formulas */ @Test @Ignore("This bug is still to be fixed") public void testBug56420SumIfNPE() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx"); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); Sheet sheet = wb.getSheetAt(0); Row r = sheet.getRow(2); Cell c = r.getCell(2); assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula()); evaluator.evaluateInCell(c); } private void bug53798Work(Workbook wb, File xlsOutput) throws IOException { Sheet testSheet = wb.getSheetAt(0); testSheet.shiftRows(2, 2, 1); saveAndReloadReport(wb, xlsOutput); // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about // when shifted by less than -1 negative amount (try -2) testSheet.shiftRows(3, 3, -1); saveAndReloadReport(wb, xlsOutput); testSheet.shiftRows(2, 2, 1); saveAndReloadReport(wb, xlsOutput); Row newRow = null; Cell newCell = null; // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted // xlsx file with unreadable data in the negative shifted row. // NOTE it's ok to create any other row. newRow = testSheet.createRow(3); saveAndReloadReport(wb, xlsOutput); newCell = newRow.createCell(0); saveAndReloadReport(wb, xlsOutput); newCell.setCellValue("new Cell in row "+newRow.getRowNum()); saveAndReloadReport(wb, xlsOutput); // 3) once a negative shift has been made any attempt to shift another group of rows // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. // NOTE: another negative shift on another group of rows is successful, provided no new rows in // place of previously shifted rows were attempted to be created as explained above. testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of // the above has been tested saveAndReloadReport(wb, xlsOutput); } /** * XSSFCell.typeMismatch on certain blank cells when formatting * with DataFormatter */ @Test public void bug56702() throws Exception { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx"); Sheet sheet = wb.getSheetAt(0); // Get wrong cell by row 8 & column 7 Cell cell = sheet.getRow(8).getCell(7); assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType()); // Check the value - will be zero as it is assertEquals(0.0, cell.getNumericCellValue(), 0.001); // Try to format DataFormatter formatter = new DataFormatter(); formatter.formatCellValue(cell); // Check the formatting assertEquals("0", formatter.formatCellValue(cell)); } /** * Formulas which reference named ranges, either in other * sheets, or workbook scoped but in other workbooks. * Used to fail with with errors like * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9 * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name */ @Test public void bug56737() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); // Check the named range definitions Name nSheetScope = wb.getName("NR_To_A1"); Name nWBScope = wb.getName("NR_Global_B2"); assertNotNull(nSheetScope); assertNotNull(nWBScope); assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); // Check the different kinds of formulas Sheet s = wb.getSheetAt(0); Cell cRefSName = s.getRow(1).getCell(3); Cell cRefWName = s.getRow(2).getCell(3); assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); // Note the formula, as stored in the file, has the external name index not filename // TODO Provide a way to get the one with the filename assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula()); // Try to evaluate them FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue()); // Try to evaluate everything eval.evaluateAll(); } private void saveAndReloadReport(Workbook wb, File outFile) throws IOException { // run some method on the font to verify if it is "disconnected" already //for(short i = 0;i < 256;i++) { Font font = wb.getFontAt((short)0); if(font instanceof XSSFFont) { XSSFFont xfont = (XSSFFont) wb.getFontAt((short)0); CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont(); assertEquals(0, ctFont.sizeOfBArray()); } } FileOutputStream fileOutStream = new FileOutputStream(outFile); wb.write(fileOutStream); fileOutStream.close(); //System.out.println("File \""+outFile.getName()+"\" has been saved successfully"); FileInputStream is = new FileInputStream(outFile); try { Workbook newWB = null; try { if(wb instanceof XSSFWorkbook) { newWB = new XSSFWorkbook(is); } else if(wb instanceof HSSFWorkbook) { newWB = new HSSFWorkbook(is); } else if(wb instanceof SXSSFWorkbook) { newWB = new SXSSFWorkbook(new XSSFWorkbook(is)); } else { throw new IllegalStateException("Unknown workbook: " + wb); } assertNotNull(newWB.getSheet("test")); } finally { newWB.close(); } } finally { is.close(); } } @Test public void testBug56688_1() { XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx"); checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */ } @Test public void testBug56688_2() { XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx"); checkValue(excel, "#VALUE!"); } @Test public void testBug56688_3() { XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx"); checkValue(excel, "#VALUE!"); } @Test public void testBug56688_4() { XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx"); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 2); double excelDate = DateUtil.getExcelDate(calendar.getTime()); NumberEval eval = new NumberEval(Math.floor(excelDate)); checkValue(excel, eval.getStringValue() + ".0"); } /** * New hyperlink with no initial cell reference, still need * to be able to change it */ @Test public void testBug56527() { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFCreationHelper creationHelper = wb.getCreationHelper(); XSSFHyperlink hyperlink; // Try with a cell reference hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL); sheet.addHyperlink(hyperlink); hyperlink.setAddress("http://myurl"); hyperlink.setCellReference("B4"); assertEquals(3, hyperlink.getFirstRow()); assertEquals(1, hyperlink.getFirstColumn()); assertEquals(3, hyperlink.getLastRow()); assertEquals(1, hyperlink.getLastColumn()); // Try with explicit rows / columns hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL); sheet.addHyperlink(hyperlink); hyperlink.setAddress("http://myurl"); hyperlink.setFirstRow(5); hyperlink.setFirstColumn(3); assertEquals(5, hyperlink.getFirstRow()); assertEquals(3, hyperlink.getFirstColumn()); assertEquals(5, hyperlink.getLastRow()); assertEquals(3, hyperlink.getLastColumn()); } /** * Shifting rows with a formula that references a * function in another file */ @Test public void bug56502() throws Exception { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx"); Sheet sheet = wb.getSheetAt(0); Cell cFunc = sheet.getRow(3).getCell(0); assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); Cell cRef = sheet.getRow(3).createCell(1); cRef.setCellFormula("A3"); // Shift it down one row sheet.shiftRows(1, sheet.getLastRowNum(), 1); // Check the new formulas: Function won't change, Reference will cFunc = sheet.getRow(4).getCell(0); assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); cRef = sheet.getRow(4).getCell(1); assertEquals("A4", cRef.getCellFormula()); } @Test public void bug54764() throws Exception { OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx"); // Check the core properties - will be found but empty, due // to the expansion being too much to be considered valid POIXMLProperties props = new POIXMLProperties(pkg); assertEquals(null, props.getCoreProperties().getTitle()); assertEquals(null, props.getCoreProperties().getSubject()); assertEquals(null, props.getCoreProperties().getDescription()); // Now check the spreadsheet itself // TODO Fix then enable /* try { new XSSFWorkbook(pkg); fail("Should fail as too much expansion occurs"); } catch(POIXMLException e) { // Expected } */ // Try with one with the entities in the Content Types try { XSSFTestDataSamples.openSamplePackage("54764-2.xlsx"); fail("Should fail as too much expansion occurs"); } catch(Exception e) { // Expected } } /** * .xlsb files are not supported, but we should generate a helpful * error message if given one */ @Test public void bug56800_xlsb() throws Exception { // Can be opened at the OPC level OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb"); // XSSF Workbook gives helpful error try { new XSSFWorkbook(pkg); fail(".xlsb files not supported"); } catch (XLSBUnsupportedException e) { // Good, detected and warned } // Workbook Factory gives helpful error on package try { WorkbookFactory.create(pkg); fail(".xlsb files not supported"); } catch (XLSBUnsupportedException e) { // Good, detected and warned } // Workbook Factory gives helpful error on file File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb"); try { WorkbookFactory.create(xlsbFile); fail(".xlsb files not supported"); } catch (XLSBUnsupportedException e) { // Good, detected and warned } } private void checkValue(XSSFWorkbook excel, String expect) { XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel); evaluator.evaluateAll(); XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1); CellValue value = evaluator.evaluate(cell); assertEquals(expect, value.formatAsString()); } }