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

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