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

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