選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TestXSSFBugs.java 137KB

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