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 71KB

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