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

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