You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestXSSFBugs.java 72KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.usermodel;
  16. import static org.hamcrest.core.IsEqual.equalTo;
  17. import static org.junit.Assert.assertEquals;
  18. import static org.junit.Assert.assertFalse;
  19. import static org.junit.Assert.assertNotNull;
  20. import static org.junit.Assert.assertNull;
  21. import static org.junit.Assert.assertThat;
  22. import static org.junit.Assert.assertTrue;
  23. import static org.junit.Assert.fail;
  24. import java.io.ByteArrayInputStream;
  25. import java.io.ByteArrayOutputStream;
  26. import java.io.File;
  27. import java.io.FileInputStream;
  28. import java.io.FileOutputStream;
  29. import java.io.IOException;
  30. import java.util.Calendar;
  31. import java.util.List;
  32. import org.apache.poi.EncryptedDocumentException;
  33. import org.apache.poi.POIDataSamples;
  34. import org.apache.poi.POIXMLDocumentPart;
  35. import org.apache.poi.POIXMLException;
  36. import org.apache.poi.POIXMLProperties;
  37. import org.apache.poi.hssf.HSSFTestDataSamples;
  38. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  39. import org.apache.poi.openxml4j.opc.OPCPackage;
  40. import org.apache.poi.openxml4j.opc.PackagePart;
  41. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  42. import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
  43. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  44. import org.apache.poi.ss.formula.WorkbookEvaluator;
  45. import org.apache.poi.ss.formula.eval.ErrorEval;
  46. import org.apache.poi.ss.formula.eval.NumberEval;
  47. import org.apache.poi.ss.formula.eval.ValueEval;
  48. import org.apache.poi.ss.formula.functions.Function;
  49. import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
  50. import org.apache.poi.ss.usermodel.Cell;
  51. import org.apache.poi.ss.usermodel.CellStyle;
  52. import org.apache.poi.ss.usermodel.CellValue;
  53. import org.apache.poi.ss.usermodel.ClientAnchor;
  54. import org.apache.poi.ss.usermodel.Comment;
  55. import org.apache.poi.ss.usermodel.CreationHelper;
  56. import org.apache.poi.ss.usermodel.DataFormatter;
  57. import org.apache.poi.ss.usermodel.DateUtil;
  58. import org.apache.poi.ss.usermodel.Drawing;
  59. import org.apache.poi.ss.usermodel.Font;
  60. import org.apache.poi.ss.usermodel.FormulaError;
  61. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  62. import org.apache.poi.ss.usermodel.Hyperlink;
  63. import org.apache.poi.ss.usermodel.IndexedColors;
  64. import org.apache.poi.ss.usermodel.Name;
  65. import org.apache.poi.ss.usermodel.Row;
  66. import org.apache.poi.ss.usermodel.Sheet;
  67. import org.apache.poi.ss.usermodel.Workbook;
  68. import org.apache.poi.ss.usermodel.WorkbookFactory;
  69. import org.apache.poi.ss.util.AreaReference;
  70. import org.apache.poi.ss.util.CellRangeAddress;
  71. import org.apache.poi.ss.util.CellReference;
  72. import org.apache.poi.util.TempFile;
  73. import org.apache.poi.xssf.XLSBUnsupportedException;
  74. import org.apache.poi.xssf.XSSFITestDataProvider;
  75. import org.apache.poi.xssf.XSSFTestDataSamples;
  76. import org.apache.poi.xssf.model.CalculationChain;
  77. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  78. import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
  79. import org.junit.Ignore;
  80. import org.junit.Test;
  81. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
  82. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  83. import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl;
  84. public final class TestXSSFBugs extends BaseTestBugzillaIssues {
  85. public TestXSSFBugs() {
  86. super(XSSFITestDataProvider.instance);
  87. }
  88. /**
  89. * test writing a file with large number of unique strings,
  90. * open resulting file in Excel to check results!
  91. */
  92. @Test
  93. public void bug15375_2() {
  94. bug15375(1000);
  95. }
  96. /**
  97. * Named ranges had the right reference, but
  98. * the wrong sheet name
  99. */
  100. @Test
  101. public void bug45430() {
  102. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx");
  103. assertFalse(wb.isMacroEnabled());
  104. assertEquals(3, wb.getNumberOfNames());
  105. assertEquals(0, wb.getNameAt(0).getCTName().getLocalSheetId());
  106. assertFalse(wb.getNameAt(0).getCTName().isSetLocalSheetId());
  107. assertEquals("SheetA!$A$1", wb.getNameAt(0).getRefersToFormula());
  108. assertEquals("SheetA", wb.getNameAt(0).getSheetName());
  109. assertEquals(0, wb.getNameAt(1).getCTName().getLocalSheetId());
  110. assertFalse(wb.getNameAt(1).getCTName().isSetLocalSheetId());
  111. assertEquals("SheetB!$A$1", wb.getNameAt(1).getRefersToFormula());
  112. assertEquals("SheetB", wb.getNameAt(1).getSheetName());
  113. assertEquals(0, wb.getNameAt(2).getCTName().getLocalSheetId());
  114. assertFalse(wb.getNameAt(2).getCTName().isSetLocalSheetId());
  115. assertEquals("SheetC!$A$1", wb.getNameAt(2).getRefersToFormula());
  116. assertEquals("SheetC", wb.getNameAt(2).getSheetName());
  117. // Save and re-load, still there
  118. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  119. assertEquals(3, nwb.getNumberOfNames());
  120. assertEquals("SheetA!$A$1", nwb.getNameAt(0).getRefersToFormula());
  121. }
  122. /**
  123. * We should carry vba macros over after save
  124. */
  125. @Test
  126. public void bug45431() throws Exception {
  127. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm");
  128. OPCPackage pkg = wb.getPackage();
  129. assertTrue(wb.isMacroEnabled());
  130. // Check the various macro related bits can be found
  131. PackagePart vba = pkg.getPart(
  132. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  133. );
  134. assertNotNull(vba);
  135. // And the drawing bit
  136. PackagePart drw = pkg.getPart(
  137. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  138. );
  139. assertNotNull(drw);
  140. // Save and re-open, both still there
  141. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  142. OPCPackage nPkg = nwb.getPackage();
  143. assertTrue(nwb.isMacroEnabled());
  144. vba = nPkg.getPart(
  145. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  146. );
  147. assertNotNull(vba);
  148. drw = nPkg.getPart(
  149. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  150. );
  151. assertNotNull(drw);
  152. // And again, just to be sure
  153. nwb = XSSFTestDataSamples.writeOutAndReadBack(nwb);
  154. nPkg = nwb.getPackage();
  155. assertTrue(nwb.isMacroEnabled());
  156. vba = nPkg.getPart(
  157. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  158. );
  159. assertNotNull(vba);
  160. drw = nPkg.getPart(
  161. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  162. );
  163. assertNotNull(drw);
  164. }
  165. @Test
  166. public void bug47504() {
  167. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx");
  168. assertEquals(1, wb.getNumberOfSheets());
  169. XSSFSheet sh = wb.getSheetAt(0);
  170. XSSFDrawing drawing = sh.createDrawingPatriarch();
  171. List<POIXMLDocumentPart> rels = drawing.getRelations();
  172. assertEquals(1, rels.size());
  173. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  174. // And again, just to be sure
  175. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  176. assertEquals(1, wb.getNumberOfSheets());
  177. sh = wb.getSheetAt(0);
  178. drawing = sh.createDrawingPatriarch();
  179. rels = drawing.getRelations();
  180. assertEquals(1, rels.size());
  181. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  182. }
  183. /**
  184. * Excel will sometimes write a button with a textbox
  185. * containing &gt;br&lt; (not closed!).
  186. * Clearly Excel shouldn't do this, but test that we can
  187. * read the file despite the naughtyness
  188. */
  189. @Test
  190. public void bug49020() throws Exception {
  191. /*XSSFWorkbook wb =*/ XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx");
  192. }
  193. /**
  194. * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas
  195. */
  196. @Test
  197. public void bug49325() throws Exception {
  198. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx");
  199. CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet();
  200. assertNotNull(sh.getPhoneticPr());
  201. }
  202. /**
  203. * Names which are defined with a Sheet
  204. * should return that sheet index properly
  205. */
  206. @Test
  207. public void bug48923() throws Exception {
  208. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx");
  209. assertEquals(4, wb.getNumberOfNames());
  210. Name b1 = wb.getName("NameB1");
  211. Name b2 = wb.getName("NameB2");
  212. Name sheet2 = wb.getName("NameSheet2");
  213. Name test = wb.getName("Test");
  214. assertNotNull(b1);
  215. assertEquals("NameB1", b1.getNameName());
  216. assertEquals("Sheet1", b1.getSheetName());
  217. assertEquals(-1, b1.getSheetIndex());
  218. assertNotNull(b2);
  219. assertEquals("NameB2", b2.getNameName());
  220. assertEquals("Sheet1", b2.getSheetName());
  221. assertEquals(-1, b2.getSheetIndex());
  222. assertNotNull(sheet2);
  223. assertEquals("NameSheet2", sheet2.getNameName());
  224. assertEquals("Sheet2", sheet2.getSheetName());
  225. assertEquals(-1, sheet2.getSheetIndex());
  226. assertNotNull(test);
  227. assertEquals("Test", test.getNameName());
  228. assertEquals("Sheet1", test.getSheetName());
  229. assertEquals(-1, test.getSheetIndex());
  230. }
  231. /**
  232. * Problem with evaluation formulas due to
  233. * NameXPtgs.
  234. * Blows up on:
  235. * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0))
  236. *
  237. * TODO: delete this test case when MROUND and VAR are implemented
  238. */
  239. @Test
  240. public void bug48539() throws Exception {
  241. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx");
  242. assertEquals(3, wb.getNumberOfSheets());
  243. assertEquals(0, wb.getNumberOfNames());
  244. // Try each cell individually
  245. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  246. for(int i=0; i<wb.getNumberOfSheets(); i++) {
  247. Sheet s = wb.getSheetAt(i);
  248. for(Row r : s) {
  249. for(Cell c : r) {
  250. if(c.getCellType() == Cell.CELL_TYPE_FORMULA) {
  251. String formula = c.getCellFormula();
  252. CellValue cv;
  253. try {
  254. cv = eval.evaluate(c);
  255. } catch (Exception e) {
  256. throw new RuntimeException("Can't evaluate formula: " + formula, e);
  257. }
  258. if(cv.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  259. // assert that the calculated value agrees with
  260. // the cached formula result calculated by Excel
  261. double cachedFormulaResult = c.getNumericCellValue();
  262. double evaluatedFormulaResult = cv.getNumberValue();
  263. assertEquals(c.getCellFormula(), cachedFormulaResult, evaluatedFormulaResult, 1E-7);
  264. }
  265. }
  266. }
  267. }
  268. }
  269. // Now all of them
  270. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  271. }
  272. /**
  273. * Foreground colours should be found even if
  274. * a theme is used
  275. */
  276. @Test
  277. public void bug48779() throws Exception {
  278. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx");
  279. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  280. XSSFCellStyle cs = cell.getCellStyle();
  281. assertNotNull(cs);
  282. assertEquals(1, cs.getIndex());
  283. // Look at the low level xml elements
  284. assertEquals(2, cs.getCoreXf().getFillId());
  285. assertEquals(0, cs.getCoreXf().getXfId());
  286. assertEquals(true, cs.getCoreXf().getApplyFill());
  287. XSSFCellFill fg = wb.getStylesSource().getFillAt(2);
  288. assertEquals(0, fg.getFillForegroundColor().getIndexed());
  289. assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0);
  290. assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex());
  291. assertEquals(64, fg.getFillBackgroundColor().getIndexed());
  292. // Now look higher up
  293. assertNotNull(cs.getFillForegroundXSSFColor());
  294. assertEquals(0, cs.getFillForegroundColor());
  295. assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex());
  296. assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex());
  297. assertNotNull(cs.getFillBackgroundColor());
  298. assertEquals(64, cs.getFillBackgroundColor());
  299. assertEquals(null, cs.getFillBackgroundXSSFColor().getARGBHex());
  300. assertEquals(null, cs.getFillBackgroundColorColor().getARGBHex());
  301. }
  302. /**
  303. * With HSSF, if you create a font, don't change it, and
  304. * create a 2nd, you really do get two fonts that you
  305. * can alter as and when you want.
  306. * With XSSF, that wasn't the case, but this verfies
  307. * that it now is again
  308. */
  309. @Test
  310. public void bug48718() throws Exception {
  311. // Verify the HSSF behaviour
  312. // Then ensure the same for XSSF
  313. Workbook[] wbs = new Workbook[] {
  314. new HSSFWorkbook(),
  315. new XSSFWorkbook()
  316. };
  317. int[] initialFonts = new int[] { 4, 1 };
  318. for(int i=0; i<wbs.length; i++) {
  319. Workbook wb = wbs[i];
  320. int startingFonts = initialFonts[i];
  321. assertEquals(startingFonts, wb.getNumberOfFonts());
  322. // Get a font, and slightly change it
  323. Font a = wb.createFont();
  324. assertEquals(startingFonts+1, wb.getNumberOfFonts());
  325. a.setFontHeightInPoints((short)23);
  326. assertEquals(startingFonts+1, wb.getNumberOfFonts());
  327. // Get two more, unchanged
  328. /*Font b =*/ wb.createFont();
  329. assertEquals(startingFonts+2, wb.getNumberOfFonts());
  330. /*Font c =*/ wb.createFont();
  331. assertEquals(startingFonts+3, wb.getNumberOfFonts());
  332. }
  333. }
  334. /**
  335. * Ensure General and @ format are working properly
  336. * for integers
  337. */
  338. @Test
  339. public void bug47490() throws Exception {
  340. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx");
  341. Sheet s = wb.getSheetAt(1);
  342. Row r;
  343. DataFormatter df = new DataFormatter();
  344. r = s.getRow(1);
  345. assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0);
  346. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  347. assertEquals("1", df.formatCellValue(r.getCell(2)));
  348. assertEquals("1", df.formatRawCellContents(1.0, -1, "@"));
  349. assertEquals("1", df.formatRawCellContents(1.0, -1, "General"));
  350. r = s.getRow(2);
  351. assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0);
  352. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  353. assertEquals("12", df.formatCellValue(r.getCell(2)));
  354. assertEquals("12", df.formatRawCellContents(12.0, -1, "@"));
  355. assertEquals("12", df.formatRawCellContents(12.0, -1, "General"));
  356. r = s.getRow(3);
  357. assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0);
  358. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  359. assertEquals("123", df.formatCellValue(r.getCell(2)));
  360. assertEquals("123", df.formatRawCellContents(123.0, -1, "@"));
  361. assertEquals("123", df.formatRawCellContents(123.0, -1, "General"));
  362. }
  363. /**
  364. * Ensures that XSSF and HSSF agree with each other,
  365. * and with the docs on when fetching the wrong
  366. * kind of value from a Formula cell
  367. */
  368. @Test
  369. public void bug47815() {
  370. Workbook[] wbs = new Workbook[] {
  371. new HSSFWorkbook(),
  372. new XSSFWorkbook()
  373. };
  374. for(Workbook wb : wbs) {
  375. Sheet s = wb.createSheet();
  376. Row r = s.createRow(0);
  377. // Setup
  378. Cell cn = r.createCell(0, Cell.CELL_TYPE_NUMERIC);
  379. cn.setCellValue(1.2);
  380. Cell cs = r.createCell(1, Cell.CELL_TYPE_STRING);
  381. cs.setCellValue("Testing");
  382. Cell cfn = r.createCell(2, Cell.CELL_TYPE_FORMULA);
  383. cfn.setCellFormula("A1");
  384. Cell cfs = r.createCell(3, Cell.CELL_TYPE_FORMULA);
  385. cfs.setCellFormula("B1");
  386. FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
  387. assertEquals(Cell.CELL_TYPE_NUMERIC, fe.evaluate(cfn).getCellType());
  388. assertEquals(Cell.CELL_TYPE_STRING, fe.evaluate(cfs).getCellType());
  389. fe.evaluateFormulaCell(cfn);
  390. fe.evaluateFormulaCell(cfs);
  391. // Now test
  392. assertEquals(Cell.CELL_TYPE_NUMERIC, cn.getCellType());
  393. assertEquals(Cell.CELL_TYPE_STRING, cs.getCellType());
  394. assertEquals(Cell.CELL_TYPE_FORMULA, cfn.getCellType());
  395. assertEquals(Cell.CELL_TYPE_NUMERIC, cfn.getCachedFormulaResultType());
  396. assertEquals(Cell.CELL_TYPE_FORMULA, cfs.getCellType());
  397. assertEquals(Cell.CELL_TYPE_STRING, cfs.getCachedFormulaResultType());
  398. // Different ways of retrieving
  399. assertEquals(1.2, cn.getNumericCellValue(), 0);
  400. try {
  401. cn.getRichStringCellValue();
  402. fail();
  403. } catch(IllegalStateException e) {}
  404. assertEquals("Testing", cs.getStringCellValue());
  405. try {
  406. cs.getNumericCellValue();
  407. fail();
  408. } catch(IllegalStateException e) {}
  409. assertEquals(1.2, cfn.getNumericCellValue(), 0);
  410. try {
  411. cfn.getRichStringCellValue();
  412. fail();
  413. } catch(IllegalStateException e) {}
  414. assertEquals("Testing", cfs.getStringCellValue());
  415. try {
  416. cfs.getNumericCellValue();
  417. fail();
  418. } catch(IllegalStateException e) {}
  419. }
  420. }
  421. /**
  422. * A problem file from a non-standard source (a scientific instrument that saves its
  423. * output as an .xlsx file) that have two issues:
  424. * 1. The Content Type part name is lower-case: [content_types].xml
  425. * 2. The file appears to use backslashes as path separators
  426. *
  427. * The OPC spec tolerates both of these peculiarities, so does POI
  428. */
  429. @Test
  430. public void bug49609() throws Exception {
  431. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx");
  432. assertEquals("FAM", wb.getSheetName(0));
  433. assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
  434. }
  435. @Test
  436. public void bug49783() throws Exception {
  437. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx");
  438. Sheet sheet = wb.getSheetAt(0);
  439. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  440. Cell cell;
  441. cell = sheet.getRow(0).getCell(0);
  442. assertEquals("#REF!*#REF!", cell.getCellFormula());
  443. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  444. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  445. Name nm1 = wb.getName("sale_1");
  446. assertNotNull("name sale_1 should be present", nm1);
  447. assertEquals("Sheet1!#REF!", nm1.getRefersToFormula());
  448. Name nm2 = wb.getName("sale_2");
  449. assertNotNull("name sale_2 should be present", nm2);
  450. assertEquals("Sheet1!#REF!", nm2.getRefersToFormula());
  451. cell = sheet.getRow(1).getCell(0);
  452. assertEquals("sale_1*sale_2", cell.getCellFormula());
  453. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  454. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  455. }
  456. /**
  457. * Creating a rich string of "hello world" and applying
  458. * a font to characters 1-5 means we have two strings,
  459. * "hello" and " world". As such, we need to apply
  460. * preserve spaces to the 2nd bit, lest we end up
  461. * with something like "helloworld" !
  462. */
  463. @Test
  464. public void bug49941() throws Exception {
  465. XSSFWorkbook wb = new XSSFWorkbook();
  466. XSSFSheet s = wb.createSheet();
  467. XSSFRow r = s.createRow(0);
  468. XSSFCell c = r.createCell(0);
  469. // First without fonts
  470. c.setCellValue(
  471. new XSSFRichTextString(" with spaces ")
  472. );
  473. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  474. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  475. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  476. // Should have the preserve set
  477. assertEquals(
  478. 1,
  479. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  480. );
  481. assertEquals(
  482. "preserve",
  483. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  484. );
  485. // Save and check
  486. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  487. s = wb.getSheetAt(0);
  488. r = s.getRow(0);
  489. c = r.getCell(0);
  490. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  491. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  492. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  493. // Change the string
  494. c.setCellValue(
  495. new XSSFRichTextString("hello world")
  496. );
  497. assertEquals("hello world", c.getRichStringCellValue().toString());
  498. // Won't have preserve
  499. assertEquals(
  500. 0,
  501. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  502. );
  503. // Apply a font
  504. XSSFFont f = wb.createFont();
  505. f.setBold(true);
  506. c.getRichStringCellValue().applyFont(0, 5, f);
  507. assertEquals("hello world", c.getRichStringCellValue().toString());
  508. // Does need preserving on the 2nd part
  509. assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  510. assertEquals(
  511. 0,
  512. c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
  513. );
  514. assertEquals(
  515. 1,
  516. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
  517. );
  518. assertEquals(
  519. "preserve",
  520. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  521. );
  522. // Save and check
  523. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  524. s = wb.getSheetAt(0);
  525. r = s.getRow(0);
  526. c = r.getCell(0);
  527. assertEquals("hello world", c.getRichStringCellValue().toString());
  528. wb.close();
  529. }
  530. /**
  531. * Repeatedly writing the same file which has styles
  532. */
  533. @Test
  534. public void bug49940() throws Exception {
  535. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx");
  536. assertEquals(3, wb.getNumberOfSheets());
  537. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  538. ByteArrayOutputStream b1 = new ByteArrayOutputStream();
  539. ByteArrayOutputStream b2 = new ByteArrayOutputStream();
  540. ByteArrayOutputStream b3 = new ByteArrayOutputStream();
  541. wb.write(b1);
  542. wb.write(b2);
  543. wb.write(b3);
  544. for(byte[] data : new byte[][] {
  545. b1.toByteArray(), b2.toByteArray(), b3.toByteArray()
  546. }) {
  547. ByteArrayInputStream bais = new ByteArrayInputStream(data);
  548. wb = new XSSFWorkbook(bais);
  549. assertEquals(3, wb.getNumberOfSheets());
  550. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  551. }
  552. }
  553. /**
  554. * Various ways of removing a cell formula should all zap the calcChain
  555. * entry.
  556. */
  557. @Test
  558. public void bug49966() throws Exception {
  559. XSSFWorkbook wb = XSSFTestDataSamples
  560. .openSampleWorkbook("shared_formulas.xlsx");
  561. XSSFSheet sheet = wb.getSheetAt(0);
  562. Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  563. // CalcChain has lots of entries
  564. CalculationChain cc = wb.getCalculationChain();
  565. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  566. assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR());
  567. assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR());
  568. assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR());
  569. assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR());
  570. assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR());
  571. assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR());
  572. assertEquals(40, cc.getCTCalcChain().sizeOfCArray());
  573. wbRead.close();
  574. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  575. // Try various ways of changing the formulas
  576. // If it stays a formula, chain entry should remain
  577. // Otherwise should go
  578. sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay
  579. sheet.getRow(2).getCell(0).setCellFormula(null); // go
  580. sheet.getRow(3).getCell(0).setCellType(Cell.CELL_TYPE_FORMULA); // stay
  581. wbRead.close();
  582. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  583. sheet.getRow(4).getCell(0).setCellType(Cell.CELL_TYPE_STRING); // go
  584. wbRead.close();
  585. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  586. validateCells(sheet);
  587. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  588. validateCells(sheet);
  589. wbRead.close();
  590. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  591. sheet.getRow(6).getCell(0).setCellType(Cell.CELL_TYPE_BLANK); // go
  592. wbRead.close();
  593. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  594. sheet.getRow(7).getCell(0).setCellValue((String) null); // go
  595. wbRead.close();
  596. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  597. // Save and check
  598. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  599. assertEquals(35, cc.getCTCalcChain().sizeOfCArray());
  600. cc = wb.getCalculationChain();
  601. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  602. assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR());
  603. assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR());
  604. wbRead.close();
  605. }
  606. @Test
  607. public void bug49966Row() throws Exception {
  608. XSSFWorkbook wb = XSSFTestDataSamples
  609. .openSampleWorkbook("shared_formulas.xlsx");
  610. XSSFSheet sheet = wb.getSheetAt(0);
  611. validateCells(sheet);
  612. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  613. validateCells(sheet);
  614. }
  615. private void validateCells(XSSFSheet sheet) {
  616. for(Row row : sheet) {
  617. // trigger handling
  618. ((XSSFRow)row).onDocumentWrite();
  619. }
  620. }
  621. @Test
  622. public void bug49156() throws Exception {
  623. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx");
  624. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  625. Sheet sheet = wb.getSheetAt(0);
  626. for(Row row : sheet){
  627. for(Cell cell : row){
  628. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){
  629. formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells
  630. }
  631. }
  632. }
  633. }
  634. /**
  635. * Newlines are valid characters in a formula
  636. */
  637. @Test
  638. public void bug50440And51875() throws Exception {
  639. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx");
  640. Sheet s = wb.getSheetAt(0);
  641. Cell c = s.getRow(0).getCell(0);
  642. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  643. assertEquals(3.0, c.getNumericCellValue(), 0);
  644. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  645. formulaEvaluator.evaluateFormulaCell(c);
  646. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  647. assertEquals(3.0, c.getNumericCellValue(), 0);
  648. // For 51875
  649. Cell b3 = s.getRow(2).getCell(1);
  650. formulaEvaluator.evaluateFormulaCell(b3);
  651. assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas
  652. assertEquals(3.0, b3.getNumericCellValue(), 0);
  653. }
  654. /**
  655. * Moving a cell comment from one cell to another
  656. */
  657. @Test
  658. public void bug50795() throws Exception {
  659. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx");
  660. XSSFSheet sheet = wb.getSheetAt(0);
  661. XSSFRow row = sheet.getRow(0);
  662. XSSFCell cellWith = row.getCell(0);
  663. XSSFCell cellWithoutComment = row.getCell(1);
  664. assertNotNull(cellWith.getCellComment());
  665. assertNull(cellWithoutComment.getCellComment());
  666. String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
  667. XSSFComment comment = cellWith.getCellComment();
  668. assertEquals(exp, comment.getString().getString());
  669. // Check we can write it out and read it back as-is
  670. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  671. sheet = wb.getSheetAt(0);
  672. row = sheet.getRow(0);
  673. cellWith = row.getCell(0);
  674. cellWithoutComment = row.getCell(1);
  675. // Double check things are as expected
  676. assertNotNull(cellWith.getCellComment());
  677. assertNull(cellWithoutComment.getCellComment());
  678. comment = cellWith.getCellComment();
  679. assertEquals(exp, comment.getString().getString());
  680. // Move the comment
  681. cellWithoutComment.setCellComment(comment);
  682. // Write out and re-check
  683. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  684. sheet = wb.getSheetAt(0);
  685. row = sheet.getRow(0);
  686. // Ensure it swapped over
  687. cellWith = row.getCell(0);
  688. cellWithoutComment = row.getCell(1);
  689. assertNull(cellWith.getCellComment());
  690. assertNotNull(cellWithoutComment.getCellComment());
  691. comment = cellWithoutComment.getCellComment();
  692. assertEquals(exp, comment.getString().getString());
  693. }
  694. /**
  695. * When the cell background colour is set with one of the first
  696. * two columns of the theme colour palette, the colours are
  697. * shades of white or black.
  698. * For those cases, ensure we don't break on reading the colour
  699. */
  700. @Test
  701. public void bug50299() throws Exception {
  702. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx");
  703. // Check all the colours
  704. for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
  705. Sheet s = wb.getSheetAt(sn);
  706. for(Row r : s) {
  707. for(Cell c : r) {
  708. CellStyle cs = c.getCellStyle();
  709. if(cs != null) {
  710. cs.getFillForegroundColor();
  711. }
  712. }
  713. }
  714. }
  715. // Check one bit in detail
  716. // Check that we get back foreground=0 for the theme colours,
  717. // and background=64 for the auto colouring
  718. Sheet s = wb.getSheetAt(0);
  719. assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor());
  720. assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor());
  721. assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor());
  722. assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor());
  723. }
  724. /**
  725. * Excel .xls style indexed colours in a .xlsx file
  726. */
  727. @Test
  728. public void bug50786() throws Exception {
  729. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx");
  730. XSSFSheet s = wb.getSheetAt(0);
  731. XSSFRow r = s.getRow(2);
  732. // Check we have the right cell
  733. XSSFCell c = r.getCell(1);
  734. assertEquals("test\u00a0", c.getRichStringCellValue().getString());
  735. // It should be light green
  736. XSSFCellStyle cs = c.getCellStyle();
  737. assertEquals(42, cs.getFillForegroundColor());
  738. assertEquals(42, cs.getFillForegroundColorColor().getIndexed());
  739. assertNotNull(cs.getFillForegroundColorColor().getRgb());
  740. assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex());
  741. }
  742. /**
  743. * If the border colours are set with themes, then we
  744. * should still be able to get colours
  745. */
  746. @Test
  747. public void bug50846() throws Exception {
  748. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx");
  749. XSSFSheet sheet = wb.getSheetAt(0);
  750. XSSFRow row = sheet.getRow(0);
  751. // Border from a theme, brown
  752. XSSFCell cellT = row.getCell(0);
  753. XSSFCellStyle styleT = cellT.getCellStyle();
  754. XSSFColor colorT = styleT.getBottomBorderXSSFColor();
  755. assertEquals(5, colorT.getTheme());
  756. assertEquals("FFC0504D", colorT.getARGBHex());
  757. // Border from a style direct, red
  758. XSSFCell cellS = row.getCell(1);
  759. XSSFCellStyle styleS = cellS.getCellStyle();
  760. XSSFColor colorS = styleS.getBottomBorderXSSFColor();
  761. assertEquals(0, colorS.getTheme());
  762. assertEquals("FFFF0000", colorS.getARGBHex());
  763. }
  764. /**
  765. * Fonts where their colours come from the theme rather
  766. * then being set explicitly still should allow the
  767. * fetching of the RGB.
  768. */
  769. @Test
  770. public void bug50784() throws Exception {
  771. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx");
  772. XSSFSheet s = wb.getSheetAt(0);
  773. XSSFRow r = s.getRow(0);
  774. // Column 1 has a font with regular colours
  775. XSSFCell cr = r.getCell(1);
  776. XSSFFont fr = wb.getFontAt( cr.getCellStyle().getFontIndex() );
  777. XSSFColor colr = fr.getXSSFColor();
  778. // No theme, has colours
  779. assertEquals(0, colr.getTheme());
  780. assertNotNull( colr.getRgb() );
  781. // Column 0 has a font with colours from a theme
  782. XSSFCell ct = r.getCell(0);
  783. XSSFFont ft = wb.getFontAt( ct.getCellStyle().getFontIndex() );
  784. XSSFColor colt = ft.getXSSFColor();
  785. // Has a theme, which has the colours on it
  786. assertEquals(9, colt.getTheme());
  787. XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme());
  788. assertNotNull( themeC.getRgb() );
  789. assertNotNull( colt.getRgb() );
  790. assertEquals( themeC.getARGBHex(), colt.getARGBHex() ); // The same colour
  791. }
  792. /**
  793. * New lines were being eaten when setting a font on
  794. * a rich text string
  795. */
  796. @Test
  797. public void bug48877() throws Exception {
  798. String text = "Use \n with word wrap on to create a new line.\n" +
  799. "This line finishes with two trailing spaces. ";
  800. XSSFWorkbook wb = new XSSFWorkbook();
  801. XSSFSheet sheet = wb.createSheet();
  802. Font font1 = wb.createFont();
  803. font1.setColor((short) 20);
  804. Font font2 = wb.createFont();
  805. font2.setColor(Font.COLOR_RED);
  806. Font font3 = wb.getFontAt((short)0);
  807. XSSFRow row = sheet.createRow(2);
  808. XSSFCell cell = row.createCell(2);
  809. XSSFRichTextString richTextString =
  810. wb.getCreationHelper().createRichTextString(text);
  811. // Check the text has the newline
  812. assertEquals(text, richTextString.getString());
  813. // Apply the font
  814. richTextString.applyFont(font3);
  815. richTextString.applyFont(0, 3, font1);
  816. cell.setCellValue(richTextString);
  817. // To enable newlines you need set a cell styles with wrap=true
  818. CellStyle cs = wb.createCellStyle();
  819. cs.setWrapText(true);
  820. cell.setCellStyle(cs);
  821. // Check the text has the
  822. assertEquals(text, cell.getStringCellValue());
  823. // Save the file and re-read it
  824. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  825. sheet = wb.getSheetAt(0);
  826. row = sheet.getRow(2);
  827. cell = row.getCell(2);
  828. assertEquals(text, cell.getStringCellValue());
  829. // Now add a 2nd, and check again
  830. int fontAt = text.indexOf("\n", 6);
  831. cell.getRichStringCellValue().applyFont(10, fontAt+1, font2);
  832. assertEquals(text, cell.getStringCellValue());
  833. assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
  834. assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT());
  835. String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT();
  836. assertEquals("line.\n", r3.substring(r3.length()-6));
  837. // Save and re-check
  838. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  839. sheet = wb.getSheetAt(0);
  840. row = sheet.getRow(2);
  841. cell = row.getCell(2);
  842. assertEquals(text, cell.getStringCellValue());
  843. wb.close();
  844. // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx");
  845. // wb.write(out);
  846. // out.close();
  847. }
  848. /**
  849. * Adding sheets when one has a table, then re-ordering
  850. */
  851. @Test
  852. public void bug50867() throws Exception {
  853. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx");
  854. assertEquals(3, wb.getNumberOfSheets());
  855. XSSFSheet s1 = wb.getSheetAt(0);
  856. XSSFSheet s2 = wb.getSheetAt(1);
  857. XSSFSheet s3 = wb.getSheetAt(2);
  858. assertEquals(1, s1.getTables().size());
  859. assertEquals(0, s2.getTables().size());
  860. assertEquals(0, s3.getTables().size());
  861. XSSFTable t = s1.getTables().get(0);
  862. assertEquals("Tabella1", t.getName());
  863. assertEquals("Tabella1", t.getDisplayName());
  864. assertEquals("A1:C3", t.getCTTable().getRef());
  865. // Add a sheet and re-order
  866. XSSFSheet s4 = wb.createSheet("NewSheet");
  867. wb.setSheetOrder(s4.getSheetName(), 0);
  868. // Check on tables
  869. assertEquals(1, s1.getTables().size());
  870. assertEquals(0, s2.getTables().size());
  871. assertEquals(0, s3.getTables().size());
  872. assertEquals(0, s4.getTables().size());
  873. // Refetch to get the new order
  874. s1 = wb.getSheetAt(0);
  875. s2 = wb.getSheetAt(1);
  876. s3 = wb.getSheetAt(2);
  877. s4 = wb.getSheetAt(3);
  878. assertEquals(0, s1.getTables().size());
  879. assertEquals(1, s2.getTables().size());
  880. assertEquals(0, s3.getTables().size());
  881. assertEquals(0, s4.getTables().size());
  882. // Save and re-load
  883. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  884. s1 = wb.getSheetAt(0);
  885. s2 = wb.getSheetAt(1);
  886. s3 = wb.getSheetAt(2);
  887. s4 = wb.getSheetAt(3);
  888. assertEquals(0, s1.getTables().size());
  889. assertEquals(1, s2.getTables().size());
  890. assertEquals(0, s3.getTables().size());
  891. assertEquals(0, s4.getTables().size());
  892. t = s2.getTables().get(0);
  893. assertEquals("Tabella1", t.getName());
  894. assertEquals("Tabella1", t.getDisplayName());
  895. assertEquals("A1:C3", t.getCTTable().getRef());
  896. // Add some more tables, and check
  897. t = s2.createTable();
  898. t.setName("New 2");
  899. t.setDisplayName("New 2");
  900. t = s3.createTable();
  901. t.setName("New 3");
  902. t.setDisplayName("New 3");
  903. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  904. s1 = wb.getSheetAt(0);
  905. s2 = wb.getSheetAt(1);
  906. s3 = wb.getSheetAt(2);
  907. s4 = wb.getSheetAt(3);
  908. assertEquals(0, s1.getTables().size());
  909. assertEquals(2, s2.getTables().size());
  910. assertEquals(1, s3.getTables().size());
  911. assertEquals(0, s4.getTables().size());
  912. t = s2.getTables().get(0);
  913. assertEquals("Tabella1", t.getName());
  914. assertEquals("Tabella1", t.getDisplayName());
  915. assertEquals("A1:C3", t.getCTTable().getRef());
  916. t = s2.getTables().get(1);
  917. assertEquals("New 2", t.getName());
  918. assertEquals("New 2", t.getDisplayName());
  919. t = s3.getTables().get(0);
  920. assertEquals("New 3", t.getName());
  921. assertEquals("New 3", t.getDisplayName());
  922. // Check the relationships
  923. assertEquals(0, s1.getRelations().size());
  924. assertEquals(3, s2.getRelations().size());
  925. assertEquals(1, s3.getRelations().size());
  926. assertEquals(0, s4.getRelations().size());
  927. assertEquals(
  928. XSSFRelation.PRINTER_SETTINGS.getContentType(),
  929. s2.getRelations().get(0).getPackagePart().getContentType()
  930. );
  931. assertEquals(
  932. XSSFRelation.TABLE.getContentType(),
  933. s2.getRelations().get(1).getPackagePart().getContentType()
  934. );
  935. assertEquals(
  936. XSSFRelation.TABLE.getContentType(),
  937. s2.getRelations().get(2).getPackagePart().getContentType()
  938. );
  939. assertEquals(
  940. XSSFRelation.TABLE.getContentType(),
  941. s3.getRelations().get(0).getPackagePart().getContentType()
  942. );
  943. assertEquals(
  944. "/xl/tables/table3.xml",
  945. s3.getRelations().get(0).getPackagePart().getPartName().toString()
  946. );
  947. }
  948. /**
  949. * Setting repeating rows and columns shouldn't break
  950. * any print settings that were there before
  951. */
  952. @SuppressWarnings("deprecation")
  953. @Test
  954. public void bug49253() throws Exception {
  955. XSSFWorkbook wb1 = new XSSFWorkbook();
  956. XSSFWorkbook wb2 = new XSSFWorkbook();
  957. // No print settings before repeating
  958. XSSFSheet s1 = wb1.createSheet();
  959. assertEquals(false, s1.getCTWorksheet().isSetPageSetup());
  960. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  961. wb1.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  962. assertEquals(true, s1.getCTWorksheet().isSetPageSetup());
  963. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  964. XSSFPrintSetup ps1 = s1.getPrintSetup();
  965. assertEquals(false, ps1.getValidSettings());
  966. assertEquals(false, ps1.getLandscape());
  967. // Had valid print settings before repeating
  968. XSSFSheet s2 = wb2.createSheet();
  969. XSSFPrintSetup ps2 = s2.getPrintSetup();
  970. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  971. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  972. ps2.setLandscape(false);
  973. assertEquals(true, ps2.getValidSettings());
  974. assertEquals(false, ps2.getLandscape());
  975. wb2.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  976. ps2 = s2.getPrintSetup();
  977. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  978. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  979. assertEquals(true, ps2.getValidSettings());
  980. assertEquals(false, ps2.getLandscape());
  981. wb1.close();
  982. wb2.close();
  983. }
  984. /**
  985. * Default Column style
  986. */
  987. @Test
  988. public void bug51037() throws Exception {
  989. XSSFWorkbook wb = new XSSFWorkbook();
  990. XSSFSheet s = wb.createSheet();
  991. CellStyle defaultStyle = wb.getCellStyleAt((short)0);
  992. assertEquals(0, defaultStyle.getIndex());
  993. CellStyle blueStyle = wb.createCellStyle();
  994. blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  995. blueStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  996. assertEquals(1, blueStyle.getIndex());
  997. CellStyle pinkStyle = wb.createCellStyle();
  998. pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
  999. pinkStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  1000. assertEquals(2, pinkStyle.getIndex());
  1001. // Starts empty
  1002. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1003. CTCols cols = s.getCTWorksheet().getColsArray(0);
  1004. assertEquals(0, cols.sizeOfColArray());
  1005. // Add some rows and columns
  1006. XSSFRow r1 = s.createRow(0);
  1007. XSSFRow r2 = s.createRow(1);
  1008. r1.createCell(0);
  1009. r1.createCell(2);
  1010. r2.createCell(0);
  1011. r2.createCell(3);
  1012. // Check no style is there
  1013. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1014. assertEquals(0, cols.sizeOfColArray());
  1015. assertEquals(defaultStyle, s.getColumnStyle(0));
  1016. assertEquals(defaultStyle, s.getColumnStyle(2));
  1017. assertEquals(defaultStyle, s.getColumnStyle(3));
  1018. // Apply the styles
  1019. s.setDefaultColumnStyle(0, pinkStyle);
  1020. s.setDefaultColumnStyle(3, blueStyle);
  1021. // Check
  1022. assertEquals(pinkStyle, s.getColumnStyle(0));
  1023. assertEquals(defaultStyle, s.getColumnStyle(2));
  1024. assertEquals(blueStyle, s.getColumnStyle(3));
  1025. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1026. assertEquals(2, cols.sizeOfColArray());
  1027. assertEquals(1, cols.getColArray(0).getMin());
  1028. assertEquals(1, cols.getColArray(0).getMax());
  1029. assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
  1030. assertEquals(4, cols.getColArray(1).getMin());
  1031. assertEquals(4, cols.getColArray(1).getMax());
  1032. assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
  1033. // Save, re-load and re-check
  1034. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1035. s = wb.getSheetAt(0);
  1036. defaultStyle = wb.getCellStyleAt(defaultStyle.getIndex());
  1037. blueStyle = wb.getCellStyleAt(blueStyle.getIndex());
  1038. pinkStyle = wb.getCellStyleAt(pinkStyle.getIndex());
  1039. assertEquals(pinkStyle, s.getColumnStyle(0));
  1040. assertEquals(defaultStyle, s.getColumnStyle(2));
  1041. assertEquals(blueStyle, s.getColumnStyle(3));
  1042. wb.close();
  1043. }
  1044. /**
  1045. * Repeatedly writing a file.
  1046. * Something with the SharedStringsTable currently breaks...
  1047. */
  1048. @Test
  1049. public void bug46662() throws Exception {
  1050. // New file
  1051. XSSFWorkbook wb = new XSSFWorkbook();
  1052. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1053. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1054. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1055. // Simple file
  1056. wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1057. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1058. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1059. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1060. // Complex file
  1061. // TODO
  1062. }
  1063. /**
  1064. * Colours and styles when the list has gaps in it
  1065. */
  1066. @Test
  1067. public void bug51222() throws Exception {
  1068. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx");
  1069. XSSFSheet s = wb.getSheetAt(0);
  1070. XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0);
  1071. XSSFCell cA5_1F497D = s.getRow(4).getCell(0);
  1072. // Check the text
  1073. assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString());
  1074. assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString());
  1075. // Check the styles assigned to them
  1076. assertEquals(4, cA4_EEECE1.getCTCell().getS());
  1077. assertEquals(5, cA5_1F497D.getCTCell().getS());
  1078. // Check we look up the correct style
  1079. assertEquals(4, cA4_EEECE1.getCellStyle().getIndex());
  1080. assertEquals(5, cA5_1F497D.getCellStyle().getIndex());
  1081. // Check the fills on them at the low level
  1082. assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId());
  1083. assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId());
  1084. // These should reference themes 2 and 3
  1085. assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme());
  1086. assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme());
  1087. // Ensure we get the right colours for these themes
  1088. // TODO fix
  1089. // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex());
  1090. // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex());
  1091. // Finally check the colours on the styles
  1092. // TODO fix
  1093. // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1094. // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1095. }
  1096. @Test
  1097. public void bug51470() throws Exception {
  1098. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx");
  1099. XSSFSheet sh0 = wb.getSheetAt(0);
  1100. XSSFSheet sh1 = wb.cloneSheet(0);
  1101. List<POIXMLDocumentPart> rels0 = sh0.getRelations();
  1102. List<POIXMLDocumentPart> rels1 = sh1.getRelations();
  1103. assertEquals(1, rels0.size());
  1104. assertEquals(1, rels1.size());
  1105. assertEquals(rels0.get(0).getPackageRelationship(), rels1.get(0).getPackageRelationship());
  1106. }
  1107. /**
  1108. * Add comments to Sheet 1, when Sheet 2 already has
  1109. * comments (so /xl/comments1.xml is taken)
  1110. */
  1111. @Test
  1112. public void bug51850() {
  1113. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx");
  1114. XSSFSheet sh1 = wb.getSheetAt(0);
  1115. XSSFSheet sh2 = wb.getSheetAt(1);
  1116. // Sheet 2 has comments
  1117. assertNotNull(sh2.getCommentsTable(false));
  1118. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1119. // Sheet 1 doesn't (yet)
  1120. assertNull(sh1.getCommentsTable(false));
  1121. // Try to add comments to Sheet 1
  1122. CreationHelper factory = wb.getCreationHelper();
  1123. Drawing drawing = sh1.createDrawingPatriarch();
  1124. ClientAnchor anchor = factory.createClientAnchor();
  1125. anchor.setCol1(0);
  1126. anchor.setCol2(4);
  1127. anchor.setRow1(0);
  1128. anchor.setRow2(1);
  1129. Comment comment1 = drawing.createCellComment(anchor);
  1130. comment1.setString(
  1131. factory.createRichTextString("I like this cell. It's my favourite."));
  1132. comment1.setAuthor("Bob T. Fish");
  1133. Comment comment2 = drawing.createCellComment(anchor);
  1134. comment2.setString(
  1135. factory.createRichTextString("This is much less fun..."));
  1136. comment2.setAuthor("Bob T. Fish");
  1137. Cell c1 = sh1.getRow(0).createCell(4);
  1138. c1.setCellValue(2.3);
  1139. c1.setCellComment(comment1);
  1140. Cell c2 = sh1.getRow(0).createCell(5);
  1141. c2.setCellValue(2.1);
  1142. c2.setCellComment(comment2);
  1143. // Save and re-load
  1144. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1145. sh1 = wb.getSheetAt(0);
  1146. sh2 = wb.getSheetAt(1);
  1147. // Check the comments
  1148. assertNotNull(sh2.getCommentsTable(false));
  1149. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1150. assertNotNull(sh1.getCommentsTable(false));
  1151. assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
  1152. }
  1153. /**
  1154. * Sheet names with a , in them
  1155. */
  1156. @Test
  1157. public void bug51963() throws Exception {
  1158. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx");
  1159. XSSFSheet sheet = wb.getSheetAt(0);
  1160. assertEquals("Abc,1", sheet.getSheetName());
  1161. Name name = wb.getName("Intekon.ProdCodes");
  1162. assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula());
  1163. AreaReference ref = new AreaReference(name.getRefersToFormula());
  1164. assertEquals(0, ref.getFirstCell().getRow());
  1165. assertEquals(0, ref.getFirstCell().getCol());
  1166. assertEquals(1, ref.getLastCell().getRow());
  1167. assertEquals(0, ref.getLastCell().getCol());
  1168. }
  1169. /**
  1170. * Sum across multiple workbooks
  1171. * eg =SUM($Sheet1.C1:$Sheet4.C1)
  1172. * DISABLED As we can't currently evaluate these
  1173. */
  1174. @Ignore
  1175. public void bug48703() throws Exception {
  1176. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx");
  1177. XSSFSheet sheet = wb.getSheetAt(0);
  1178. // Contains two forms, one with a range and one a list
  1179. XSSFRow r1 = sheet.getRow(0);
  1180. XSSFRow r2 = sheet.getRow(1);
  1181. XSSFCell c1 = r1.getCell(1);
  1182. XSSFCell c2 = r2.getCell(1);
  1183. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1184. assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula());
  1185. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1186. assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula());
  1187. // Try evaluating both
  1188. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  1189. eval.evaluateFormulaCell(c1);
  1190. eval.evaluateFormulaCell(c2);
  1191. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1192. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1193. }
  1194. /**
  1195. * Bugzilla 51710: problems reading shared formuals from .xlsx
  1196. */
  1197. @Test
  1198. public void bug51710() {
  1199. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx");
  1200. final String[] columns = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
  1201. final int rowMax = 500; // bug triggers on row index 59
  1202. Sheet sheet = wb.getSheetAt(0);
  1203. // go through all formula cells
  1204. for (int rInd = 2; rInd <= rowMax; rInd++) {
  1205. Row row = sheet.getRow(rInd);
  1206. for (int cInd = 1; cInd <= 12; cInd++) {
  1207. Cell cell = row.getCell(cInd);
  1208. String formula = cell.getCellFormula();
  1209. CellReference ref = new CellReference(cell);
  1210. //simulate correct answer
  1211. String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2";
  1212. assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula);
  1213. }
  1214. }
  1215. }
  1216. /**
  1217. * Bug 53101:
  1218. */
  1219. @Test
  1220. public void bug5301(){
  1221. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx");
  1222. FormulaEvaluator evaluator =
  1223. workbook.getCreationHelper().createFormulaEvaluator();
  1224. // A1: SUM(B1: IZ1)
  1225. double a1Value =
  1226. evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(0)).getNumberValue();
  1227. // Assert
  1228. assertEquals(259.0, a1Value, 0.0);
  1229. // KY: SUM(B1: IZ1)
  1230. /*double ky1Value =*/
  1231. evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(310)).getNumberValue();
  1232. // Assert
  1233. assertEquals(259.0, a1Value, 0.0);
  1234. }
  1235. @Test
  1236. public void bug54436(){
  1237. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx");
  1238. if(!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")){
  1239. Function func = new Function() {
  1240. public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
  1241. return ErrorEval.NA;
  1242. }
  1243. };
  1244. WorkbookEvaluator.registerFunction("GETPIVOTDATA", func);
  1245. }
  1246. workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
  1247. }
  1248. /**
  1249. * Password Protected .xlsx files should give a helpful
  1250. * error message when called via WorkbookFactory.
  1251. * (You need to supply a password explicitly for them)
  1252. */
  1253. @Test(expected=EncryptedDocumentException.class)
  1254. public void bug55692_stream() throws Exception {
  1255. // Directly on a Stream
  1256. WorkbookFactory.create(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1257. }
  1258. @Test(expected=EncryptedDocumentException.class)
  1259. public void bug55692_poifs() throws Exception {
  1260. // Via a POIFSFileSystem
  1261. POIFSFileSystem fsP = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1262. WorkbookFactory.create(fsP);
  1263. }
  1264. @Test(expected=EncryptedDocumentException.class)
  1265. public void bug55692_npoifs() throws Exception {
  1266. // Via a NPOIFSFileSystem
  1267. NPOIFSFileSystem fsNP = new NPOIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1268. WorkbookFactory.create(fsNP);
  1269. }
  1270. @Test
  1271. public void bug53282() {
  1272. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx");
  1273. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1274. assertEquals("#@_#", c.getStringCellValue());
  1275. assertEquals("http://invalid.uri", c.getHyperlink().getAddress());
  1276. }
  1277. /**
  1278. * Was giving NullPointerException
  1279. * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead
  1280. * due to a lack of Styles Table
  1281. */
  1282. @Test
  1283. public void bug56278() throws Exception {
  1284. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx");
  1285. assertEquals(0, wb.getSheetIndex("Market Rates"));
  1286. // Save and re-check
  1287. Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1288. assertEquals(0, nwb.getSheetIndex("Market Rates"));
  1289. }
  1290. @Test
  1291. public void bug56315() {
  1292. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx");
  1293. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1294. CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c);
  1295. double rounded = cv.getNumberValue();
  1296. assertEquals(0.1, rounded, 0.0);
  1297. }
  1298. @Test
  1299. public void bug56468() throws Exception {
  1300. XSSFWorkbook wb = new XSSFWorkbook();
  1301. XSSFSheet sheet = wb.createSheet();
  1302. XSSFRow row = sheet.createRow(0);
  1303. XSSFCell cell = row.createCell(0);
  1304. cell.setCellValue("Hi");
  1305. sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0));
  1306. ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
  1307. wb.write(bos);
  1308. byte firstSave[] = bos.toByteArray();
  1309. bos.reset();
  1310. wb.write(bos);
  1311. byte secondSave[] = bos.toByteArray();
  1312. assertThat(firstSave, equalTo(secondSave));
  1313. wb.close();
  1314. }
  1315. /**
  1316. * ISO-8601 style cell formats with a T in them, eg
  1317. * cell format of "yyyy-MM-ddTHH:mm:ss"
  1318. */
  1319. @Test
  1320. public void bug54034() throws IOException {
  1321. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx");
  1322. Sheet sheet = wb.getSheet("Sheet1");
  1323. Row row = sheet.getRow(1);
  1324. Cell cell = row.getCell(2);
  1325. assertTrue(DateUtil.isCellDateFormatted(cell));
  1326. DataFormatter fmt = new DataFormatter();
  1327. assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
  1328. assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
  1329. }
  1330. @Test
  1331. public void testBug53798XLSX() throws IOException {
  1332. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1333. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1334. bug53798Work(wb, xlsOutput);
  1335. }
  1336. @Ignore("Shifting rows is not yet implemented in SXSSFSheet")
  1337. @Test
  1338. public void testBug53798XLSXStream() throws IOException {
  1339. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1340. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1341. bug53798Work(new SXSSFWorkbook(wb), xlsOutput);
  1342. }
  1343. @Test
  1344. public void testBug53798XLS() throws IOException {
  1345. Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls");
  1346. File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
  1347. bug53798Work(wb, xlsOutput);
  1348. }
  1349. /**
  1350. * SUMIF was throwing a NPE on some formulas
  1351. */
  1352. @Test
  1353. @Ignore("This bug is still to be fixed")
  1354. public void testBug56420SumIfNPE() throws Exception {
  1355. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx");
  1356. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1357. Sheet sheet = wb.getSheetAt(0);
  1358. Row r = sheet.getRow(2);
  1359. Cell c = r.getCell(2);
  1360. assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula());
  1361. evaluator.evaluateInCell(c);
  1362. }
  1363. private void bug53798Work(Workbook wb, File xlsOutput) throws IOException {
  1364. Sheet testSheet = wb.getSheetAt(0);
  1365. testSheet.shiftRows(2, 2, 1);
  1366. saveAndReloadReport(wb, xlsOutput);
  1367. // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about
  1368. // when shifted by less than -1 negative amount (try -2)
  1369. testSheet.shiftRows(3, 3, -1);
  1370. saveAndReloadReport(wb, xlsOutput);
  1371. testSheet.shiftRows(2, 2, 1);
  1372. saveAndReloadReport(wb, xlsOutput);
  1373. Row newRow = null;
  1374. Cell newCell = null;
  1375. // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted
  1376. // xlsx file with unreadable data in the negative shifted row.
  1377. // NOTE it's ok to create any other row.
  1378. newRow = testSheet.createRow(3);
  1379. saveAndReloadReport(wb, xlsOutput);
  1380. newCell = newRow.createCell(0);
  1381. saveAndReloadReport(wb, xlsOutput);
  1382. newCell.setCellValue("new Cell in row "+newRow.getRowNum());
  1383. saveAndReloadReport(wb, xlsOutput);
  1384. // 3) once a negative shift has been made any attempt to shift another group of rows
  1385. // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception:
  1386. // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException.
  1387. // NOTE: another negative shift on another group of rows is successful, provided no new rows in
  1388. // place of previously shifted rows were attempted to be created as explained above.
  1389. testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of
  1390. // the above has been tested
  1391. saveAndReloadReport(wb, xlsOutput);
  1392. }
  1393. /**
  1394. * XSSFCell.typeMismatch on certain blank cells when formatting
  1395. * with DataFormatter
  1396. */
  1397. @Test
  1398. public void bug56702() throws Exception {
  1399. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx");
  1400. Sheet sheet = wb.getSheetAt(0);
  1401. // Get wrong cell by row 8 & column 7
  1402. Cell cell = sheet.getRow(8).getCell(7);
  1403. assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
  1404. // Check the value - will be zero as it is <c><v/></c>
  1405. assertEquals(0.0, cell.getNumericCellValue(), 0.001);
  1406. // Try to format
  1407. DataFormatter formatter = new DataFormatter();
  1408. formatter.formatCellValue(cell);
  1409. // Check the formatting
  1410. assertEquals("0", formatter.formatCellValue(cell));
  1411. }
  1412. /**
  1413. * Formulas which reference named ranges, either in other
  1414. * sheets, or workbook scoped but in other workbooks.
  1415. * Used to fail with with errors like
  1416. * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9
  1417. * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name
  1418. */
  1419. @Test
  1420. public void bug56737() throws IOException {
  1421. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx");
  1422. // Check the named range definitions
  1423. Name nSheetScope = wb.getName("NR_To_A1");
  1424. Name nWBScope = wb.getName("NR_Global_B2");
  1425. assertNotNull(nSheetScope);
  1426. assertNotNull(nWBScope);
  1427. assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula());
  1428. assertEquals("Defines!$B$2", nWBScope.getRefersToFormula());
  1429. // Check the different kinds of formulas
  1430. Sheet s = wb.getSheetAt(0);
  1431. Cell cRefSName = s.getRow(1).getCell(3);
  1432. Cell cRefWName = s.getRow(2).getCell(3);
  1433. assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula());
  1434. // Note the formula, as stored in the file, has the external name index not filename
  1435. // TODO Provide a way to get the one with the filename
  1436. assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula());
  1437. // Try to evaluate them
  1438. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  1439. assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue());
  1440. assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue());
  1441. // Try to evaluate everything
  1442. eval.evaluateAll();
  1443. }
  1444. private void saveAndReloadReport(Workbook wb, File outFile) throws IOException {
  1445. // run some method on the font to verify if it is "disconnected" already
  1446. //for(short i = 0;i < 256;i++)
  1447. {
  1448. Font font = wb.getFontAt((short)0);
  1449. if(font instanceof XSSFFont) {
  1450. XSSFFont xfont = (XSSFFont) wb.getFontAt((short)0);
  1451. CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont();
  1452. assertEquals(0, ctFont.sizeOfBArray());
  1453. }
  1454. }
  1455. FileOutputStream fileOutStream = new FileOutputStream(outFile);
  1456. wb.write(fileOutStream);
  1457. fileOutStream.close();
  1458. //System.out.println("File \""+outFile.getName()+"\" has been saved successfully");
  1459. FileInputStream is = new FileInputStream(outFile);
  1460. try {
  1461. Workbook newWB = null;
  1462. try {
  1463. if(wb instanceof XSSFWorkbook) {
  1464. newWB = new XSSFWorkbook(is);
  1465. } else if(wb instanceof HSSFWorkbook) {
  1466. newWB = new HSSFWorkbook(is);
  1467. } else if(wb instanceof SXSSFWorkbook) {
  1468. newWB = new SXSSFWorkbook(new XSSFWorkbook(is));
  1469. } else {
  1470. throw new IllegalStateException("Unknown workbook: " + wb);
  1471. }
  1472. assertNotNull(newWB.getSheet("test"));
  1473. } finally {
  1474. newWB.close();
  1475. }
  1476. } finally {
  1477. is.close();
  1478. }
  1479. }
  1480. @Test
  1481. public void testBug56688_1() {
  1482. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx");
  1483. checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
  1484. }
  1485. @Test
  1486. public void testBug56688_2() {
  1487. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx");
  1488. checkValue(excel, "#VALUE!");
  1489. }
  1490. @Test
  1491. public void testBug56688_3() {
  1492. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx");
  1493. checkValue(excel, "#VALUE!");
  1494. }
  1495. @Test
  1496. public void testBug56688_4() {
  1497. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx");
  1498. Calendar calendar = Calendar.getInstance();
  1499. calendar.add(Calendar.MONTH, 2);
  1500. double excelDate = DateUtil.getExcelDate(calendar.getTime());
  1501. NumberEval eval = new NumberEval(Math.floor(excelDate));
  1502. checkValue(excel, eval.getStringValue() + ".0");
  1503. }
  1504. /**
  1505. * New hyperlink with no initial cell reference, still need
  1506. * to be able to change it
  1507. */
  1508. @Test
  1509. public void testBug56527() {
  1510. XSSFWorkbook wb = new XSSFWorkbook();
  1511. XSSFSheet sheet = wb.createSheet();
  1512. XSSFCreationHelper creationHelper = wb.getCreationHelper();
  1513. XSSFHyperlink hyperlink;
  1514. // Try with a cell reference
  1515. hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL);
  1516. sheet.addHyperlink(hyperlink);
  1517. hyperlink.setAddress("http://myurl");
  1518. hyperlink.setCellReference("B4");
  1519. assertEquals(3, hyperlink.getFirstRow());
  1520. assertEquals(1, hyperlink.getFirstColumn());
  1521. assertEquals(3, hyperlink.getLastRow());
  1522. assertEquals(1, hyperlink.getLastColumn());
  1523. // Try with explicit rows / columns
  1524. hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL);
  1525. sheet.addHyperlink(hyperlink);
  1526. hyperlink.setAddress("http://myurl");
  1527. hyperlink.setFirstRow(5);
  1528. hyperlink.setFirstColumn(3);
  1529. assertEquals(5, hyperlink.getFirstRow());
  1530. assertEquals(3, hyperlink.getFirstColumn());
  1531. assertEquals(5, hyperlink.getLastRow());
  1532. assertEquals(3, hyperlink.getLastColumn());
  1533. }
  1534. /**
  1535. * Shifting rows with a formula that references a
  1536. * function in another file
  1537. */
  1538. @Test
  1539. public void bug56502() throws Exception {
  1540. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx");
  1541. Sheet sheet = wb.getSheetAt(0);
  1542. Cell cFunc = sheet.getRow(3).getCell(0);
  1543. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1544. Cell cRef = sheet.getRow(3).createCell(1);
  1545. cRef.setCellFormula("A3");
  1546. // Shift it down one row
  1547. sheet.shiftRows(1, sheet.getLastRowNum(), 1);
  1548. // Check the new formulas: Function won't change, Reference will
  1549. cFunc = sheet.getRow(4).getCell(0);
  1550. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1551. cRef = sheet.getRow(4).getCell(1);
  1552. assertEquals("A4", cRef.getCellFormula());
  1553. }
  1554. @Test
  1555. public void bug54764() throws Exception {
  1556. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx");
  1557. // Check the core properties - will be found but empty, due
  1558. // to the expansion being too much to be considered valid
  1559. POIXMLProperties props = new POIXMLProperties(pkg);
  1560. assertEquals(null, props.getCoreProperties().getTitle());
  1561. assertEquals(null, props.getCoreProperties().getSubject());
  1562. assertEquals(null, props.getCoreProperties().getDescription());
  1563. // Now check the spreadsheet itself
  1564. try {
  1565. new XSSFWorkbook(pkg);
  1566. fail("Should fail as too much expansion occurs");
  1567. } catch(POIXMLException e) {
  1568. // Expected
  1569. }
  1570. // Try with one with the entities in the Content Types
  1571. try {
  1572. XSSFTestDataSamples.openSamplePackage("54764-2.xlsx");
  1573. fail("Should fail as too much expansion occurs");
  1574. } catch(Exception e) {
  1575. // Expected
  1576. }
  1577. // Check we can still parse valid files after all that
  1578. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1579. assertEquals(3, wb.getNumberOfSheets());
  1580. }
  1581. /**
  1582. * .xlsb files are not supported, but we should generate a helpful
  1583. * error message if given one
  1584. */
  1585. @Test
  1586. public void bug56800_xlsb() throws Exception {
  1587. // Can be opened at the OPC level
  1588. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb");
  1589. // XSSF Workbook gives helpful error
  1590. try {
  1591. new XSSFWorkbook(pkg);
  1592. fail(".xlsb files not supported");
  1593. } catch (XLSBUnsupportedException e) {
  1594. // Good, detected and warned
  1595. }
  1596. // Workbook Factory gives helpful error on package
  1597. try {
  1598. WorkbookFactory.create(pkg);
  1599. fail(".xlsb files not supported");
  1600. } catch (XLSBUnsupportedException e) {
  1601. // Good, detected and warned
  1602. }
  1603. // Workbook Factory gives helpful error on file
  1604. File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb");
  1605. try {
  1606. WorkbookFactory.create(xlsbFile);
  1607. fail(".xlsb files not supported");
  1608. } catch (XLSBUnsupportedException e) {
  1609. // Good, detected and warned
  1610. }
  1611. }
  1612. private void checkValue(XSSFWorkbook excel, String expect) {
  1613. XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
  1614. evaluator.evaluateAll();
  1615. XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
  1616. CellValue value = evaluator.evaluate(cell);
  1617. assertEquals(expect, value.formatAsString());
  1618. }
  1619. }