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

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