You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestXSSFBugs.java 93KB

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