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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603
  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.junit.Assert.assertArrayEquals;
  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.assertTrue;
  22. import static org.junit.Assert.fail;
  23. import java.io.ByteArrayInputStream;
  24. import java.io.ByteArrayOutputStream;
  25. import java.io.File;
  26. import java.io.FileInputStream;
  27. import java.io.FileOutputStream;
  28. import java.io.IOException;
  29. import java.util.Arrays;
  30. import java.util.Calendar;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Set;
  34. import java.util.TreeMap;
  35. import org.apache.poi.EncryptedDocumentException;
  36. import org.apache.poi.POIDataSamples;
  37. import org.apache.poi.POIXMLDocumentPart;
  38. import org.apache.poi.POIXMLException;
  39. import org.apache.poi.POIXMLProperties;
  40. import org.apache.poi.hssf.HSSFTestDataSamples;
  41. import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
  42. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  43. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  44. import org.apache.poi.openxml4j.opc.OPCPackage;
  45. import org.apache.poi.openxml4j.opc.PackageAccess;
  46. import org.apache.poi.openxml4j.opc.PackagePart;
  47. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  48. import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
  49. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  50. import org.apache.poi.ss.formula.WorkbookEvaluator;
  51. import org.apache.poi.ss.formula.eval.ErrorEval;
  52. import org.apache.poi.ss.formula.eval.NumberEval;
  53. import org.apache.poi.ss.formula.eval.ValueEval;
  54. import org.apache.poi.ss.formula.functions.Function;
  55. import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
  56. import org.apache.poi.ss.usermodel.Cell;
  57. import org.apache.poi.ss.usermodel.CellStyle;
  58. import org.apache.poi.ss.usermodel.CellValue;
  59. import org.apache.poi.ss.usermodel.ClientAnchor;
  60. import org.apache.poi.ss.usermodel.Comment;
  61. import org.apache.poi.ss.usermodel.CreationHelper;
  62. import org.apache.poi.ss.usermodel.DataFormatter;
  63. import org.apache.poi.ss.usermodel.DateUtil;
  64. import org.apache.poi.ss.usermodel.Drawing;
  65. import org.apache.poi.ss.usermodel.Font;
  66. import org.apache.poi.ss.usermodel.FormulaError;
  67. import org.apache.poi.ss.usermodel.FormulaEvaluator;
  68. import org.apache.poi.ss.usermodel.Hyperlink;
  69. import org.apache.poi.ss.usermodel.IndexedColors;
  70. import org.apache.poi.ss.usermodel.Name;
  71. import org.apache.poi.ss.usermodel.Row;
  72. import org.apache.poi.ss.usermodel.Sheet;
  73. import org.apache.poi.ss.usermodel.Workbook;
  74. import org.apache.poi.ss.usermodel.WorkbookFactory;
  75. import org.apache.poi.ss.util.AreaReference;
  76. import org.apache.poi.ss.util.CellRangeAddress;
  77. import org.apache.poi.ss.util.CellReference;
  78. import org.apache.poi.util.TempFile;
  79. import org.apache.poi.xssf.XLSBUnsupportedException;
  80. import org.apache.poi.xssf.XSSFITestDataProvider;
  81. import org.apache.poi.xssf.XSSFTestDataSamples;
  82. import org.apache.poi.xssf.model.CalculationChain;
  83. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  84. import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
  85. import org.junit.Ignore;
  86. import org.junit.Test;
  87. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell;
  88. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
  89. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
  90. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames;
  91. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  92. import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl;
  93. public final class TestXSSFBugs extends BaseTestBugzillaIssues {
  94. public TestXSSFBugs() {
  95. super(XSSFITestDataProvider.instance);
  96. }
  97. /**
  98. * test writing a file with large number of unique strings,
  99. * open resulting file in Excel to check results!
  100. */
  101. @Test
  102. public void bug15375_2() {
  103. bug15375(1000);
  104. }
  105. /**
  106. * Named ranges had the right reference, but
  107. * the wrong sheet name
  108. */
  109. @Test
  110. public void bug45430() {
  111. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx");
  112. assertFalse(wb.isMacroEnabled());
  113. assertEquals(3, wb.getNumberOfNames());
  114. assertEquals(0, wb.getNameAt(0).getCTName().getLocalSheetId());
  115. assertFalse(wb.getNameAt(0).getCTName().isSetLocalSheetId());
  116. assertEquals("SheetA!$A$1", wb.getNameAt(0).getRefersToFormula());
  117. assertEquals("SheetA", wb.getNameAt(0).getSheetName());
  118. assertEquals(0, wb.getNameAt(1).getCTName().getLocalSheetId());
  119. assertFalse(wb.getNameAt(1).getCTName().isSetLocalSheetId());
  120. assertEquals("SheetB!$A$1", wb.getNameAt(1).getRefersToFormula());
  121. assertEquals("SheetB", wb.getNameAt(1).getSheetName());
  122. assertEquals(0, wb.getNameAt(2).getCTName().getLocalSheetId());
  123. assertFalse(wb.getNameAt(2).getCTName().isSetLocalSheetId());
  124. assertEquals("SheetC!$A$1", wb.getNameAt(2).getRefersToFormula());
  125. assertEquals("SheetC", wb.getNameAt(2).getSheetName());
  126. // Save and re-load, still there
  127. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  128. assertEquals(3, nwb.getNumberOfNames());
  129. assertEquals("SheetA!$A$1", nwb.getNameAt(0).getRefersToFormula());
  130. }
  131. /**
  132. * We should carry vba macros over after save
  133. */
  134. @Test
  135. public void bug45431() throws Exception {
  136. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm");
  137. OPCPackage pkg = wb.getPackage();
  138. assertTrue(wb.isMacroEnabled());
  139. // Check the various macro related bits can be found
  140. PackagePart vba = pkg.getPart(
  141. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  142. );
  143. assertNotNull(vba);
  144. // And the drawing bit
  145. PackagePart drw = pkg.getPart(
  146. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  147. );
  148. assertNotNull(drw);
  149. // Save and re-open, both still there
  150. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  151. OPCPackage nPkg = nwb.getPackage();
  152. assertTrue(nwb.isMacroEnabled());
  153. vba = nPkg.getPart(
  154. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  155. );
  156. assertNotNull(vba);
  157. drw = nPkg.getPart(
  158. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  159. );
  160. assertNotNull(drw);
  161. // And again, just to be sure
  162. nwb = XSSFTestDataSamples.writeOutAndReadBack(nwb);
  163. nPkg = nwb.getPackage();
  164. assertTrue(nwb.isMacroEnabled());
  165. vba = nPkg.getPart(
  166. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  167. );
  168. assertNotNull(vba);
  169. drw = nPkg.getPart(
  170. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  171. );
  172. assertNotNull(drw);
  173. }
  174. @Test
  175. public void bug47504() {
  176. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx");
  177. assertEquals(1, wb.getNumberOfSheets());
  178. XSSFSheet sh = wb.getSheetAt(0);
  179. XSSFDrawing drawing = sh.createDrawingPatriarch();
  180. List<POIXMLDocumentPart> rels = drawing.getRelations();
  181. assertEquals(1, rels.size());
  182. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  183. // And again, just to be sure
  184. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  185. assertEquals(1, wb.getNumberOfSheets());
  186. sh = wb.getSheetAt(0);
  187. drawing = sh.createDrawingPatriarch();
  188. rels = drawing.getRelations();
  189. assertEquals(1, rels.size());
  190. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  191. }
  192. /**
  193. * Excel will sometimes write a button with a textbox
  194. * containing &gt;br&lt; (not closed!).
  195. * Clearly Excel shouldn't do this, but test that we can
  196. * read the file despite the naughtyness
  197. */
  198. @Test
  199. public void bug49020() throws Exception {
  200. /*XSSFWorkbook wb =*/ XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx");
  201. }
  202. /**
  203. * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas
  204. */
  205. @Test
  206. public void bug49325() throws Exception {
  207. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx");
  208. CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet();
  209. assertNotNull(sh.getPhoneticPr());
  210. }
  211. /**
  212. * Names which are defined with a Sheet
  213. * should return that sheet index properly
  214. */
  215. @Test
  216. public void bug48923() throws Exception {
  217. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx");
  218. assertEquals(4, wb.getNumberOfNames());
  219. Name b1 = wb.getName("NameB1");
  220. Name b2 = wb.getName("NameB2");
  221. Name sheet2 = wb.getName("NameSheet2");
  222. Name test = wb.getName("Test");
  223. assertNotNull(b1);
  224. assertEquals("NameB1", b1.getNameName());
  225. assertEquals("Sheet1", b1.getSheetName());
  226. assertEquals(-1, b1.getSheetIndex());
  227. assertNotNull(b2);
  228. assertEquals("NameB2", b2.getNameName());
  229. assertEquals("Sheet1", b2.getSheetName());
  230. assertEquals(-1, b2.getSheetIndex());
  231. assertNotNull(sheet2);
  232. assertEquals("NameSheet2", sheet2.getNameName());
  233. assertEquals("Sheet2", sheet2.getSheetName());
  234. assertEquals(-1, sheet2.getSheetIndex());
  235. assertNotNull(test);
  236. assertEquals("Test", test.getNameName());
  237. assertEquals("Sheet1", test.getSheetName());
  238. assertEquals(-1, test.getSheetIndex());
  239. }
  240. /**
  241. * Problem with evaluation formulas due to
  242. * NameXPtgs.
  243. * Blows up on:
  244. * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0))
  245. *
  246. * TODO: delete this test case when MROUND and VAR are implemented
  247. */
  248. @Test
  249. public void bug48539() throws Exception {
  250. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx");
  251. assertEquals(3, wb.getNumberOfSheets());
  252. assertEquals(0, wb.getNumberOfNames());
  253. // Try each cell individually
  254. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  255. for(int i=0; i<wb.getNumberOfSheets(); i++) {
  256. Sheet s = wb.getSheetAt(i);
  257. for(Row r : s) {
  258. for(Cell c : r) {
  259. if(c.getCellType() == Cell.CELL_TYPE_FORMULA) {
  260. String formula = c.getCellFormula();
  261. CellValue cv;
  262. try {
  263. cv = eval.evaluate(c);
  264. } catch (Exception e) {
  265. throw new RuntimeException("Can't evaluate formula: " + formula, e);
  266. }
  267. if(cv.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  268. // assert that the calculated value agrees with
  269. // the cached formula result calculated by Excel
  270. double cachedFormulaResult = c.getNumericCellValue();
  271. double evaluatedFormulaResult = cv.getNumberValue();
  272. assertEquals(c.getCellFormula(), cachedFormulaResult, evaluatedFormulaResult, 1E-7);
  273. }
  274. }
  275. }
  276. }
  277. }
  278. // Now all of them
  279. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  280. }
  281. /**
  282. * Foreground colours should be found even if
  283. * a theme is used
  284. */
  285. @Test
  286. public void bug48779() throws Exception {
  287. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx");
  288. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  289. XSSFCellStyle cs = cell.getCellStyle();
  290. assertNotNull(cs);
  291. assertEquals(1, cs.getIndex());
  292. // Look at the low level xml elements
  293. assertEquals(2, cs.getCoreXf().getFillId());
  294. assertEquals(0, cs.getCoreXf().getXfId());
  295. assertEquals(true, cs.getCoreXf().getApplyFill());
  296. XSSFCellFill fg = wb.getStylesSource().getFillAt(2);
  297. assertEquals(0, fg.getFillForegroundColor().getIndexed());
  298. assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0);
  299. assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex());
  300. assertEquals(64, fg.getFillBackgroundColor().getIndexed());
  301. // Now look higher up
  302. assertNotNull(cs.getFillForegroundXSSFColor());
  303. assertEquals(0, cs.getFillForegroundColor());
  304. assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex());
  305. assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex());
  306. assertNotNull(cs.getFillBackgroundColor());
  307. assertEquals(64, cs.getFillBackgroundColor());
  308. assertEquals(null, cs.getFillBackgroundXSSFColor().getARGBHex());
  309. assertEquals(null, cs.getFillBackgroundColorColor().getARGBHex());
  310. }
  311. /**
  312. * With HSSF, if you create a font, don't change it, and
  313. * create a 2nd, you really do get two fonts that you
  314. * can alter as and when you want.
  315. * With XSSF, that wasn't the case, but this verfies
  316. * that it now is again
  317. */
  318. @Test
  319. public void bug48718() throws Exception {
  320. // Verify the HSSF behaviour
  321. // Then ensure the same for XSSF
  322. Workbook[] wbs = new Workbook[] {
  323. new HSSFWorkbook(),
  324. new XSSFWorkbook()
  325. };
  326. int[] initialFonts = new int[] { 4, 1 };
  327. for(int i=0; i<wbs.length; i++) {
  328. Workbook wb = wbs[i];
  329. int startingFonts = initialFonts[i];
  330. assertEquals(startingFonts, wb.getNumberOfFonts());
  331. // Get a font, and slightly change it
  332. Font a = wb.createFont();
  333. assertEquals(startingFonts+1, wb.getNumberOfFonts());
  334. a.setFontHeightInPoints((short)23);
  335. assertEquals(startingFonts+1, wb.getNumberOfFonts());
  336. // Get two more, unchanged
  337. /*Font b =*/ wb.createFont();
  338. assertEquals(startingFonts+2, wb.getNumberOfFonts());
  339. /*Font c =*/ wb.createFont();
  340. assertEquals(startingFonts+3, wb.getNumberOfFonts());
  341. }
  342. }
  343. /**
  344. * Ensure General and @ format are working properly
  345. * for integers
  346. */
  347. @Test
  348. public void bug47490() throws Exception {
  349. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx");
  350. Sheet s = wb.getSheetAt(1);
  351. Row r;
  352. DataFormatter df = new DataFormatter();
  353. r = s.getRow(1);
  354. assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0);
  355. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  356. assertEquals("1", df.formatCellValue(r.getCell(2)));
  357. assertEquals("1", df.formatRawCellContents(1.0, -1, "@"));
  358. assertEquals("1", df.formatRawCellContents(1.0, -1, "General"));
  359. r = s.getRow(2);
  360. assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0);
  361. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  362. assertEquals("12", df.formatCellValue(r.getCell(2)));
  363. assertEquals("12", df.formatRawCellContents(12.0, -1, "@"));
  364. assertEquals("12", df.formatRawCellContents(12.0, -1, "General"));
  365. r = s.getRow(3);
  366. assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0);
  367. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  368. assertEquals("123", df.formatCellValue(r.getCell(2)));
  369. assertEquals("123", df.formatRawCellContents(123.0, -1, "@"));
  370. assertEquals("123", df.formatRawCellContents(123.0, -1, "General"));
  371. }
  372. /**
  373. * Ensures that XSSF and HSSF agree with each other,
  374. * and with the docs on when fetching the wrong
  375. * kind of value from a Formula cell
  376. */
  377. @Test
  378. public void bug47815() {
  379. Workbook[] wbs = new Workbook[] {
  380. new HSSFWorkbook(),
  381. new XSSFWorkbook()
  382. };
  383. for(Workbook wb : wbs) {
  384. Sheet s = wb.createSheet();
  385. Row r = s.createRow(0);
  386. // Setup
  387. Cell cn = r.createCell(0, Cell.CELL_TYPE_NUMERIC);
  388. cn.setCellValue(1.2);
  389. Cell cs = r.createCell(1, Cell.CELL_TYPE_STRING);
  390. cs.setCellValue("Testing");
  391. Cell cfn = r.createCell(2, Cell.CELL_TYPE_FORMULA);
  392. cfn.setCellFormula("A1");
  393. Cell cfs = r.createCell(3, Cell.CELL_TYPE_FORMULA);
  394. cfs.setCellFormula("B1");
  395. FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
  396. assertEquals(Cell.CELL_TYPE_NUMERIC, fe.evaluate(cfn).getCellType());
  397. assertEquals(Cell.CELL_TYPE_STRING, fe.evaluate(cfs).getCellType());
  398. fe.evaluateFormulaCell(cfn);
  399. fe.evaluateFormulaCell(cfs);
  400. // Now test
  401. assertEquals(Cell.CELL_TYPE_NUMERIC, cn.getCellType());
  402. assertEquals(Cell.CELL_TYPE_STRING, cs.getCellType());
  403. assertEquals(Cell.CELL_TYPE_FORMULA, cfn.getCellType());
  404. assertEquals(Cell.CELL_TYPE_NUMERIC, cfn.getCachedFormulaResultType());
  405. assertEquals(Cell.CELL_TYPE_FORMULA, cfs.getCellType());
  406. assertEquals(Cell.CELL_TYPE_STRING, cfs.getCachedFormulaResultType());
  407. // Different ways of retrieving
  408. assertEquals(1.2, cn.getNumericCellValue(), 0);
  409. try {
  410. cn.getRichStringCellValue();
  411. fail();
  412. } catch(IllegalStateException e) {}
  413. assertEquals("Testing", cs.getStringCellValue());
  414. try {
  415. cs.getNumericCellValue();
  416. fail();
  417. } catch(IllegalStateException e) {}
  418. assertEquals(1.2, cfn.getNumericCellValue(), 0);
  419. try {
  420. cfn.getRichStringCellValue();
  421. fail();
  422. } catch(IllegalStateException e) {}
  423. assertEquals("Testing", cfs.getStringCellValue());
  424. try {
  425. cfs.getNumericCellValue();
  426. fail();
  427. } catch(IllegalStateException e) {}
  428. }
  429. }
  430. /**
  431. * A problem file from a non-standard source (a scientific instrument that saves its
  432. * output as an .xlsx file) that have two issues:
  433. * 1. The Content Type part name is lower-case: [content_types].xml
  434. * 2. The file appears to use backslashes as path separators
  435. *
  436. * The OPC spec tolerates both of these peculiarities, so does POI
  437. */
  438. @Test
  439. public void bug49609() throws Exception {
  440. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx");
  441. assertEquals("FAM", wb.getSheetName(0));
  442. assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
  443. }
  444. @Test
  445. public void bug49783() throws Exception {
  446. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx");
  447. Sheet sheet = wb.getSheetAt(0);
  448. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  449. Cell cell;
  450. cell = sheet.getRow(0).getCell(0);
  451. assertEquals("#REF!*#REF!", cell.getCellFormula());
  452. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  453. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  454. Name nm1 = wb.getName("sale_1");
  455. assertNotNull("name sale_1 should be present", nm1);
  456. assertEquals("Sheet1!#REF!", nm1.getRefersToFormula());
  457. Name nm2 = wb.getName("sale_2");
  458. assertNotNull("name sale_2 should be present", nm2);
  459. assertEquals("Sheet1!#REF!", nm2.getRefersToFormula());
  460. cell = sheet.getRow(1).getCell(0);
  461. assertEquals("sale_1*sale_2", cell.getCellFormula());
  462. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  463. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  464. }
  465. /**
  466. * Creating a rich string of "hello world" and applying
  467. * a font to characters 1-5 means we have two strings,
  468. * "hello" and " world". As such, we need to apply
  469. * preserve spaces to the 2nd bit, lest we end up
  470. * with something like "helloworld" !
  471. */
  472. @Test
  473. public void bug49941() throws Exception {
  474. XSSFWorkbook wb = new XSSFWorkbook();
  475. XSSFSheet s = wb.createSheet();
  476. XSSFRow r = s.createRow(0);
  477. XSSFCell c = r.createCell(0);
  478. // First without fonts
  479. c.setCellValue(
  480. new XSSFRichTextString(" with spaces ")
  481. );
  482. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  483. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  484. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  485. // Should have the preserve set
  486. assertEquals(
  487. 1,
  488. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  489. );
  490. assertEquals(
  491. "preserve",
  492. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  493. );
  494. // Save and check
  495. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  496. wb.close();
  497. s = wbBack.getSheetAt(0);
  498. r = s.getRow(0);
  499. c = r.getCell(0);
  500. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  501. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  502. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  503. // Change the string
  504. c.setCellValue(
  505. new XSSFRichTextString("hello world")
  506. );
  507. assertEquals("hello world", c.getRichStringCellValue().toString());
  508. // Won't have preserve
  509. assertEquals(
  510. 0,
  511. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  512. );
  513. // Apply a font
  514. XSSFFont f = wbBack.createFont();
  515. f.setBold(true);
  516. c.getRichStringCellValue().applyFont(0, 5, f);
  517. assertEquals("hello world", c.getRichStringCellValue().toString());
  518. // Does need preserving on the 2nd part
  519. assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  520. assertEquals(
  521. 0,
  522. c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
  523. );
  524. assertEquals(
  525. 1,
  526. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
  527. );
  528. assertEquals(
  529. "preserve",
  530. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  531. );
  532. // Save and check
  533. wbBack = XSSFTestDataSamples.writeOutAndReadBack(wbBack);
  534. s = wbBack.getSheetAt(0);
  535. r = s.getRow(0);
  536. c = r.getCell(0);
  537. assertEquals("hello world", c.getRichStringCellValue().toString());
  538. wbBack.close();
  539. }
  540. /**
  541. * Repeatedly writing the same file which has styles
  542. */
  543. @Test
  544. public void bug49940() throws Exception {
  545. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx");
  546. assertEquals(3, wb.getNumberOfSheets());
  547. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  548. ByteArrayOutputStream b1 = new ByteArrayOutputStream();
  549. ByteArrayOutputStream b2 = new ByteArrayOutputStream();
  550. ByteArrayOutputStream b3 = new ByteArrayOutputStream();
  551. wb.write(b1);
  552. wb.write(b2);
  553. wb.write(b3);
  554. for(byte[] data : new byte[][] {
  555. b1.toByteArray(), b2.toByteArray(), b3.toByteArray()
  556. }) {
  557. ByteArrayInputStream bais = new ByteArrayInputStream(data);
  558. wb = new XSSFWorkbook(bais);
  559. assertEquals(3, wb.getNumberOfSheets());
  560. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  561. }
  562. }
  563. /**
  564. * Various ways of removing a cell formula should all zap the calcChain
  565. * entry.
  566. */
  567. @Test
  568. public void bug49966() throws Exception {
  569. XSSFWorkbook wb = XSSFTestDataSamples
  570. .openSampleWorkbook("shared_formulas.xlsx");
  571. XSSFSheet sheet = wb.getSheetAt(0);
  572. Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  573. // CalcChain has lots of entries
  574. CalculationChain cc = wb.getCalculationChain();
  575. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  576. assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR());
  577. assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR());
  578. assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR());
  579. assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR());
  580. assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR());
  581. assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR());
  582. assertEquals(40, cc.getCTCalcChain().sizeOfCArray());
  583. wbRead.close();
  584. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  585. // Try various ways of changing the formulas
  586. // If it stays a formula, chain entry should remain
  587. // Otherwise should go
  588. sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay
  589. sheet.getRow(2).getCell(0).setCellFormula(null); // go
  590. sheet.getRow(3).getCell(0).setCellType(Cell.CELL_TYPE_FORMULA); // stay
  591. wbRead.close();
  592. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  593. sheet.getRow(4).getCell(0).setCellType(Cell.CELL_TYPE_STRING); // go
  594. wbRead.close();
  595. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  596. validateCells(sheet);
  597. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  598. validateCells(sheet);
  599. wbRead.close();
  600. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  601. sheet.getRow(6).getCell(0).setCellType(Cell.CELL_TYPE_BLANK); // go
  602. wbRead.close();
  603. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  604. sheet.getRow(7).getCell(0).setCellValue((String) null); // go
  605. wbRead.close();
  606. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  607. // Save and check
  608. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  609. assertEquals(35, cc.getCTCalcChain().sizeOfCArray());
  610. cc = wb.getCalculationChain();
  611. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  612. assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR());
  613. assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR());
  614. wbRead.close();
  615. }
  616. @Test
  617. public void bug49966Row() throws Exception {
  618. XSSFWorkbook wb = XSSFTestDataSamples
  619. .openSampleWorkbook("shared_formulas.xlsx");
  620. XSSFSheet sheet = wb.getSheetAt(0);
  621. validateCells(sheet);
  622. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  623. validateCells(sheet);
  624. }
  625. private void validateCells(XSSFSheet sheet) {
  626. for(Row row : sheet) {
  627. // trigger handling
  628. ((XSSFRow)row).onDocumentWrite();
  629. }
  630. }
  631. @Test
  632. public void bug49156() throws Exception {
  633. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx");
  634. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  635. Sheet sheet = wb.getSheetAt(0);
  636. for(Row row : sheet){
  637. for(Cell cell : row){
  638. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){
  639. formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells
  640. }
  641. }
  642. }
  643. }
  644. /**
  645. * Newlines are valid characters in a formula
  646. */
  647. @Test
  648. public void bug50440And51875() throws Exception {
  649. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx");
  650. Sheet s = wb.getSheetAt(0);
  651. Cell c = s.getRow(0).getCell(0);
  652. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  653. assertEquals(3.0, c.getNumericCellValue(), 0);
  654. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  655. formulaEvaluator.evaluateFormulaCell(c);
  656. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  657. assertEquals(3.0, c.getNumericCellValue(), 0);
  658. // For 51875
  659. Cell b3 = s.getRow(2).getCell(1);
  660. formulaEvaluator.evaluateFormulaCell(b3);
  661. assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas
  662. assertEquals(3.0, b3.getNumericCellValue(), 0);
  663. }
  664. /**
  665. * Moving a cell comment from one cell to another
  666. */
  667. @Test
  668. public void bug50795() throws Exception {
  669. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx");
  670. XSSFSheet sheet = wb.getSheetAt(0);
  671. XSSFRow row = sheet.getRow(0);
  672. XSSFCell cellWith = row.getCell(0);
  673. XSSFCell cellWithoutComment = row.getCell(1);
  674. assertNotNull(cellWith.getCellComment());
  675. assertNull(cellWithoutComment.getCellComment());
  676. String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
  677. XSSFComment comment = cellWith.getCellComment();
  678. assertEquals(exp, comment.getString().getString());
  679. // Check we can write it out and read it back as-is
  680. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  681. sheet = wb.getSheetAt(0);
  682. row = sheet.getRow(0);
  683. cellWith = row.getCell(0);
  684. cellWithoutComment = row.getCell(1);
  685. // Double check things are as expected
  686. assertNotNull(cellWith.getCellComment());
  687. assertNull(cellWithoutComment.getCellComment());
  688. comment = cellWith.getCellComment();
  689. assertEquals(exp, comment.getString().getString());
  690. // Move the comment
  691. cellWithoutComment.setCellComment(comment);
  692. // Write out and re-check
  693. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  694. sheet = wb.getSheetAt(0);
  695. row = sheet.getRow(0);
  696. // Ensure it swapped over
  697. cellWith = row.getCell(0);
  698. cellWithoutComment = row.getCell(1);
  699. assertNull(cellWith.getCellComment());
  700. assertNotNull(cellWithoutComment.getCellComment());
  701. comment = cellWithoutComment.getCellComment();
  702. assertEquals(exp, comment.getString().getString());
  703. }
  704. /**
  705. * When the cell background colour is set with one of the first
  706. * two columns of the theme colour palette, the colours are
  707. * shades of white or black.
  708. * For those cases, ensure we don't break on reading the colour
  709. */
  710. @Test
  711. public void bug50299() throws Exception {
  712. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx");
  713. // Check all the colours
  714. for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
  715. Sheet s = wb.getSheetAt(sn);
  716. for(Row r : s) {
  717. for(Cell c : r) {
  718. CellStyle cs = c.getCellStyle();
  719. if(cs != null) {
  720. cs.getFillForegroundColor();
  721. }
  722. }
  723. }
  724. }
  725. // Check one bit in detail
  726. // Check that we get back foreground=0 for the theme colours,
  727. // and background=64 for the auto colouring
  728. Sheet s = wb.getSheetAt(0);
  729. assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor());
  730. assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor());
  731. assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor());
  732. assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor());
  733. }
  734. /**
  735. * Excel .xls style indexed colours in a .xlsx file
  736. */
  737. @Test
  738. public void bug50786() throws Exception {
  739. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx");
  740. XSSFSheet s = wb.getSheetAt(0);
  741. XSSFRow r = s.getRow(2);
  742. // Check we have the right cell
  743. XSSFCell c = r.getCell(1);
  744. assertEquals("test\u00a0", c.getRichStringCellValue().getString());
  745. // It should be light green
  746. XSSFCellStyle cs = c.getCellStyle();
  747. assertEquals(42, cs.getFillForegroundColor());
  748. assertEquals(42, cs.getFillForegroundColorColor().getIndexed());
  749. assertNotNull(cs.getFillForegroundColorColor().getRgb());
  750. assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex());
  751. }
  752. /**
  753. * If the border colours are set with themes, then we
  754. * should still be able to get colours
  755. */
  756. @Test
  757. public void bug50846() throws Exception {
  758. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx");
  759. XSSFSheet sheet = wb.getSheetAt(0);
  760. XSSFRow row = sheet.getRow(0);
  761. // Border from a theme, brown
  762. XSSFCell cellT = row.getCell(0);
  763. XSSFCellStyle styleT = cellT.getCellStyle();
  764. XSSFColor colorT = styleT.getBottomBorderXSSFColor();
  765. assertEquals(5, colorT.getTheme());
  766. assertEquals("FFC0504D", colorT.getARGBHex());
  767. // Border from a style direct, red
  768. XSSFCell cellS = row.getCell(1);
  769. XSSFCellStyle styleS = cellS.getCellStyle();
  770. XSSFColor colorS = styleS.getBottomBorderXSSFColor();
  771. assertEquals(0, colorS.getTheme());
  772. assertEquals("FFFF0000", colorS.getARGBHex());
  773. }
  774. /**
  775. * Fonts where their colours come from the theme rather
  776. * then being set explicitly still should allow the
  777. * fetching of the RGB.
  778. */
  779. @Test
  780. public void bug50784() throws Exception {
  781. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx");
  782. XSSFSheet s = wb.getSheetAt(0);
  783. XSSFRow r = s.getRow(0);
  784. // Column 1 has a font with regular colours
  785. XSSFCell cr = r.getCell(1);
  786. XSSFFont fr = wb.getFontAt( cr.getCellStyle().getFontIndex() );
  787. XSSFColor colr = fr.getXSSFColor();
  788. // No theme, has colours
  789. assertEquals(0, colr.getTheme());
  790. assertNotNull( colr.getRgb() );
  791. // Column 0 has a font with colours from a theme
  792. XSSFCell ct = r.getCell(0);
  793. XSSFFont ft = wb.getFontAt( ct.getCellStyle().getFontIndex() );
  794. XSSFColor colt = ft.getXSSFColor();
  795. // Has a theme, which has the colours on it
  796. assertEquals(9, colt.getTheme());
  797. XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme());
  798. assertNotNull( themeC.getRgb() );
  799. assertNotNull( colt.getRgb() );
  800. assertEquals( themeC.getARGBHex(), colt.getARGBHex() ); // The same colour
  801. }
  802. /**
  803. * New lines were being eaten when setting a font on
  804. * a rich text string
  805. */
  806. @Test
  807. public void bug48877() throws Exception {
  808. String text = "Use \n with word wrap on to create a new line.\n" +
  809. "This line finishes with two trailing spaces. ";
  810. XSSFWorkbook wb = new XSSFWorkbook();
  811. XSSFSheet sheet = wb.createSheet();
  812. Font font1 = wb.createFont();
  813. font1.setColor((short) 20);
  814. Font font2 = wb.createFont();
  815. font2.setColor(Font.COLOR_RED);
  816. Font font3 = wb.getFontAt((short)0);
  817. XSSFRow row = sheet.createRow(2);
  818. XSSFCell cell = row.createCell(2);
  819. XSSFRichTextString richTextString =
  820. wb.getCreationHelper().createRichTextString(text);
  821. // Check the text has the newline
  822. assertEquals(text, richTextString.getString());
  823. // Apply the font
  824. richTextString.applyFont(font3);
  825. richTextString.applyFont(0, 3, font1);
  826. cell.setCellValue(richTextString);
  827. // To enable newlines you need set a cell styles with wrap=true
  828. CellStyle cs = wb.createCellStyle();
  829. cs.setWrapText(true);
  830. cell.setCellStyle(cs);
  831. // Check the text has the
  832. assertEquals(text, cell.getStringCellValue());
  833. // Save the file and re-read it
  834. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  835. wb.close();
  836. sheet = wbBack.getSheetAt(0);
  837. row = sheet.getRow(2);
  838. cell = row.getCell(2);
  839. assertEquals(text, cell.getStringCellValue());
  840. // Now add a 2nd, and check again
  841. int fontAt = text.indexOf("\n", 6);
  842. cell.getRichStringCellValue().applyFont(10, fontAt+1, font2);
  843. assertEquals(text, cell.getStringCellValue());
  844. assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
  845. assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT());
  846. String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT();
  847. assertEquals("line.\n", r3.substring(r3.length()-6));
  848. // Save and re-check
  849. wbBack = XSSFTestDataSamples.writeOutAndReadBack(wbBack);
  850. sheet = wbBack.getSheetAt(0);
  851. row = sheet.getRow(2);
  852. cell = row.getCell(2);
  853. assertEquals(text, cell.getStringCellValue());
  854. wbBack.close();
  855. // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx");
  856. // wb.write(out);
  857. // out.close();
  858. }
  859. /**
  860. * Adding sheets when one has a table, then re-ordering
  861. */
  862. @Test
  863. public void bug50867() throws Exception {
  864. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx");
  865. assertEquals(3, wb.getNumberOfSheets());
  866. XSSFSheet s1 = wb.getSheetAt(0);
  867. XSSFSheet s2 = wb.getSheetAt(1);
  868. XSSFSheet s3 = wb.getSheetAt(2);
  869. assertEquals(1, s1.getTables().size());
  870. assertEquals(0, s2.getTables().size());
  871. assertEquals(0, s3.getTables().size());
  872. XSSFTable t = s1.getTables().get(0);
  873. assertEquals("Tabella1", t.getName());
  874. assertEquals("Tabella1", t.getDisplayName());
  875. assertEquals("A1:C3", t.getCTTable().getRef());
  876. // Add a sheet and re-order
  877. XSSFSheet s4 = wb.createSheet("NewSheet");
  878. wb.setSheetOrder(s4.getSheetName(), 0);
  879. // Check on tables
  880. assertEquals(1, s1.getTables().size());
  881. assertEquals(0, s2.getTables().size());
  882. assertEquals(0, s3.getTables().size());
  883. assertEquals(0, s4.getTables().size());
  884. // Refetch to get the new order
  885. s1 = wb.getSheetAt(0);
  886. s2 = wb.getSheetAt(1);
  887. s3 = wb.getSheetAt(2);
  888. s4 = wb.getSheetAt(3);
  889. assertEquals(0, s1.getTables().size());
  890. assertEquals(1, s2.getTables().size());
  891. assertEquals(0, s3.getTables().size());
  892. assertEquals(0, s4.getTables().size());
  893. // Save and re-load
  894. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  895. s1 = wb.getSheetAt(0);
  896. s2 = wb.getSheetAt(1);
  897. s3 = wb.getSheetAt(2);
  898. s4 = wb.getSheetAt(3);
  899. assertEquals(0, s1.getTables().size());
  900. assertEquals(1, s2.getTables().size());
  901. assertEquals(0, s3.getTables().size());
  902. assertEquals(0, s4.getTables().size());
  903. t = s2.getTables().get(0);
  904. assertEquals("Tabella1", t.getName());
  905. assertEquals("Tabella1", t.getDisplayName());
  906. assertEquals("A1:C3", t.getCTTable().getRef());
  907. // Add some more tables, and check
  908. t = s2.createTable();
  909. t.setName("New 2");
  910. t.setDisplayName("New 2");
  911. t = s3.createTable();
  912. t.setName("New 3");
  913. t.setDisplayName("New 3");
  914. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  915. s1 = wb.getSheetAt(0);
  916. s2 = wb.getSheetAt(1);
  917. s3 = wb.getSheetAt(2);
  918. s4 = wb.getSheetAt(3);
  919. assertEquals(0, s1.getTables().size());
  920. assertEquals(2, s2.getTables().size());
  921. assertEquals(1, s3.getTables().size());
  922. assertEquals(0, s4.getTables().size());
  923. t = s2.getTables().get(0);
  924. assertEquals("Tabella1", t.getName());
  925. assertEquals("Tabella1", t.getDisplayName());
  926. assertEquals("A1:C3", t.getCTTable().getRef());
  927. t = s2.getTables().get(1);
  928. assertEquals("New 2", t.getName());
  929. assertEquals("New 2", t.getDisplayName());
  930. t = s3.getTables().get(0);
  931. assertEquals("New 3", t.getName());
  932. assertEquals("New 3", t.getDisplayName());
  933. // Check the relationships
  934. assertEquals(0, s1.getRelations().size());
  935. assertEquals(3, s2.getRelations().size());
  936. assertEquals(1, s3.getRelations().size());
  937. assertEquals(0, s4.getRelations().size());
  938. assertEquals(
  939. XSSFRelation.PRINTER_SETTINGS.getContentType(),
  940. s2.getRelations().get(0).getPackagePart().getContentType()
  941. );
  942. assertEquals(
  943. XSSFRelation.TABLE.getContentType(),
  944. s2.getRelations().get(1).getPackagePart().getContentType()
  945. );
  946. assertEquals(
  947. XSSFRelation.TABLE.getContentType(),
  948. s2.getRelations().get(2).getPackagePart().getContentType()
  949. );
  950. assertEquals(
  951. XSSFRelation.TABLE.getContentType(),
  952. s3.getRelations().get(0).getPackagePart().getContentType()
  953. );
  954. assertEquals(
  955. "/xl/tables/table3.xml",
  956. s3.getRelations().get(0).getPackagePart().getPartName().toString()
  957. );
  958. }
  959. /**
  960. * Setting repeating rows and columns shouldn't break
  961. * any print settings that were there before
  962. */
  963. @SuppressWarnings("deprecation")
  964. @Test
  965. public void bug49253() throws Exception {
  966. XSSFWorkbook wb1 = new XSSFWorkbook();
  967. XSSFWorkbook wb2 = new XSSFWorkbook();
  968. // No print settings before repeating
  969. XSSFSheet s1 = wb1.createSheet();
  970. assertEquals(false, s1.getCTWorksheet().isSetPageSetup());
  971. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  972. wb1.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  973. assertEquals(true, s1.getCTWorksheet().isSetPageSetup());
  974. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  975. XSSFPrintSetup ps1 = s1.getPrintSetup();
  976. assertEquals(false, ps1.getValidSettings());
  977. assertEquals(false, ps1.getLandscape());
  978. // Had valid print settings before repeating
  979. XSSFSheet s2 = wb2.createSheet();
  980. XSSFPrintSetup ps2 = s2.getPrintSetup();
  981. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  982. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  983. ps2.setLandscape(false);
  984. assertEquals(true, ps2.getValidSettings());
  985. assertEquals(false, ps2.getLandscape());
  986. wb2.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  987. ps2 = s2.getPrintSetup();
  988. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  989. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  990. assertEquals(true, ps2.getValidSettings());
  991. assertEquals(false, ps2.getLandscape());
  992. wb1.close();
  993. wb2.close();
  994. }
  995. /**
  996. * Default Column style
  997. */
  998. @Test
  999. public void bug51037() throws Exception {
  1000. XSSFWorkbook wb = new XSSFWorkbook();
  1001. XSSFSheet s = wb.createSheet();
  1002. CellStyle defaultStyle = wb.getCellStyleAt((short)0);
  1003. assertEquals(0, defaultStyle.getIndex());
  1004. CellStyle blueStyle = wb.createCellStyle();
  1005. blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  1006. blueStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  1007. assertEquals(1, blueStyle.getIndex());
  1008. CellStyle pinkStyle = wb.createCellStyle();
  1009. pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
  1010. pinkStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  1011. assertEquals(2, pinkStyle.getIndex());
  1012. // Starts empty
  1013. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1014. CTCols cols = s.getCTWorksheet().getColsArray(0);
  1015. assertEquals(0, cols.sizeOfColArray());
  1016. // Add some rows and columns
  1017. XSSFRow r1 = s.createRow(0);
  1018. XSSFRow r2 = s.createRow(1);
  1019. r1.createCell(0);
  1020. r1.createCell(2);
  1021. r2.createCell(0);
  1022. r2.createCell(3);
  1023. // Check no style is there
  1024. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1025. assertEquals(0, cols.sizeOfColArray());
  1026. assertEquals(defaultStyle, s.getColumnStyle(0));
  1027. assertEquals(defaultStyle, s.getColumnStyle(2));
  1028. assertEquals(defaultStyle, s.getColumnStyle(3));
  1029. // Apply the styles
  1030. s.setDefaultColumnStyle(0, pinkStyle);
  1031. s.setDefaultColumnStyle(3, blueStyle);
  1032. // Check
  1033. assertEquals(pinkStyle, s.getColumnStyle(0));
  1034. assertEquals(defaultStyle, s.getColumnStyle(2));
  1035. assertEquals(blueStyle, s.getColumnStyle(3));
  1036. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  1037. assertEquals(2, cols.sizeOfColArray());
  1038. assertEquals(1, cols.getColArray(0).getMin());
  1039. assertEquals(1, cols.getColArray(0).getMax());
  1040. assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
  1041. assertEquals(4, cols.getColArray(1).getMin());
  1042. assertEquals(4, cols.getColArray(1).getMax());
  1043. assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
  1044. // Save, re-load and re-check
  1045. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1046. wb.close();
  1047. s = wbBack.getSheetAt(0);
  1048. defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex());
  1049. blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex());
  1050. pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex());
  1051. assertEquals(pinkStyle, s.getColumnStyle(0));
  1052. assertEquals(defaultStyle, s.getColumnStyle(2));
  1053. assertEquals(blueStyle, s.getColumnStyle(3));
  1054. wbBack.close();
  1055. }
  1056. /**
  1057. * Repeatedly writing a file.
  1058. * Something with the SharedStringsTable currently breaks...
  1059. */
  1060. @Test
  1061. public void bug46662() throws Exception {
  1062. // New file
  1063. XSSFWorkbook wb = new XSSFWorkbook();
  1064. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1065. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1066. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1067. // Simple file
  1068. wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1069. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1070. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1071. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1072. // Complex file
  1073. // TODO
  1074. }
  1075. /**
  1076. * Colours and styles when the list has gaps in it
  1077. */
  1078. @Test
  1079. public void bug51222() throws Exception {
  1080. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx");
  1081. XSSFSheet s = wb.getSheetAt(0);
  1082. XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0);
  1083. XSSFCell cA5_1F497D = s.getRow(4).getCell(0);
  1084. // Check the text
  1085. assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString());
  1086. assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString());
  1087. // Check the styles assigned to them
  1088. assertEquals(4, cA4_EEECE1.getCTCell().getS());
  1089. assertEquals(5, cA5_1F497D.getCTCell().getS());
  1090. // Check we look up the correct style
  1091. assertEquals(4, cA4_EEECE1.getCellStyle().getIndex());
  1092. assertEquals(5, cA5_1F497D.getCellStyle().getIndex());
  1093. // Check the fills on them at the low level
  1094. assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId());
  1095. assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId());
  1096. // These should reference themes 2 and 3
  1097. assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme());
  1098. assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme());
  1099. // Ensure we get the right colours for these themes
  1100. // TODO fix
  1101. // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex());
  1102. // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex());
  1103. // Finally check the colours on the styles
  1104. // TODO fix
  1105. // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1106. // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1107. }
  1108. @Test
  1109. public void bug51470() throws Exception {
  1110. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx");
  1111. XSSFSheet sh0 = wb.getSheetAt(0);
  1112. XSSFSheet sh1 = wb.cloneSheet(0);
  1113. List<POIXMLDocumentPart> rels0 = sh0.getRelations();
  1114. List<POIXMLDocumentPart> rels1 = sh1.getRelations();
  1115. assertEquals(1, rels0.size());
  1116. assertEquals(1, rels1.size());
  1117. assertEquals(rels0.get(0).getPackageRelationship(), rels1.get(0).getPackageRelationship());
  1118. }
  1119. /**
  1120. * Add comments to Sheet 1, when Sheet 2 already has
  1121. * comments (so /xl/comments1.xml is taken)
  1122. */
  1123. @Test
  1124. public void bug51850() {
  1125. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx");
  1126. XSSFSheet sh1 = wb.getSheetAt(0);
  1127. XSSFSheet sh2 = wb.getSheetAt(1);
  1128. // Sheet 2 has comments
  1129. assertNotNull(sh2.getCommentsTable(false));
  1130. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1131. // Sheet 1 doesn't (yet)
  1132. assertNull(sh1.getCommentsTable(false));
  1133. // Try to add comments to Sheet 1
  1134. CreationHelper factory = wb.getCreationHelper();
  1135. Drawing drawing = sh1.createDrawingPatriarch();
  1136. ClientAnchor anchor = factory.createClientAnchor();
  1137. anchor.setCol1(0);
  1138. anchor.setCol2(4);
  1139. anchor.setRow1(0);
  1140. anchor.setRow2(1);
  1141. Comment comment1 = drawing.createCellComment(anchor);
  1142. comment1.setString(
  1143. factory.createRichTextString("I like this cell. It's my favourite."));
  1144. comment1.setAuthor("Bob T. Fish");
  1145. anchor = factory.createClientAnchor();
  1146. anchor.setCol1(0);
  1147. anchor.setCol2(4);
  1148. anchor.setRow1(1);
  1149. anchor.setRow2(1);
  1150. Comment comment2 = drawing.createCellComment(anchor);
  1151. comment2.setString(
  1152. factory.createRichTextString("This is much less fun..."));
  1153. comment2.setAuthor("Bob T. Fish");
  1154. Cell c1 = sh1.getRow(0).createCell(4);
  1155. c1.setCellValue(2.3);
  1156. c1.setCellComment(comment1);
  1157. Cell c2 = sh1.getRow(0).createCell(5);
  1158. c2.setCellValue(2.1);
  1159. c2.setCellComment(comment2);
  1160. // Save and re-load
  1161. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1162. sh1 = wb.getSheetAt(0);
  1163. sh2 = wb.getSheetAt(1);
  1164. // Check the comments
  1165. assertNotNull(sh2.getCommentsTable(false));
  1166. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1167. assertNotNull(sh1.getCommentsTable(false));
  1168. assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
  1169. }
  1170. /**
  1171. * Sheet names with a , in them
  1172. */
  1173. @Test
  1174. public void bug51963() throws Exception {
  1175. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx");
  1176. XSSFSheet sheet = wb.getSheetAt(0);
  1177. assertEquals("Abc,1", sheet.getSheetName());
  1178. Name name = wb.getName("Intekon.ProdCodes");
  1179. assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula());
  1180. AreaReference ref = new AreaReference(name.getRefersToFormula());
  1181. assertEquals(0, ref.getFirstCell().getRow());
  1182. assertEquals(0, ref.getFirstCell().getCol());
  1183. assertEquals(1, ref.getLastCell().getRow());
  1184. assertEquals(0, ref.getLastCell().getCol());
  1185. }
  1186. /**
  1187. * Sum across multiple workbooks
  1188. * eg =SUM($Sheet1.C1:$Sheet4.C1)
  1189. * DISABLED As we can't currently evaluate these
  1190. */
  1191. @Ignore
  1192. public void bug48703() throws Exception {
  1193. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx");
  1194. XSSFSheet sheet = wb.getSheetAt(0);
  1195. // Contains two forms, one with a range and one a list
  1196. XSSFRow r1 = sheet.getRow(0);
  1197. XSSFRow r2 = sheet.getRow(1);
  1198. XSSFCell c1 = r1.getCell(1);
  1199. XSSFCell c2 = r2.getCell(1);
  1200. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1201. assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula());
  1202. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1203. assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula());
  1204. // Try evaluating both
  1205. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  1206. eval.evaluateFormulaCell(c1);
  1207. eval.evaluateFormulaCell(c2);
  1208. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1209. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1210. }
  1211. /**
  1212. * Bugzilla 51710: problems reading shared formuals from .xlsx
  1213. */
  1214. @Test
  1215. public void bug51710() {
  1216. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx");
  1217. final String[] columns = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
  1218. final int rowMax = 500; // bug triggers on row index 59
  1219. Sheet sheet = wb.getSheetAt(0);
  1220. // go through all formula cells
  1221. for (int rInd = 2; rInd <= rowMax; rInd++) {
  1222. Row row = sheet.getRow(rInd);
  1223. for (int cInd = 1; cInd <= 12; cInd++) {
  1224. Cell cell = row.getCell(cInd);
  1225. String formula = cell.getCellFormula();
  1226. CellReference ref = new CellReference(cell);
  1227. //simulate correct answer
  1228. String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2";
  1229. assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula);
  1230. }
  1231. }
  1232. }
  1233. /**
  1234. * Bug 53101:
  1235. */
  1236. @Test
  1237. public void bug5301(){
  1238. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx");
  1239. FormulaEvaluator evaluator =
  1240. workbook.getCreationHelper().createFormulaEvaluator();
  1241. // A1: SUM(B1: IZ1)
  1242. double a1Value =
  1243. evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(0)).getNumberValue();
  1244. // Assert
  1245. assertEquals(259.0, a1Value, 0.0);
  1246. // KY: SUM(B1: IZ1)
  1247. /*double ky1Value =*/
  1248. evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(310)).getNumberValue();
  1249. // Assert
  1250. assertEquals(259.0, a1Value, 0.0);
  1251. }
  1252. @Test
  1253. public void bug54436(){
  1254. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx");
  1255. if(!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")){
  1256. Function func = new Function() {
  1257. public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
  1258. return ErrorEval.NA;
  1259. }
  1260. };
  1261. WorkbookEvaluator.registerFunction("GETPIVOTDATA", func);
  1262. }
  1263. workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
  1264. }
  1265. /**
  1266. * Password Protected .xlsx files should give a helpful
  1267. * error message when called via WorkbookFactory with no password
  1268. */
  1269. @Test(expected=EncryptedDocumentException.class)
  1270. public void bug55692_poifs() throws Exception {
  1271. // Via a POIFSFileSystem
  1272. POIFSFileSystem fsP = new POIFSFileSystem(
  1273. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1274. WorkbookFactory.create(fsP);
  1275. }
  1276. public void bug55692_stream() throws Exception {
  1277. // Directly on a Stream, will go via NPOIFS and spot it's
  1278. // actually a .xlsx file encrypted with the default password, and open
  1279. Workbook wb = WorkbookFactory.create(
  1280. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1281. assertNotNull(wb);
  1282. assertEquals(3, wb.getNumberOfSheets());
  1283. }
  1284. public void bug55692_npoifs() throws Exception {
  1285. // Via a NPOIFSFileSystem, will spot it's actually a .xlsx file
  1286. // encrypted with the default password, and open
  1287. NPOIFSFileSystem fsNP = new NPOIFSFileSystem(
  1288. POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1289. Workbook wb = WorkbookFactory.create(fsNP);
  1290. assertNotNull(wb);
  1291. assertEquals(3, wb.getNumberOfSheets());
  1292. }
  1293. @Test
  1294. public void bug53282() {
  1295. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx");
  1296. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1297. assertEquals("#@_#", c.getStringCellValue());
  1298. assertEquals("http://invalid.uri", c.getHyperlink().getAddress());
  1299. }
  1300. /**
  1301. * Was giving NullPointerException
  1302. * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead
  1303. * due to a lack of Styles Table
  1304. */
  1305. @Test
  1306. public void bug56278() throws Exception {
  1307. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx");
  1308. assertEquals(0, wb.getSheetIndex("Market Rates"));
  1309. // Save and re-check
  1310. Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1311. assertEquals(0, nwb.getSheetIndex("Market Rates"));
  1312. }
  1313. @Test
  1314. public void bug56315() {
  1315. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx");
  1316. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1317. CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c);
  1318. double rounded = cv.getNumberValue();
  1319. assertEquals(0.1, rounded, 0.0);
  1320. }
  1321. @Test
  1322. public void bug56468() throws Exception {
  1323. XSSFWorkbook wb = new XSSFWorkbook();
  1324. XSSFSheet sheet = wb.createSheet();
  1325. XSSFRow row = sheet.createRow(0);
  1326. XSSFCell cell = row.createCell(0);
  1327. cell.setCellValue("Hi");
  1328. sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0));
  1329. // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had different file-creation
  1330. // dates stored.
  1331. // We try to do a loop until the current second changes in order to avoid problems with some date information that is written to the ZIP and thus
  1332. // causes differences
  1333. long start = System.currentTimeMillis()/1000;
  1334. while(System.currentTimeMillis()/1000 == start) {
  1335. Thread.sleep(10);
  1336. }
  1337. ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
  1338. wb.write(bos);
  1339. byte firstSave[] = bos.toByteArray();
  1340. bos.reset();
  1341. wb.write(bos);
  1342. byte secondSave[] = bos.toByteArray();
  1343. /*OutputStream stream = new FileOutputStream("C:\\temp\\poi.xlsx");
  1344. try {
  1345. wb.write(stream);
  1346. } finally {
  1347. stream.close();
  1348. }*/
  1349. assertArrayEquals("Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave),
  1350. firstSave, secondSave);
  1351. wb.close();
  1352. }
  1353. /**
  1354. * ISO-8601 style cell formats with a T in them, eg
  1355. * cell format of "yyyy-MM-ddTHH:mm:ss"
  1356. */
  1357. @Test
  1358. public void bug54034() throws IOException {
  1359. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx");
  1360. Sheet sheet = wb.getSheet("Sheet1");
  1361. Row row = sheet.getRow(1);
  1362. Cell cell = row.getCell(2);
  1363. assertTrue(DateUtil.isCellDateFormatted(cell));
  1364. DataFormatter fmt = new DataFormatter();
  1365. assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
  1366. assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
  1367. }
  1368. @Test
  1369. public void testBug53798XLSX() throws IOException {
  1370. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1371. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1372. bug53798Work(wb, xlsOutput);
  1373. }
  1374. @Ignore("Shifting rows is not yet implemented in SXSSFSheet")
  1375. @Test
  1376. public void testBug53798XLSXStream() throws IOException {
  1377. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1378. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1379. bug53798Work(new SXSSFWorkbook(wb), xlsOutput);
  1380. }
  1381. @Test
  1382. public void testBug53798XLS() throws IOException {
  1383. Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls");
  1384. File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
  1385. bug53798Work(wb, xlsOutput);
  1386. }
  1387. /**
  1388. * SUMIF was throwing a NPE on some formulas
  1389. */
  1390. @Test
  1391. @Ignore("This bug is still to be fixed")
  1392. public void testBug56420SumIfNPE() throws Exception {
  1393. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx");
  1394. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1395. Sheet sheet = wb.getSheetAt(0);
  1396. Row r = sheet.getRow(2);
  1397. Cell c = r.getCell(2);
  1398. assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula());
  1399. evaluator.evaluateInCell(c);
  1400. }
  1401. private void bug53798Work(Workbook wb, File xlsOutput) throws IOException {
  1402. Sheet testSheet = wb.getSheetAt(0);
  1403. testSheet.shiftRows(2, 2, 1);
  1404. saveAndReloadReport(wb, xlsOutput);
  1405. // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about
  1406. // when shifted by less than -1 negative amount (try -2)
  1407. testSheet.shiftRows(3, 3, -1);
  1408. saveAndReloadReport(wb, xlsOutput);
  1409. testSheet.shiftRows(2, 2, 1);
  1410. saveAndReloadReport(wb, xlsOutput);
  1411. Row newRow = null;
  1412. Cell newCell = null;
  1413. // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted
  1414. // xlsx file with unreadable data in the negative shifted row.
  1415. // NOTE it's ok to create any other row.
  1416. newRow = testSheet.createRow(3);
  1417. saveAndReloadReport(wb, xlsOutput);
  1418. newCell = newRow.createCell(0);
  1419. saveAndReloadReport(wb, xlsOutput);
  1420. newCell.setCellValue("new Cell in row "+newRow.getRowNum());
  1421. saveAndReloadReport(wb, xlsOutput);
  1422. // 3) once a negative shift has been made any attempt to shift another group of rows
  1423. // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception:
  1424. // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException.
  1425. // NOTE: another negative shift on another group of rows is successful, provided no new rows in
  1426. // place of previously shifted rows were attempted to be created as explained above.
  1427. testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of
  1428. // the above has been tested
  1429. saveAndReloadReport(wb, xlsOutput);
  1430. }
  1431. /**
  1432. * XSSFCell.typeMismatch on certain blank cells when formatting
  1433. * with DataFormatter
  1434. */
  1435. @Test
  1436. public void bug56702() throws Exception {
  1437. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx");
  1438. Sheet sheet = wb.getSheetAt(0);
  1439. // Get wrong cell by row 8 & column 7
  1440. Cell cell = sheet.getRow(8).getCell(7);
  1441. assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
  1442. // Check the value - will be zero as it is <c><v/></c>
  1443. assertEquals(0.0, cell.getNumericCellValue(), 0.001);
  1444. // Try to format
  1445. DataFormatter formatter = new DataFormatter();
  1446. formatter.formatCellValue(cell);
  1447. // Check the formatting
  1448. assertEquals("0", formatter.formatCellValue(cell));
  1449. }
  1450. /**
  1451. * Formulas which reference named ranges, either in other
  1452. * sheets, or workbook scoped but in other workbooks.
  1453. * Used to fail with with errors like
  1454. * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9
  1455. * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name
  1456. */
  1457. @Test
  1458. public void bug56737() throws IOException {
  1459. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx");
  1460. // Check the named range definitions
  1461. Name nSheetScope = wb.getName("NR_To_A1");
  1462. Name nWBScope = wb.getName("NR_Global_B2");
  1463. assertNotNull(nSheetScope);
  1464. assertNotNull(nWBScope);
  1465. assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula());
  1466. assertEquals("Defines!$B$2", nWBScope.getRefersToFormula());
  1467. // Check the different kinds of formulas
  1468. Sheet s = wb.getSheetAt(0);
  1469. Cell cRefSName = s.getRow(1).getCell(3);
  1470. Cell cRefWName = s.getRow(2).getCell(3);
  1471. assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula());
  1472. // Note the formula, as stored in the file, has the external name index not filename
  1473. // TODO Provide a way to get the one with the filename
  1474. assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula());
  1475. // Try to evaluate them
  1476. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  1477. assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue());
  1478. assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue());
  1479. // Try to evaluate everything
  1480. eval.evaluateAll();
  1481. }
  1482. private void saveAndReloadReport(Workbook wb, File outFile) throws IOException {
  1483. // run some method on the font to verify if it is "disconnected" already
  1484. //for(short i = 0;i < 256;i++)
  1485. {
  1486. Font font = wb.getFontAt((short)0);
  1487. if(font instanceof XSSFFont) {
  1488. XSSFFont xfont = (XSSFFont) wb.getFontAt((short)0);
  1489. CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont();
  1490. assertEquals(0, ctFont.sizeOfBArray());
  1491. }
  1492. }
  1493. FileOutputStream fileOutStream = new FileOutputStream(outFile);
  1494. wb.write(fileOutStream);
  1495. fileOutStream.close();
  1496. //System.out.println("File \""+outFile.getName()+"\" has been saved successfully");
  1497. FileInputStream is = new FileInputStream(outFile);
  1498. try {
  1499. Workbook newWB = null;
  1500. try {
  1501. if(wb instanceof XSSFWorkbook) {
  1502. newWB = new XSSFWorkbook(is);
  1503. } else if(wb instanceof HSSFWorkbook) {
  1504. newWB = new HSSFWorkbook(is);
  1505. } else if(wb instanceof SXSSFWorkbook) {
  1506. newWB = new SXSSFWorkbook(new XSSFWorkbook(is));
  1507. } else {
  1508. throw new IllegalStateException("Unknown workbook: " + wb);
  1509. }
  1510. assertNotNull(newWB.getSheet("test"));
  1511. } finally {
  1512. newWB.close();
  1513. }
  1514. } finally {
  1515. is.close();
  1516. }
  1517. }
  1518. @Test
  1519. public void testBug56688_1() {
  1520. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx");
  1521. checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
  1522. }
  1523. @Test
  1524. public void testBug56688_2() {
  1525. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx");
  1526. checkValue(excel, "#VALUE!");
  1527. }
  1528. @Test
  1529. public void testBug56688_3() {
  1530. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx");
  1531. checkValue(excel, "#VALUE!");
  1532. }
  1533. @Test
  1534. public void testBug56688_4() {
  1535. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx");
  1536. Calendar calendar = Calendar.getInstance();
  1537. calendar.add(Calendar.MONTH, 2);
  1538. double excelDate = DateUtil.getExcelDate(calendar.getTime());
  1539. NumberEval eval = new NumberEval(Math.floor(excelDate));
  1540. checkValue(excel, eval.getStringValue() + ".0");
  1541. }
  1542. /**
  1543. * New hyperlink with no initial cell reference, still need
  1544. * to be able to change it
  1545. * @throws IOException
  1546. */
  1547. @Test
  1548. public void testBug56527() throws IOException {
  1549. XSSFWorkbook wb = new XSSFWorkbook();
  1550. XSSFSheet sheet = wb.createSheet();
  1551. XSSFCreationHelper creationHelper = wb.getCreationHelper();
  1552. XSSFHyperlink hyperlink;
  1553. // Try with a cell reference
  1554. hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL);
  1555. sheet.addHyperlink(hyperlink);
  1556. hyperlink.setAddress("http://myurl");
  1557. hyperlink.setCellReference("B4");
  1558. assertEquals(3, hyperlink.getFirstRow());
  1559. assertEquals(1, hyperlink.getFirstColumn());
  1560. assertEquals(3, hyperlink.getLastRow());
  1561. assertEquals(1, hyperlink.getLastColumn());
  1562. // Try with explicit rows / columns
  1563. hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_URL);
  1564. sheet.addHyperlink(hyperlink);
  1565. hyperlink.setAddress("http://myurl");
  1566. hyperlink.setFirstRow(5);
  1567. hyperlink.setFirstColumn(3);
  1568. assertEquals(5, hyperlink.getFirstRow());
  1569. assertEquals(3, hyperlink.getFirstColumn());
  1570. assertEquals(5, hyperlink.getLastRow());
  1571. assertEquals(3, hyperlink.getLastColumn());
  1572. wb.close();
  1573. }
  1574. /**
  1575. * Shifting rows with a formula that references a
  1576. * function in another file
  1577. */
  1578. @Test
  1579. public void bug56502() throws Exception {
  1580. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx");
  1581. Sheet sheet = wb.getSheetAt(0);
  1582. Cell cFunc = sheet.getRow(3).getCell(0);
  1583. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1584. Cell cRef = sheet.getRow(3).createCell(1);
  1585. cRef.setCellFormula("A3");
  1586. // Shift it down one row
  1587. sheet.shiftRows(1, sheet.getLastRowNum(), 1);
  1588. // Check the new formulas: Function won't change, Reference will
  1589. cFunc = sheet.getRow(4).getCell(0);
  1590. assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula());
  1591. cRef = sheet.getRow(4).getCell(1);
  1592. assertEquals("A4", cRef.getCellFormula());
  1593. }
  1594. @Test
  1595. public void bug54764() throws Exception {
  1596. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx");
  1597. // Check the core properties - will be found but empty, due
  1598. // to the expansion being too much to be considered valid
  1599. POIXMLProperties props = new POIXMLProperties(pkg);
  1600. assertEquals(null, props.getCoreProperties().getTitle());
  1601. assertEquals(null, props.getCoreProperties().getSubject());
  1602. assertEquals(null, props.getCoreProperties().getDescription());
  1603. // Now check the spreadsheet itself
  1604. try {
  1605. new XSSFWorkbook(pkg);
  1606. fail("Should fail as too much expansion occurs");
  1607. } catch(POIXMLException e) {
  1608. // Expected
  1609. }
  1610. // Try with one with the entities in the Content Types
  1611. try {
  1612. XSSFTestDataSamples.openSamplePackage("54764-2.xlsx");
  1613. fail("Should fail as too much expansion occurs");
  1614. } catch(Exception e) {
  1615. // Expected
  1616. }
  1617. // Check we can still parse valid files after all that
  1618. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1619. assertEquals(3, wb.getNumberOfSheets());
  1620. }
  1621. /**
  1622. * CTDefinedNamesImpl should be included in the smaller
  1623. * poi-ooxml-schemas jar
  1624. */
  1625. @Test
  1626. public void bug57176() throws Exception {
  1627. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx");
  1628. CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames();
  1629. List<CTDefinedName> definedNameList = definedNames.getDefinedNameList();
  1630. for (CTDefinedName defName : definedNameList) {
  1631. assertNotNull(defName.getName());
  1632. assertNotNull(defName.getStringValue());
  1633. }
  1634. assertEquals("TestDefinedName", definedNameList.get(0).getName());
  1635. }
  1636. /**
  1637. * .xlsb files are not supported, but we should generate a helpful
  1638. * error message if given one
  1639. */
  1640. @Test
  1641. public void bug56800_xlsb() throws Exception {
  1642. // Can be opened at the OPC level
  1643. OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb");
  1644. // XSSF Workbook gives helpful error
  1645. try {
  1646. new XSSFWorkbook(pkg);
  1647. fail(".xlsb files not supported");
  1648. } catch (XLSBUnsupportedException e) {
  1649. // Good, detected and warned
  1650. }
  1651. // Workbook Factory gives helpful error on package
  1652. try {
  1653. WorkbookFactory.create(pkg);
  1654. fail(".xlsb files not supported");
  1655. } catch (XLSBUnsupportedException e) {
  1656. // Good, detected and warned
  1657. }
  1658. // Workbook Factory gives helpful error on file
  1659. File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb");
  1660. try {
  1661. WorkbookFactory.create(xlsbFile);
  1662. fail(".xlsb files not supported");
  1663. } catch (XLSBUnsupportedException e) {
  1664. // Good, detected and warned
  1665. }
  1666. }
  1667. private void checkValue(XSSFWorkbook excel, String expect) {
  1668. XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
  1669. evaluator.evaluateAll();
  1670. XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
  1671. CellValue value = evaluator.evaluate(cell);
  1672. assertEquals(expect, value.formatAsString());
  1673. }
  1674. @Test
  1675. public void testBug57196() throws IOException {
  1676. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx");
  1677. Sheet sheet = wb.getSheet("Feuil1");
  1678. Row mod=sheet.getRow(1);
  1679. mod.getCell(1).setCellValue(3);
  1680. HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  1681. // FileOutputStream fileOutput = new FileOutputStream("/tmp/57196.xlsx");
  1682. // wb.write(fileOutput);
  1683. // fileOutput.close();
  1684. wb.close();
  1685. }
  1686. @Test
  1687. public void test57196_Detail() {
  1688. XSSFWorkbook wb = new XSSFWorkbook();
  1689. XSSFSheet sheet = wb.createSheet("Sheet1");
  1690. XSSFRow row = sheet.createRow(0);
  1691. XSSFCell cell = row.createCell(0);
  1692. cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
  1693. XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
  1694. CellValue cv = fe.evaluate(cell);
  1695. assertNotNull(cv);
  1696. }
  1697. @Test
  1698. public void test57196_Detail2() {
  1699. XSSFWorkbook wb = new XSSFWorkbook();
  1700. XSSFSheet sheet = wb.createSheet("Sheet1");
  1701. XSSFRow row = sheet.createRow(0);
  1702. XSSFCell cell = row.createCell(0);
  1703. cell.setCellFormula("DEC2HEX(O2+D2)");
  1704. XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
  1705. CellValue cv = fe.evaluate(cell);
  1706. assertNotNull(cv);
  1707. }
  1708. @Test
  1709. public void test57196_WorkbookEvaluator() {
  1710. //System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
  1711. //System.setProperty("poi.log.level", "3");
  1712. try {
  1713. XSSFWorkbook wb = new XSSFWorkbook();
  1714. XSSFSheet sheet = wb.createSheet("Sheet1");
  1715. XSSFRow row = sheet.createRow(0);
  1716. XSSFCell cell = row.createCell(0);
  1717. cell.setCellValue("0");
  1718. cell = row.createCell(1);
  1719. cell.setCellValue(0);
  1720. cell = row.createCell(2);
  1721. cell.setCellValue(0);
  1722. // simple formula worked
  1723. cell.setCellFormula("DEC2HEX(O2+D2)");
  1724. WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1725. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1726. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1727. // this already failed! Hex2Dec did not correctly handle RefEval
  1728. cell.setCellFormula("HEX2DEC(O8)");
  1729. workbookEvaluator.clearAllCachedResultValues();
  1730. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1731. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1732. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1733. // slightly more complex one failed
  1734. cell.setCellFormula("HEX2DEC(O8)-O2+D2");
  1735. workbookEvaluator.clearAllCachedResultValues();
  1736. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1737. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1738. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1739. // more complicated failed
  1740. cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
  1741. workbookEvaluator.clearAllCachedResultValues();
  1742. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1743. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1744. // what other similar functions
  1745. cell.setCellFormula("DEC2BIN(O8)-O2+D2");
  1746. workbookEvaluator.clearAllCachedResultValues();
  1747. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1748. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1749. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1750. // what other similar functions
  1751. cell.setCellFormula("DEC2BIN(A1)");
  1752. workbookEvaluator.clearAllCachedResultValues();
  1753. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1754. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1755. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1756. // what other similar functions
  1757. cell.setCellFormula("BIN2DEC(B1)");
  1758. workbookEvaluator.clearAllCachedResultValues();
  1759. workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null);
  1760. workbookEvaluator.setDebugEvaluationOutputForNextEval(true);
  1761. workbookEvaluator.evaluate(new XSSFEvaluationCell(cell));
  1762. } finally {
  1763. System.clearProperty("org.apache.poi.util.POILogger");
  1764. System.clearProperty("poi.log.level");
  1765. }
  1766. }
  1767. @Test
  1768. public void bug57430() throws Exception {
  1769. XSSFWorkbook wb = new XSSFWorkbook();
  1770. try {
  1771. wb.createSheet("Sheet1");
  1772. XSSFName name1 = wb.createName();
  1773. name1.setNameName("FMLA");
  1774. name1.setRefersToFormula("Sheet1!$B$3");
  1775. } finally {
  1776. wb.close();
  1777. }
  1778. }
  1779. /**
  1780. * A .xlsx file with no Shared Strings table should open fine
  1781. * in read-only mode
  1782. */
  1783. @SuppressWarnings("resource")
  1784. @Test
  1785. public void bug57482() throws Exception {
  1786. for (PackageAccess access : new PackageAccess[] {
  1787. PackageAccess.READ_WRITE, PackageAccess.READ
  1788. }) {
  1789. File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx");
  1790. OPCPackage pkg = OPCPackage.open(file, access);
  1791. try {
  1792. // Try to open it and read the contents
  1793. XSSFWorkbook wb = new XSSFWorkbook(pkg);
  1794. assertNotNull(wb.getSharedStringSource());
  1795. assertEquals(0, wb.getSharedStringSource().getCount());
  1796. DataFormatter fmt = new DataFormatter();
  1797. XSSFSheet s = wb.getSheetAt(0);
  1798. assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0)));
  1799. assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1)));
  1800. assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0)));
  1801. // Add a text cell
  1802. s.getRow(0).createCell(3).setCellValue("Testing");
  1803. assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3)));
  1804. // Try to write-out and read again, should only work
  1805. // in read-write mode, not read-only mode
  1806. try {
  1807. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1808. if (access == PackageAccess.READ)
  1809. fail("Shouln't be able to write from read-only mode");
  1810. } catch (InvalidOperationException e) {
  1811. if (access == PackageAccess.READ) {
  1812. // Expected
  1813. } else {
  1814. // Shouldn't occur in write-mode
  1815. throw e;
  1816. }
  1817. }
  1818. // Check again
  1819. s = wb.getSheetAt(0);
  1820. assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0)));
  1821. assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1)));
  1822. assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0)));
  1823. assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3)));
  1824. } finally {
  1825. pkg.revert();
  1826. }
  1827. }
  1828. }
  1829. /**
  1830. * "Unknown error type: -60" fetching formula error value
  1831. */
  1832. @Test
  1833. public void bug57535() throws Exception {
  1834. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx");
  1835. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1836. evaluator.clearAllCachedResultValues();
  1837. Sheet sheet = wb.getSheet("Sheet1");
  1838. Cell cell = sheet.getRow(5).getCell(4);
  1839. assertEquals(Cell.CELL_TYPE_FORMULA, cell.getCellType());
  1840. assertEquals("E4+E5", cell.getCellFormula());
  1841. CellValue value = evaluator.evaluate(cell);
  1842. assertEquals(Cell.CELL_TYPE_ERROR, value.getCellType());
  1843. assertEquals(-60, value.getErrorValue());
  1844. assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString());
  1845. assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString());
  1846. }
  1847. @Test
  1848. public void test57165() throws IOException {
  1849. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
  1850. try {
  1851. removeAllSheetsBut(3, wb);
  1852. wb.cloneSheet(0); // Throws exception here
  1853. wb.setSheetName(1, "New Sheet");
  1854. //saveWorkbook(wb, fileName);
  1855. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1856. try {
  1857. } finally {
  1858. wbBack.close();
  1859. }
  1860. } finally {
  1861. wb.close();
  1862. }
  1863. }
  1864. @Test
  1865. public void test57165_create() throws IOException {
  1866. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx");
  1867. try {
  1868. removeAllSheetsBut(3, wb);
  1869. wb.createSheet("newsheet"); // Throws exception here
  1870. wb.setSheetName(1, "New Sheet");
  1871. //saveWorkbook(wb, fileName);
  1872. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1873. try {
  1874. } finally {
  1875. wbBack.close();
  1876. }
  1877. } finally {
  1878. wb.close();
  1879. }
  1880. }
  1881. private static void removeAllSheetsBut(int sheetIndex, Workbook wb)
  1882. {
  1883. int sheetNb = wb.getNumberOfSheets();
  1884. // Move this sheet at the first position
  1885. wb.setSheetOrder(wb.getSheetName(sheetIndex), 0);
  1886. for (int sn = sheetNb - 1; sn > 0; sn--)
  1887. {
  1888. wb.removeSheetAt(sn);
  1889. }
  1890. }
  1891. /**
  1892. * Sums 2 plus the cell at the left, indirectly to avoid reference
  1893. * problems when deleting columns, conditionally to stop recursion
  1894. */
  1895. private static final String FORMULA1 =
  1896. "IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0,"
  1897. + "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2";
  1898. /**
  1899. * Sums 2 plus the upper cell, indirectly to avoid reference
  1900. * problems when deleting rows, conditionally to stop recursion
  1901. */
  1902. private static final String FORMULA2 =
  1903. "IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0,"
  1904. + "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2";
  1905. /**
  1906. * Expected:
  1907. * [ 0][ 2][ 4]
  1908. * @throws IOException
  1909. */
  1910. @Test
  1911. public void testBug56820_Formula1() throws IOException {
  1912. Workbook wb = new XSSFWorkbook();
  1913. try {
  1914. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1915. Sheet sh = wb.createSheet();
  1916. sh.createRow(0).createCell(0).setCellValue(0.0d);
  1917. Cell formulaCell1 = sh.getRow(0).createCell(1);
  1918. Cell formulaCell2 = sh.getRow(0).createCell(2);
  1919. formulaCell1.setCellFormula(FORMULA1);
  1920. formulaCell2.setCellFormula(FORMULA1);
  1921. double A1 = evaluator.evaluate(formulaCell1).getNumberValue();
  1922. double A2 = evaluator.evaluate(formulaCell2).getNumberValue();
  1923. assertEquals(2, A1, 0);
  1924. assertEquals(4, A2, 0); //<-- FAILS EXPECTATIONS
  1925. } finally {
  1926. wb.close();
  1927. }
  1928. }
  1929. /**
  1930. * Expected:
  1931. * [ 0] <- number
  1932. * [ 2] <- formula
  1933. * [ 4] <- formula
  1934. * @throws IOException
  1935. */
  1936. @Test
  1937. public void testBug56820_Formula2() throws IOException {
  1938. Workbook wb = new XSSFWorkbook();
  1939. try {
  1940. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1941. Sheet sh = wb.createSheet();
  1942. sh.createRow(0).createCell(0).setCellValue(0.0d);
  1943. Cell formulaCell1 = sh.createRow(1).createCell(0);
  1944. Cell formulaCell2 = sh.createRow(2).createCell(0);
  1945. formulaCell1.setCellFormula(FORMULA2);
  1946. formulaCell2.setCellFormula(FORMULA2);
  1947. double A1 = evaluator.evaluate(formulaCell1).getNumberValue();
  1948. double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); //<-- FAILS EVALUATION
  1949. assertEquals(2, A1, 0);
  1950. assertEquals(4, A2, 0);
  1951. } finally {
  1952. wb.close();
  1953. }
  1954. }
  1955. @Test
  1956. public void test56467() throws IOException {
  1957. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx");
  1958. try {
  1959. Sheet orig = wb.getSheetAt(0);
  1960. assertNotNull(orig);
  1961. Sheet sheet = wb.cloneSheet(0);
  1962. Drawing drawing = sheet.createDrawingPatriarch();
  1963. for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) {
  1964. if (shape instanceof XSSFPicture) {
  1965. XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData();
  1966. assertNotNull(pictureData);
  1967. }
  1968. }
  1969. // OutputStream out = new FileOutputStream("/tmp/56467.xls");
  1970. // try {
  1971. // wb.write(out);
  1972. // } finally {
  1973. // out.close();
  1974. // }
  1975. } finally {
  1976. wb.close();
  1977. }
  1978. }
  1979. /**
  1980. * OOXML-Strict files
  1981. * Not currently working - namespace mis-match from XMLBeans
  1982. */
  1983. @Test
  1984. @Ignore("XMLBeans namespace mis-match on ooxml-strict files")
  1985. public void test57699() throws Exception {
  1986. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx");
  1987. assertEquals(3, wb.getNumberOfSheets());
  1988. // TODO Check sheet contents
  1989. // TODO Check formula evaluation
  1990. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1991. assertEquals(3, wbBack.getNumberOfSheets());
  1992. // TODO Re-check sheet contents
  1993. // TODO Re-check formula evaluation
  1994. }
  1995. @Test
  1996. public void testBug56295_MergeXlslsWithStyles() throws IOException {
  1997. XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx");
  1998. XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0);
  1999. XSSFRow srcRow = sheet.getRow(0);
  2000. XSSFCell oldCell = srcRow.getCell(0);
  2001. XSSFCellStyle cellStyle = oldCell.getCellStyle();
  2002. checkStyle(cellStyle);
  2003. // StylesTable table = xlsToAppendWorkbook.getStylesSource();
  2004. // List<XSSFCellFill> fills = table.getFills();
  2005. // System.out.println("Having " + fills.size() + " fills");
  2006. // for(XSSFCellFill fill : fills) {
  2007. // System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor());
  2008. // }
  2009. XSSFWorkbook targetWorkbook = new XSSFWorkbook();
  2010. XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName());
  2011. XSSFRow destRow = newSheet.createRow(0);
  2012. XSSFCell newCell = destRow.createCell(0);
  2013. //newCell.getCellStyle().cloneStyleFrom(cellStyle);
  2014. CellStyle newCellStyle = targetWorkbook.createCellStyle();
  2015. newCellStyle.cloneStyleFrom(cellStyle);
  2016. newCell.setCellStyle(newCellStyle);
  2017. checkStyle(newCell.getCellStyle());
  2018. newCell.setCellValue(oldCell.getStringCellValue());
  2019. // OutputStream os = new FileOutputStream("output.xlsm");
  2020. // try {
  2021. // targetWorkbook.write(os);
  2022. // } finally {
  2023. // os.close();
  2024. // }
  2025. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook);
  2026. XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
  2027. checkStyle(styleBack);
  2028. }
  2029. /**
  2030. * Paragraph with property BuFont but none of the properties
  2031. * BuNone, BuChar, and BuAutoNum, used to trigger a NPE
  2032. * Excel treats this as not-bulleted, so now do we
  2033. */
  2034. @Test
  2035. public void testBug57826() {
  2036. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx");
  2037. assertTrue("no sheets in workbook", workbook.getNumberOfSheets() >= 1);
  2038. XSSFSheet sheet = workbook.getSheetAt(0);
  2039. XSSFDrawing drawing = sheet.getDrawingPatriarch();
  2040. assertNotNull(drawing);
  2041. List<XSSFShape> shapes = drawing.getShapes();
  2042. assertEquals(1, shapes.size());
  2043. assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
  2044. XSSFSimpleShape shape = (XSSFSimpleShape)shapes.get(0);
  2045. // Used to throw a NPE
  2046. String text = shape.getText();
  2047. // No bulleting info included
  2048. assertEquals("test ok", text);
  2049. }
  2050. private void checkStyle(XSSFCellStyle cellStyle) {
  2051. assertNotNull(cellStyle);
  2052. assertEquals(0, cellStyle.getFillForegroundColor());
  2053. assertNotNull(cellStyle.getFillForegroundXSSFColor());
  2054. XSSFColor fgColor = cellStyle.getFillForegroundColorColor();
  2055. assertNotNull(fgColor);
  2056. assertEquals("FF00FFFF", fgColor.getARGBHex());
  2057. assertEquals(0, cellStyle.getFillBackgroundColor());
  2058. assertNotNull(cellStyle.getFillBackgroundXSSFColor());
  2059. XSSFColor bgColor = cellStyle.getFillBackgroundColorColor();
  2060. assertNotNull(bgColor);
  2061. assertEquals("FF00FFFF", fgColor.getARGBHex());
  2062. }
  2063. @Test
  2064. public void bug57642() throws Exception {
  2065. XSSFWorkbook wb = new XSSFWorkbook();
  2066. XSSFSheet s = wb.createSheet("TestSheet");
  2067. XSSFCell c = s.createRow(0).createCell(0);
  2068. c.setCellFormula("ISERROR(TestSheet!A1)");
  2069. c = s.createRow(1).createCell(1);
  2070. c.setCellFormula("ISERROR(B2)");
  2071. wb.setSheetName(0, "CSN");
  2072. c = s.getRow(0).getCell(0);
  2073. assertEquals("ISERROR(CSN!A1)", c.getCellFormula());
  2074. c = s.getRow(1).getCell(1);
  2075. assertEquals("ISERROR(B2)", c.getCellFormula());
  2076. wb.close();
  2077. }
  2078. /**
  2079. * .xlsx supports 64000 cell styles, the style indexes after
  2080. * 32,767 must not be -32,768, then -32,767, -32,766
  2081. */
  2082. @Test
  2083. public void bug57880() throws Exception {
  2084. int numStyles = 33000;
  2085. XSSFWorkbook wb = new XSSFWorkbook();
  2086. XSSFSheet s = wb.createSheet("TestSheet");
  2087. XSSFDataFormat fmt = wb.getCreationHelper().createDataFormat();
  2088. for (int i=1; i<numStyles; i++) {
  2089. short df = fmt.getFormat("test"+i);
  2090. // Format indexes will be wrapped beyond 32,676
  2091. assertEquals(164+i, df&0xffff);
  2092. // Create a style and use it
  2093. XSSFCellStyle style = wb.createCellStyle();
  2094. assertEquals(i, style.getUIndex());
  2095. style.setDataFormat(df);
  2096. XSSFCell c = s.createRow(i).createCell(0, Cell.CELL_TYPE_NUMERIC);
  2097. c.setCellStyle(style);
  2098. c.setCellValue(i);
  2099. }
  2100. // using temp file instead of ByteArrayOutputStream because of OOM in gump run
  2101. File tmp = TempFile.createTempFile("poi-test", ".bug57880");
  2102. FileOutputStream fos = new FileOutputStream(tmp);
  2103. wb.write(fos);
  2104. fos.close();
  2105. wb.close();
  2106. fmt = null; s = null; wb = null;
  2107. // System.gc();
  2108. wb = new XSSFWorkbook(tmp);
  2109. fmt = wb.getCreationHelper().createDataFormat();
  2110. s = wb.getSheetAt(0);
  2111. for (int i=1; i<numStyles; i++) {
  2112. XSSFCellStyle style = wb.getCellStyleAt((short)i);
  2113. assertNotNull(style);
  2114. assertEquals(i, style.getUIndex());
  2115. assertEquals(164+i, style.getDataFormat()&0xffff);
  2116. assertEquals("test"+i, style.getDataFormatString());
  2117. }
  2118. wb.close();
  2119. tmp.delete();
  2120. }
  2121. @Test
  2122. public void test56574() throws IOException {
  2123. runTest56574(false);
  2124. runTest56574(true);
  2125. }
  2126. @SuppressWarnings("deprecation")
  2127. private void runTest56574(boolean createRow) throws IOException {
  2128. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx");
  2129. Sheet sheet = wb.getSheet("Func");
  2130. assertNotNull(sheet);
  2131. Map<String, Object[]> data;
  2132. data = new TreeMap<String, Object[]>();
  2133. data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
  2134. data.put("2", new Object[] {2, "Amit", "Shukla"});
  2135. data.put("3", new Object[] {1, "Lokesh", "Gupta"});
  2136. data.put("4", new Object[] {4, "John", "Adwards"});
  2137. data.put("5", new Object[] {2, "Brian", "Schultz"});
  2138. Set<String> keyset = data.keySet();
  2139. int rownum = 1;
  2140. for (String key : keyset)
  2141. {
  2142. final Row row;
  2143. if(createRow) {
  2144. row = sheet.createRow(rownum++);
  2145. } else {
  2146. row = sheet.getRow(rownum++);
  2147. }
  2148. assertNotNull(row);
  2149. Object [] objArr = data.get(key);
  2150. int cellnum = 0;
  2151. for (Object obj : objArr)
  2152. {
  2153. Cell cell = row.getCell(cellnum);
  2154. if(cell == null){
  2155. cell = row.createCell(cellnum);
  2156. } else {
  2157. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
  2158. cell.setCellFormula(null);
  2159. cell.getCellStyle().setDataFormat((short) 0);
  2160. }
  2161. }
  2162. if(obj instanceof String) {
  2163. cell.setCellValue((String)obj);
  2164. } else if(obj instanceof Integer) {
  2165. cell.setCellValue((Integer)obj);
  2166. }
  2167. cellnum++;
  2168. }
  2169. }
  2170. XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) wb);
  2171. wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
  2172. CalculationChain chain = ((XSSFWorkbook)wb).getCalculationChain();
  2173. CTCalcCell[] cArray = chain.getCTCalcChain().getCArray();
  2174. for(CTCalcCell calc : cArray) {
  2175. // A2 to A6 should be gone
  2176. assertFalse(calc.getR().equals("A2"));
  2177. assertFalse(calc.getR().equals("A3"));
  2178. assertFalse(calc.getR().equals("A4"));
  2179. assertFalse(calc.getR().equals("A5"));
  2180. assertFalse(calc.getR().equals("A6"));
  2181. }
  2182. /*FileOutputStream out = new FileOutputStream(new File("C:\\temp\\56574.xlsx"));
  2183. try {
  2184. wb.write(out);
  2185. } finally {
  2186. out.close();
  2187. }*/
  2188. Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  2189. Sheet sheetBack = wbBack.getSheet("Func");
  2190. assertNotNull(sheetBack);
  2191. chain = ((XSSFWorkbook)wbBack).getCalculationChain();
  2192. cArray = chain.getCTCalcChain().getCArray();
  2193. for(CTCalcCell calc : cArray) {
  2194. // A2 to A6 should be gone
  2195. assertFalse(calc.getR().equals("A2"));
  2196. assertFalse(calc.getR().equals("A3"));
  2197. assertFalse(calc.getR().equals("A4"));
  2198. assertFalse(calc.getR().equals("A5"));
  2199. assertFalse(calc.getR().equals("A6"));
  2200. }
  2201. wb.close();
  2202. }
  2203. }