Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

TestXSSFBugs.java 66KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  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.hamcrest.core.IsEqual.equalTo;
  17. import static org.junit.Assert.*;
  18. import java.io.ByteArrayInputStream;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.File;
  21. import java.io.FileInputStream;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.util.List;
  25. import org.apache.poi.EncryptedDocumentException;
  26. import org.apache.poi.POIDataSamples;
  27. import org.apache.poi.POIXMLDocumentPart;
  28. import org.apache.poi.hssf.HSSFTestDataSamples;
  29. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  30. import org.apache.poi.openxml4j.opc.OPCPackage;
  31. import org.apache.poi.openxml4j.opc.PackagePart;
  32. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  33. import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
  34. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  35. import org.apache.poi.ss.formula.WorkbookEvaluator;
  36. import org.apache.poi.ss.formula.eval.ErrorEval;
  37. import org.apache.poi.ss.formula.eval.ValueEval;
  38. import org.apache.poi.ss.formula.functions.Function;
  39. import org.apache.poi.ss.usermodel.*;
  40. import org.apache.poi.ss.util.AreaReference;
  41. import org.apache.poi.ss.util.CellRangeAddress;
  42. import org.apache.poi.ss.util.CellReference;
  43. import org.apache.poi.util.TempFile;
  44. import org.apache.poi.xssf.XSSFITestDataProvider;
  45. import org.apache.poi.xssf.XSSFTestDataSamples;
  46. import org.apache.poi.xssf.model.CalculationChain;
  47. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  48. import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
  49. import org.junit.Ignore;
  50. import org.junit.Test;
  51. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
  52. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
  53. import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl;
  54. public final class TestXSSFBugs extends BaseTestBugzillaIssues {
  55. public TestXSSFBugs() {
  56. super(XSSFITestDataProvider.instance);
  57. }
  58. /**
  59. * test writing a file with large number of unique strings,
  60. * open resulting file in Excel to check results!
  61. */
  62. @Test
  63. public void bug15375_2() {
  64. bug15375(1000);
  65. }
  66. /**
  67. * Named ranges had the right reference, but
  68. * the wrong sheet name
  69. */
  70. @Test
  71. public void bug45430() {
  72. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx");
  73. assertFalse(wb.isMacroEnabled());
  74. assertEquals(3, wb.getNumberOfNames());
  75. assertEquals(0, wb.getNameAt(0).getCTName().getLocalSheetId());
  76. assertFalse(wb.getNameAt(0).getCTName().isSetLocalSheetId());
  77. assertEquals("SheetA!$A$1", wb.getNameAt(0).getRefersToFormula());
  78. assertEquals("SheetA", wb.getNameAt(0).getSheetName());
  79. assertEquals(0, wb.getNameAt(1).getCTName().getLocalSheetId());
  80. assertFalse(wb.getNameAt(1).getCTName().isSetLocalSheetId());
  81. assertEquals("SheetB!$A$1", wb.getNameAt(1).getRefersToFormula());
  82. assertEquals("SheetB", wb.getNameAt(1).getSheetName());
  83. assertEquals(0, wb.getNameAt(2).getCTName().getLocalSheetId());
  84. assertFalse(wb.getNameAt(2).getCTName().isSetLocalSheetId());
  85. assertEquals("SheetC!$A$1", wb.getNameAt(2).getRefersToFormula());
  86. assertEquals("SheetC", wb.getNameAt(2).getSheetName());
  87. // Save and re-load, still there
  88. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  89. assertEquals(3, nwb.getNumberOfNames());
  90. assertEquals("SheetA!$A$1", nwb.getNameAt(0).getRefersToFormula());
  91. }
  92. /**
  93. * We should carry vba macros over after save
  94. */
  95. @Test
  96. public void bug45431() throws Exception {
  97. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm");
  98. OPCPackage pkg = wb.getPackage();
  99. assertTrue(wb.isMacroEnabled());
  100. // Check the various macro related bits can be found
  101. PackagePart vba = pkg.getPart(
  102. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  103. );
  104. assertNotNull(vba);
  105. // And the drawing bit
  106. PackagePart drw = pkg.getPart(
  107. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  108. );
  109. assertNotNull(drw);
  110. // Save and re-open, both still there
  111. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  112. OPCPackage nPkg = nwb.getPackage();
  113. assertTrue(nwb.isMacroEnabled());
  114. vba = nPkg.getPart(
  115. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  116. );
  117. assertNotNull(vba);
  118. drw = nPkg.getPart(
  119. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  120. );
  121. assertNotNull(drw);
  122. // And again, just to be sure
  123. nwb = XSSFTestDataSamples.writeOutAndReadBack(nwb);
  124. nPkg = nwb.getPackage();
  125. assertTrue(nwb.isMacroEnabled());
  126. vba = nPkg.getPart(
  127. PackagingURIHelper.createPartName("/xl/vbaProject.bin")
  128. );
  129. assertNotNull(vba);
  130. drw = nPkg.getPart(
  131. PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
  132. );
  133. assertNotNull(drw);
  134. }
  135. @Test
  136. public void bug47504() {
  137. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx");
  138. assertEquals(1, wb.getNumberOfSheets());
  139. XSSFSheet sh = wb.getSheetAt(0);
  140. XSSFDrawing drawing = sh.createDrawingPatriarch();
  141. List<POIXMLDocumentPart> rels = drawing.getRelations();
  142. assertEquals(1, rels.size());
  143. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  144. // And again, just to be sure
  145. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  146. assertEquals(1, wb.getNumberOfSheets());
  147. sh = wb.getSheetAt(0);
  148. drawing = sh.createDrawingPatriarch();
  149. rels = drawing.getRelations();
  150. assertEquals(1, rels.size());
  151. assertEquals("Sheet1!A1", rels.get(0).getPackageRelationship().getTargetURI().getFragment());
  152. }
  153. /**
  154. * Excel will sometimes write a button with a textbox
  155. * containing &gt;br&lt; (not closed!).
  156. * Clearly Excel shouldn't do this, but test that we can
  157. * read the file despite the naughtyness
  158. */
  159. @Test
  160. public void bug49020() throws Exception {
  161. /*XSSFWorkbook wb =*/ XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx");
  162. }
  163. /**
  164. * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas
  165. */
  166. @Test
  167. public void bug49325() throws Exception {
  168. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx");
  169. CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet();
  170. assertNotNull(sh.getPhoneticPr());
  171. }
  172. /**
  173. * Names which are defined with a Sheet
  174. * should return that sheet index properly
  175. */
  176. @Test
  177. public void bug48923() throws Exception {
  178. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx");
  179. assertEquals(4, wb.getNumberOfNames());
  180. Name b1 = wb.getName("NameB1");
  181. Name b2 = wb.getName("NameB2");
  182. Name sheet2 = wb.getName("NameSheet2");
  183. Name test = wb.getName("Test");
  184. assertNotNull(b1);
  185. assertEquals("NameB1", b1.getNameName());
  186. assertEquals("Sheet1", b1.getSheetName());
  187. assertEquals(-1, b1.getSheetIndex());
  188. assertNotNull(b2);
  189. assertEquals("NameB2", b2.getNameName());
  190. assertEquals("Sheet1", b2.getSheetName());
  191. assertEquals(-1, b2.getSheetIndex());
  192. assertNotNull(sheet2);
  193. assertEquals("NameSheet2", sheet2.getNameName());
  194. assertEquals("Sheet2", sheet2.getSheetName());
  195. assertEquals(-1, sheet2.getSheetIndex());
  196. assertNotNull(test);
  197. assertEquals("Test", test.getNameName());
  198. assertEquals("Sheet1", test.getSheetName());
  199. assertEquals(-1, test.getSheetIndex());
  200. }
  201. /**
  202. * Problem with evaluation formulas due to
  203. * NameXPtgs.
  204. * Blows up on:
  205. * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0))
  206. *
  207. * TODO: delete this test case when MROUND and VAR are implemented
  208. */
  209. @Test
  210. public void bug48539() throws Exception {
  211. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx");
  212. assertEquals(3, wb.getNumberOfSheets());
  213. assertEquals(0, wb.getNumberOfNames());
  214. // Try each cell individually
  215. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  216. for(int i=0; i<wb.getNumberOfSheets(); i++) {
  217. Sheet s = wb.getSheetAt(i);
  218. for(Row r : s) {
  219. for(Cell c : r) {
  220. if(c.getCellType() == Cell.CELL_TYPE_FORMULA) {
  221. String formula = c.getCellFormula();
  222. CellValue cv;
  223. try {
  224. cv = eval.evaluate(c);
  225. } catch (Exception e) {
  226. throw new RuntimeException("Can't evaluate formula: " + formula, e);
  227. }
  228. if(cv.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  229. // assert that the calculated value agrees with
  230. // the cached formula result calculated by Excel
  231. double cachedFormulaResult = c.getNumericCellValue();
  232. double evaluatedFormulaResult = cv.getNumberValue();
  233. assertEquals(c.getCellFormula(), cachedFormulaResult, evaluatedFormulaResult, 1E-7);
  234. }
  235. }
  236. }
  237. }
  238. }
  239. // Now all of them
  240. XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
  241. }
  242. /**
  243. * Foreground colours should be found even if
  244. * a theme is used
  245. */
  246. @Test
  247. public void bug48779() throws Exception {
  248. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx");
  249. XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
  250. XSSFCellStyle cs = cell.getCellStyle();
  251. assertNotNull(cs);
  252. assertEquals(1, cs.getIndex());
  253. // Look at the low level xml elements
  254. assertEquals(2, cs.getCoreXf().getFillId());
  255. assertEquals(0, cs.getCoreXf().getXfId());
  256. assertEquals(true, cs.getCoreXf().getApplyFill());
  257. XSSFCellFill fg = wb.getStylesSource().getFillAt(2);
  258. assertEquals(0, fg.getFillForegroundColor().getIndexed());
  259. assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0);
  260. assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex());
  261. assertEquals(64, fg.getFillBackgroundColor().getIndexed());
  262. // Now look higher up
  263. assertNotNull(cs.getFillForegroundXSSFColor());
  264. assertEquals(0, cs.getFillForegroundColor());
  265. assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex());
  266. assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex());
  267. assertNotNull(cs.getFillBackgroundColor());
  268. assertEquals(64, cs.getFillBackgroundColor());
  269. assertEquals(null, cs.getFillBackgroundXSSFColor().getARGBHex());
  270. assertEquals(null, cs.getFillBackgroundColorColor().getARGBHex());
  271. }
  272. /**
  273. * With HSSF, if you create a font, don't change it, and
  274. * create a 2nd, you really do get two fonts that you
  275. * can alter as and when you want.
  276. * With XSSF, that wasn't the case, but this verfies
  277. * that it now is again
  278. */
  279. @Test
  280. public void bug48718() throws Exception {
  281. // Verify the HSSF behaviour
  282. // Then ensure the same for XSSF
  283. Workbook[] wbs = new Workbook[] {
  284. new HSSFWorkbook(),
  285. new XSSFWorkbook()
  286. };
  287. int[] initialFonts = new int[] { 4, 1 };
  288. for(int i=0; i<wbs.length; i++) {
  289. Workbook wb = wbs[i];
  290. int startingFonts = initialFonts[i];
  291. assertEquals(startingFonts, wb.getNumberOfFonts());
  292. // Get a font, and slightly change it
  293. Font a = wb.createFont();
  294. assertEquals(startingFonts+1, wb.getNumberOfFonts());
  295. a.setFontHeightInPoints((short)23);
  296. assertEquals(startingFonts+1, wb.getNumberOfFonts());
  297. // Get two more, unchanged
  298. /*Font b =*/ wb.createFont();
  299. assertEquals(startingFonts+2, wb.getNumberOfFonts());
  300. /*Font c =*/ wb.createFont();
  301. assertEquals(startingFonts+3, wb.getNumberOfFonts());
  302. }
  303. }
  304. /**
  305. * Ensure General and @ format are working properly
  306. * for integers
  307. */
  308. @Test
  309. public void bug47490() throws Exception {
  310. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx");
  311. Sheet s = wb.getSheetAt(1);
  312. Row r;
  313. DataFormatter df = new DataFormatter();
  314. r = s.getRow(1);
  315. assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0);
  316. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  317. assertEquals("1", df.formatCellValue(r.getCell(2)));
  318. assertEquals("1", df.formatRawCellContents(1.0, -1, "@"));
  319. assertEquals("1", df.formatRawCellContents(1.0, -1, "General"));
  320. r = s.getRow(2);
  321. assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0);
  322. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  323. assertEquals("12", df.formatCellValue(r.getCell(2)));
  324. assertEquals("12", df.formatRawCellContents(12.0, -1, "@"));
  325. assertEquals("12", df.formatRawCellContents(12.0, -1, "General"));
  326. r = s.getRow(3);
  327. assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0);
  328. assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString());
  329. assertEquals("123", df.formatCellValue(r.getCell(2)));
  330. assertEquals("123", df.formatRawCellContents(123.0, -1, "@"));
  331. assertEquals("123", df.formatRawCellContents(123.0, -1, "General"));
  332. }
  333. /**
  334. * Ensures that XSSF and HSSF agree with each other,
  335. * and with the docs on when fetching the wrong
  336. * kind of value from a Formula cell
  337. */
  338. @Test
  339. public void bug47815() {
  340. Workbook[] wbs = new Workbook[] {
  341. new HSSFWorkbook(),
  342. new XSSFWorkbook()
  343. };
  344. for(Workbook wb : wbs) {
  345. Sheet s = wb.createSheet();
  346. Row r = s.createRow(0);
  347. // Setup
  348. Cell cn = r.createCell(0, Cell.CELL_TYPE_NUMERIC);
  349. cn.setCellValue(1.2);
  350. Cell cs = r.createCell(1, Cell.CELL_TYPE_STRING);
  351. cs.setCellValue("Testing");
  352. Cell cfn = r.createCell(2, Cell.CELL_TYPE_FORMULA);
  353. cfn.setCellFormula("A1");
  354. Cell cfs = r.createCell(3, Cell.CELL_TYPE_FORMULA);
  355. cfs.setCellFormula("B1");
  356. FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
  357. assertEquals(Cell.CELL_TYPE_NUMERIC, fe.evaluate(cfn).getCellType());
  358. assertEquals(Cell.CELL_TYPE_STRING, fe.evaluate(cfs).getCellType());
  359. fe.evaluateFormulaCell(cfn);
  360. fe.evaluateFormulaCell(cfs);
  361. // Now test
  362. assertEquals(Cell.CELL_TYPE_NUMERIC, cn.getCellType());
  363. assertEquals(Cell.CELL_TYPE_STRING, cs.getCellType());
  364. assertEquals(Cell.CELL_TYPE_FORMULA, cfn.getCellType());
  365. assertEquals(Cell.CELL_TYPE_NUMERIC, cfn.getCachedFormulaResultType());
  366. assertEquals(Cell.CELL_TYPE_FORMULA, cfs.getCellType());
  367. assertEquals(Cell.CELL_TYPE_STRING, cfs.getCachedFormulaResultType());
  368. // Different ways of retrieving
  369. assertEquals(1.2, cn.getNumericCellValue(), 0);
  370. try {
  371. cn.getRichStringCellValue();
  372. fail();
  373. } catch(IllegalStateException e) {}
  374. assertEquals("Testing", cs.getStringCellValue());
  375. try {
  376. cs.getNumericCellValue();
  377. fail();
  378. } catch(IllegalStateException e) {}
  379. assertEquals(1.2, cfn.getNumericCellValue(), 0);
  380. try {
  381. cfn.getRichStringCellValue();
  382. fail();
  383. } catch(IllegalStateException e) {}
  384. assertEquals("Testing", cfs.getStringCellValue());
  385. try {
  386. cfs.getNumericCellValue();
  387. fail();
  388. } catch(IllegalStateException e) {}
  389. }
  390. }
  391. /**
  392. * A problem file from a non-standard source (a scientific instrument that saves its
  393. * output as an .xlsx file) that have two issues:
  394. * 1. The Content Type part name is lower-case: [content_types].xml
  395. * 2. The file appears to use backslashes as path separators
  396. *
  397. * The OPC spec tolerates both of these peculiarities, so does POI
  398. */
  399. @Test
  400. public void bug49609() throws Exception {
  401. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx");
  402. assertEquals("FAM", wb.getSheetName(0));
  403. assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
  404. }
  405. @Test
  406. public void bug49783() throws Exception {
  407. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx");
  408. Sheet sheet = wb.getSheetAt(0);
  409. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  410. Cell cell;
  411. cell = sheet.getRow(0).getCell(0);
  412. assertEquals("#REF!*#REF!", cell.getCellFormula());
  413. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  414. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  415. Name nm1 = wb.getName("sale_1");
  416. assertNotNull("name sale_1 should be present", nm1);
  417. assertEquals("Sheet1!#REF!", nm1.getRefersToFormula());
  418. Name nm2 = wb.getName("sale_2");
  419. assertNotNull("name sale_2 should be present", nm2);
  420. assertEquals("Sheet1!#REF!", nm2.getRefersToFormula());
  421. cell = sheet.getRow(1).getCell(0);
  422. assertEquals("sale_1*sale_2", cell.getCellFormula());
  423. assertEquals(Cell.CELL_TYPE_ERROR, evaluator.evaluateInCell(cell).getCellType());
  424. assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString());
  425. }
  426. /**
  427. * Creating a rich string of "hello world" and applying
  428. * a font to characters 1-5 means we have two strings,
  429. * "hello" and " world". As such, we need to apply
  430. * preserve spaces to the 2nd bit, lest we end up
  431. * with something like "helloworld" !
  432. */
  433. @Test
  434. public void bug49941() throws Exception {
  435. XSSFWorkbook wb = new XSSFWorkbook();
  436. XSSFSheet s = wb.createSheet();
  437. XSSFRow r = s.createRow(0);
  438. XSSFCell c = r.createCell(0);
  439. // First without fonts
  440. c.setCellValue(
  441. new XSSFRichTextString(" with spaces ")
  442. );
  443. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  444. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  445. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  446. // Should have the preserve set
  447. assertEquals(
  448. 1,
  449. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  450. );
  451. assertEquals(
  452. "preserve",
  453. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  454. );
  455. // Save and check
  456. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  457. s = wb.getSheetAt(0);
  458. r = s.getRow(0);
  459. c = r.getCell(0);
  460. assertEquals(" with spaces ", c.getRichStringCellValue().toString());
  461. assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  462. assertEquals(true, c.getRichStringCellValue().getCTRst().isSetT());
  463. // Change the string
  464. c.setCellValue(
  465. new XSSFRichTextString("hello world")
  466. );
  467. assertEquals("hello world", c.getRichStringCellValue().toString());
  468. // Won't have preserve
  469. assertEquals(
  470. 0,
  471. c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
  472. );
  473. // Apply a font
  474. XSSFFont f = wb.createFont();
  475. f.setBold(true);
  476. c.getRichStringCellValue().applyFont(0, 5, f);
  477. assertEquals("hello world", c.getRichStringCellValue().toString());
  478. // Does need preserving on the 2nd part
  479. assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
  480. assertEquals(
  481. 0,
  482. c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
  483. );
  484. assertEquals(
  485. 1,
  486. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
  487. );
  488. assertEquals(
  489. "preserve",
  490. c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
  491. );
  492. // Save and check
  493. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  494. s = wb.getSheetAt(0);
  495. r = s.getRow(0);
  496. c = r.getCell(0);
  497. assertEquals("hello world", c.getRichStringCellValue().toString());
  498. wb.close();
  499. }
  500. /**
  501. * Repeatedly writing the same file which has styles
  502. */
  503. @Test
  504. public void bug49940() throws Exception {
  505. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx");
  506. assertEquals(3, wb.getNumberOfSheets());
  507. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  508. ByteArrayOutputStream b1 = new ByteArrayOutputStream();
  509. ByteArrayOutputStream b2 = new ByteArrayOutputStream();
  510. ByteArrayOutputStream b3 = new ByteArrayOutputStream();
  511. wb.write(b1);
  512. wb.write(b2);
  513. wb.write(b3);
  514. for(byte[] data : new byte[][] {
  515. b1.toByteArray(), b2.toByteArray(), b3.toByteArray()
  516. }) {
  517. ByteArrayInputStream bais = new ByteArrayInputStream(data);
  518. wb = new XSSFWorkbook(bais);
  519. assertEquals(3, wb.getNumberOfSheets());
  520. assertEquals(10, wb.getStylesSource().getNumCellStyles());
  521. }
  522. }
  523. /**
  524. * Various ways of removing a cell formula should all zap the calcChain
  525. * entry.
  526. */
  527. @Test
  528. public void bug49966() throws Exception {
  529. XSSFWorkbook wb = XSSFTestDataSamples
  530. .openSampleWorkbook("shared_formulas.xlsx");
  531. XSSFSheet sheet = wb.getSheetAt(0);
  532. Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  533. // CalcChain has lots of entries
  534. CalculationChain cc = wb.getCalculationChain();
  535. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  536. assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR());
  537. assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR());
  538. assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR());
  539. assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR());
  540. assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR());
  541. assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR());
  542. assertEquals(40, cc.getCTCalcChain().sizeOfCArray());
  543. wbRead.close();
  544. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  545. // Try various ways of changing the formulas
  546. // If it stays a formula, chain entry should remain
  547. // Otherwise should go
  548. sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay
  549. sheet.getRow(2).getCell(0).setCellFormula(null); // go
  550. sheet.getRow(3).getCell(0).setCellType(Cell.CELL_TYPE_FORMULA); // stay
  551. wbRead.close();
  552. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  553. sheet.getRow(4).getCell(0).setCellType(Cell.CELL_TYPE_STRING); // go
  554. wbRead.close();
  555. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  556. validateCells(sheet);
  557. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  558. validateCells(sheet);
  559. wbRead.close();
  560. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  561. sheet.getRow(6).getCell(0).setCellType(Cell.CELL_TYPE_BLANK); // go
  562. wbRead.close();
  563. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  564. sheet.getRow(7).getCell(0).setCellValue((String) null); // go
  565. wbRead.close();
  566. wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb);
  567. // Save and check
  568. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  569. assertEquals(35, cc.getCTCalcChain().sizeOfCArray());
  570. cc = wb.getCalculationChain();
  571. assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR());
  572. assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR());
  573. assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR());
  574. wbRead.close();
  575. }
  576. @Test
  577. public void bug49966Row() throws Exception {
  578. XSSFWorkbook wb = XSSFTestDataSamples
  579. .openSampleWorkbook("shared_formulas.xlsx");
  580. XSSFSheet sheet = wb.getSheetAt(0);
  581. validateCells(sheet);
  582. sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
  583. validateCells(sheet);
  584. }
  585. private void validateCells(XSSFSheet sheet) {
  586. for(Row row : sheet) {
  587. // trigger handling
  588. ((XSSFRow)row).onDocumentWrite();
  589. }
  590. }
  591. @Test
  592. public void bug49156() throws Exception {
  593. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx");
  594. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  595. Sheet sheet = wb.getSheetAt(0);
  596. for(Row row : sheet){
  597. for(Cell cell : row){
  598. if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){
  599. formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells
  600. }
  601. }
  602. }
  603. }
  604. /**
  605. * Newlines are valid characters in a formula
  606. */
  607. @Test
  608. public void bug50440And51875() throws Exception {
  609. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx");
  610. Sheet s = wb.getSheetAt(0);
  611. Cell c = s.getRow(0).getCell(0);
  612. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  613. assertEquals(3.0, c.getNumericCellValue(), 0);
  614. FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
  615. formulaEvaluator.evaluateFormulaCell(c);
  616. assertEquals("SUM(\n1,2\n)", c.getCellFormula());
  617. assertEquals(3.0, c.getNumericCellValue(), 0);
  618. // For 51875
  619. Cell b3 = s.getRow(2).getCell(1);
  620. formulaEvaluator.evaluateFormulaCell(b3);
  621. assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas
  622. assertEquals(3.0, b3.getNumericCellValue(), 0);
  623. }
  624. /**
  625. * Moving a cell comment from one cell to another
  626. */
  627. @Test
  628. public void bug50795() throws Exception {
  629. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx");
  630. XSSFSheet sheet = wb.getSheetAt(0);
  631. XSSFRow row = sheet.getRow(0);
  632. XSSFCell cellWith = row.getCell(0);
  633. XSSFCell cellWithoutComment = row.getCell(1);
  634. assertNotNull(cellWith.getCellComment());
  635. assertNull(cellWithoutComment.getCellComment());
  636. String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
  637. XSSFComment comment = cellWith.getCellComment();
  638. assertEquals(exp, comment.getString().getString());
  639. // Check we can write it out and read it back as-is
  640. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  641. sheet = wb.getSheetAt(0);
  642. row = sheet.getRow(0);
  643. cellWith = row.getCell(0);
  644. cellWithoutComment = row.getCell(1);
  645. // Double check things are as expected
  646. assertNotNull(cellWith.getCellComment());
  647. assertNull(cellWithoutComment.getCellComment());
  648. comment = cellWith.getCellComment();
  649. assertEquals(exp, comment.getString().getString());
  650. // Move the comment
  651. cellWithoutComment.setCellComment(comment);
  652. // Write out and re-check
  653. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  654. sheet = wb.getSheetAt(0);
  655. row = sheet.getRow(0);
  656. // Ensure it swapped over
  657. cellWith = row.getCell(0);
  658. cellWithoutComment = row.getCell(1);
  659. assertNull(cellWith.getCellComment());
  660. assertNotNull(cellWithoutComment.getCellComment());
  661. comment = cellWithoutComment.getCellComment();
  662. assertEquals(exp, comment.getString().getString());
  663. }
  664. /**
  665. * When the cell background colour is set with one of the first
  666. * two columns of the theme colour palette, the colours are
  667. * shades of white or black.
  668. * For those cases, ensure we don't break on reading the colour
  669. */
  670. @Test
  671. public void bug50299() throws Exception {
  672. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx");
  673. // Check all the colours
  674. for(int sn=0; sn<wb.getNumberOfSheets(); sn++) {
  675. Sheet s = wb.getSheetAt(sn);
  676. for(Row r : s) {
  677. for(Cell c : r) {
  678. CellStyle cs = c.getCellStyle();
  679. if(cs != null) {
  680. cs.getFillForegroundColor();
  681. }
  682. }
  683. }
  684. }
  685. // Check one bit in detail
  686. // Check that we get back foreground=0 for the theme colours,
  687. // and background=64 for the auto colouring
  688. Sheet s = wb.getSheetAt(0);
  689. assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor());
  690. assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor());
  691. assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor());
  692. assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor());
  693. }
  694. /**
  695. * Excel .xls style indexed colours in a .xlsx file
  696. */
  697. @Test
  698. public void bug50786() throws Exception {
  699. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx");
  700. XSSFSheet s = wb.getSheetAt(0);
  701. XSSFRow r = s.getRow(2);
  702. // Check we have the right cell
  703. XSSFCell c = r.getCell(1);
  704. assertEquals("test\u00a0", c.getRichStringCellValue().getString());
  705. // It should be light green
  706. XSSFCellStyle cs = c.getCellStyle();
  707. assertEquals(42, cs.getFillForegroundColor());
  708. assertEquals(42, cs.getFillForegroundColorColor().getIndexed());
  709. assertNotNull(cs.getFillForegroundColorColor().getRgb());
  710. assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex());
  711. }
  712. /**
  713. * If the border colours are set with themes, then we
  714. * should still be able to get colours
  715. */
  716. @Test
  717. public void bug50846() throws Exception {
  718. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx");
  719. XSSFSheet sheet = wb.getSheetAt(0);
  720. XSSFRow row = sheet.getRow(0);
  721. // Border from a theme, brown
  722. XSSFCell cellT = row.getCell(0);
  723. XSSFCellStyle styleT = cellT.getCellStyle();
  724. XSSFColor colorT = styleT.getBottomBorderXSSFColor();
  725. assertEquals(5, colorT.getTheme());
  726. assertEquals("FFC0504D", colorT.getARGBHex());
  727. // Border from a style direct, red
  728. XSSFCell cellS = row.getCell(1);
  729. XSSFCellStyle styleS = cellS.getCellStyle();
  730. XSSFColor colorS = styleS.getBottomBorderXSSFColor();
  731. assertEquals(0, colorS.getTheme());
  732. assertEquals("FFFF0000", colorS.getARGBHex());
  733. }
  734. /**
  735. * Fonts where their colours come from the theme rather
  736. * then being set explicitly still should allow the
  737. * fetching of the RGB.
  738. */
  739. @Test
  740. public void bug50784() throws Exception {
  741. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx");
  742. XSSFSheet s = wb.getSheetAt(0);
  743. XSSFRow r = s.getRow(0);
  744. // Column 1 has a font with regular colours
  745. XSSFCell cr = r.getCell(1);
  746. XSSFFont fr = wb.getFontAt( cr.getCellStyle().getFontIndex() );
  747. XSSFColor colr = fr.getXSSFColor();
  748. // No theme, has colours
  749. assertEquals(0, colr.getTheme());
  750. assertNotNull( colr.getRgb() );
  751. // Column 0 has a font with colours from a theme
  752. XSSFCell ct = r.getCell(0);
  753. XSSFFont ft = wb.getFontAt( ct.getCellStyle().getFontIndex() );
  754. XSSFColor colt = ft.getXSSFColor();
  755. // Has a theme, which has the colours on it
  756. assertEquals(9, colt.getTheme());
  757. XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme());
  758. assertNotNull( themeC.getRgb() );
  759. assertNotNull( colt.getRgb() );
  760. assertEquals( themeC.getARGBHex(), colt.getARGBHex() ); // The same colour
  761. }
  762. /**
  763. * New lines were being eaten when setting a font on
  764. * a rich text string
  765. */
  766. @Test
  767. public void bug48877() throws Exception {
  768. String text = "Use \n with word wrap on to create a new line.\n" +
  769. "This line finishes with two trailing spaces. ";
  770. XSSFWorkbook wb = new XSSFWorkbook();
  771. XSSFSheet sheet = wb.createSheet();
  772. Font font1 = wb.createFont();
  773. font1.setColor((short) 20);
  774. Font font2 = wb.createFont();
  775. font2.setColor(Font.COLOR_RED);
  776. Font font3 = wb.getFontAt((short)0);
  777. XSSFRow row = sheet.createRow(2);
  778. XSSFCell cell = row.createCell(2);
  779. XSSFRichTextString richTextString =
  780. wb.getCreationHelper().createRichTextString(text);
  781. // Check the text has the newline
  782. assertEquals(text, richTextString.getString());
  783. // Apply the font
  784. richTextString.applyFont(font3);
  785. richTextString.applyFont(0, 3, font1);
  786. cell.setCellValue(richTextString);
  787. // To enable newlines you need set a cell styles with wrap=true
  788. CellStyle cs = wb.createCellStyle();
  789. cs.setWrapText(true);
  790. cell.setCellStyle(cs);
  791. // Check the text has the
  792. assertEquals(text, cell.getStringCellValue());
  793. // Save the file and re-read it
  794. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  795. sheet = wb.getSheetAt(0);
  796. row = sheet.getRow(2);
  797. cell = row.getCell(2);
  798. assertEquals(text, cell.getStringCellValue());
  799. // Now add a 2nd, and check again
  800. int fontAt = text.indexOf("\n", 6);
  801. cell.getRichStringCellValue().applyFont(10, fontAt+1, font2);
  802. assertEquals(text, cell.getStringCellValue());
  803. assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
  804. assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRList().get(0).getT());
  805. String r3 = cell.getRichStringCellValue().getCTRst().getRList().get(2).getT();
  806. assertEquals("line.\n", r3.substring(r3.length()-6));
  807. // Save and re-check
  808. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  809. sheet = wb.getSheetAt(0);
  810. row = sheet.getRow(2);
  811. cell = row.getCell(2);
  812. assertEquals(text, cell.getStringCellValue());
  813. wb.close();
  814. // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx");
  815. // wb.write(out);
  816. // out.close();
  817. }
  818. /**
  819. * Adding sheets when one has a table, then re-ordering
  820. */
  821. @Test
  822. public void bug50867() throws Exception {
  823. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx");
  824. assertEquals(3, wb.getNumberOfSheets());
  825. XSSFSheet s1 = wb.getSheetAt(0);
  826. XSSFSheet s2 = wb.getSheetAt(1);
  827. XSSFSheet s3 = wb.getSheetAt(2);
  828. assertEquals(1, s1.getTables().size());
  829. assertEquals(0, s2.getTables().size());
  830. assertEquals(0, s3.getTables().size());
  831. XSSFTable t = s1.getTables().get(0);
  832. assertEquals("Tabella1", t.getName());
  833. assertEquals("Tabella1", t.getDisplayName());
  834. assertEquals("A1:C3", t.getCTTable().getRef());
  835. // Add a sheet and re-order
  836. XSSFSheet s4 = wb.createSheet("NewSheet");
  837. wb.setSheetOrder(s4.getSheetName(), 0);
  838. // Check on tables
  839. assertEquals(1, s1.getTables().size());
  840. assertEquals(0, s2.getTables().size());
  841. assertEquals(0, s3.getTables().size());
  842. assertEquals(0, s4.getTables().size());
  843. // Refetch to get the new order
  844. s1 = wb.getSheetAt(0);
  845. s2 = wb.getSheetAt(1);
  846. s3 = wb.getSheetAt(2);
  847. s4 = wb.getSheetAt(3);
  848. assertEquals(0, s1.getTables().size());
  849. assertEquals(1, s2.getTables().size());
  850. assertEquals(0, s3.getTables().size());
  851. assertEquals(0, s4.getTables().size());
  852. // Save and re-load
  853. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  854. s1 = wb.getSheetAt(0);
  855. s2 = wb.getSheetAt(1);
  856. s3 = wb.getSheetAt(2);
  857. s4 = wb.getSheetAt(3);
  858. assertEquals(0, s1.getTables().size());
  859. assertEquals(1, s2.getTables().size());
  860. assertEquals(0, s3.getTables().size());
  861. assertEquals(0, s4.getTables().size());
  862. t = s2.getTables().get(0);
  863. assertEquals("Tabella1", t.getName());
  864. assertEquals("Tabella1", t.getDisplayName());
  865. assertEquals("A1:C3", t.getCTTable().getRef());
  866. // Add some more tables, and check
  867. t = s2.createTable();
  868. t.setName("New 2");
  869. t.setDisplayName("New 2");
  870. t = s3.createTable();
  871. t.setName("New 3");
  872. t.setDisplayName("New 3");
  873. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  874. s1 = wb.getSheetAt(0);
  875. s2 = wb.getSheetAt(1);
  876. s3 = wb.getSheetAt(2);
  877. s4 = wb.getSheetAt(3);
  878. assertEquals(0, s1.getTables().size());
  879. assertEquals(2, s2.getTables().size());
  880. assertEquals(1, s3.getTables().size());
  881. assertEquals(0, s4.getTables().size());
  882. t = s2.getTables().get(0);
  883. assertEquals("Tabella1", t.getName());
  884. assertEquals("Tabella1", t.getDisplayName());
  885. assertEquals("A1:C3", t.getCTTable().getRef());
  886. t = s2.getTables().get(1);
  887. assertEquals("New 2", t.getName());
  888. assertEquals("New 2", t.getDisplayName());
  889. t = s3.getTables().get(0);
  890. assertEquals("New 3", t.getName());
  891. assertEquals("New 3", t.getDisplayName());
  892. // Check the relationships
  893. assertEquals(0, s1.getRelations().size());
  894. assertEquals(3, s2.getRelations().size());
  895. assertEquals(1, s3.getRelations().size());
  896. assertEquals(0, s4.getRelations().size());
  897. assertEquals(
  898. XSSFRelation.PRINTER_SETTINGS.getContentType(),
  899. s2.getRelations().get(0).getPackagePart().getContentType()
  900. );
  901. assertEquals(
  902. XSSFRelation.TABLE.getContentType(),
  903. s2.getRelations().get(1).getPackagePart().getContentType()
  904. );
  905. assertEquals(
  906. XSSFRelation.TABLE.getContentType(),
  907. s2.getRelations().get(2).getPackagePart().getContentType()
  908. );
  909. assertEquals(
  910. XSSFRelation.TABLE.getContentType(),
  911. s3.getRelations().get(0).getPackagePart().getContentType()
  912. );
  913. assertEquals(
  914. "/xl/tables/table3.xml",
  915. s3.getRelations().get(0).getPackagePart().getPartName().toString()
  916. );
  917. }
  918. /**
  919. * Setting repeating rows and columns shouldn't break
  920. * any print settings that were there before
  921. */
  922. @SuppressWarnings("deprecation")
  923. @Test
  924. public void bug49253() throws Exception {
  925. XSSFWorkbook wb1 = new XSSFWorkbook();
  926. XSSFWorkbook wb2 = new XSSFWorkbook();
  927. // No print settings before repeating
  928. XSSFSheet s1 = wb1.createSheet();
  929. assertEquals(false, s1.getCTWorksheet().isSetPageSetup());
  930. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  931. wb1.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  932. assertEquals(true, s1.getCTWorksheet().isSetPageSetup());
  933. assertEquals(true, s1.getCTWorksheet().isSetPageMargins());
  934. XSSFPrintSetup ps1 = s1.getPrintSetup();
  935. assertEquals(false, ps1.getValidSettings());
  936. assertEquals(false, ps1.getLandscape());
  937. // Had valid print settings before repeating
  938. XSSFSheet s2 = wb2.createSheet();
  939. XSSFPrintSetup ps2 = s2.getPrintSetup();
  940. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  941. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  942. ps2.setLandscape(false);
  943. assertEquals(true, ps2.getValidSettings());
  944. assertEquals(false, ps2.getLandscape());
  945. wb2.setRepeatingRowsAndColumns(0, 2, 3, 1, 2);
  946. ps2 = s2.getPrintSetup();
  947. assertEquals(true, s2.getCTWorksheet().isSetPageSetup());
  948. assertEquals(true, s2.getCTWorksheet().isSetPageMargins());
  949. assertEquals(true, ps2.getValidSettings());
  950. assertEquals(false, ps2.getLandscape());
  951. wb1.close();
  952. wb2.close();
  953. }
  954. /**
  955. * Default Column style
  956. */
  957. @Test
  958. public void bug51037() throws Exception {
  959. XSSFWorkbook wb = new XSSFWorkbook();
  960. XSSFSheet s = wb.createSheet();
  961. CellStyle defaultStyle = wb.getCellStyleAt((short)0);
  962. assertEquals(0, defaultStyle.getIndex());
  963. CellStyle blueStyle = wb.createCellStyle();
  964. blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
  965. blueStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  966. assertEquals(1, blueStyle.getIndex());
  967. CellStyle pinkStyle = wb.createCellStyle();
  968. pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
  969. pinkStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
  970. assertEquals(2, pinkStyle.getIndex());
  971. // Starts empty
  972. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  973. CTCols cols = s.getCTWorksheet().getColsArray(0);
  974. assertEquals(0, cols.sizeOfColArray());
  975. // Add some rows and columns
  976. XSSFRow r1 = s.createRow(0);
  977. XSSFRow r2 = s.createRow(1);
  978. r1.createCell(0);
  979. r1.createCell(2);
  980. r2.createCell(0);
  981. r2.createCell(3);
  982. // Check no style is there
  983. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  984. assertEquals(0, cols.sizeOfColArray());
  985. assertEquals(defaultStyle, s.getColumnStyle(0));
  986. assertEquals(defaultStyle, s.getColumnStyle(2));
  987. assertEquals(defaultStyle, s.getColumnStyle(3));
  988. // Apply the styles
  989. s.setDefaultColumnStyle(0, pinkStyle);
  990. s.setDefaultColumnStyle(3, blueStyle);
  991. // Check
  992. assertEquals(pinkStyle, s.getColumnStyle(0));
  993. assertEquals(defaultStyle, s.getColumnStyle(2));
  994. assertEquals(blueStyle, s.getColumnStyle(3));
  995. assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
  996. assertEquals(2, cols.sizeOfColArray());
  997. assertEquals(1, cols.getColArray(0).getMin());
  998. assertEquals(1, cols.getColArray(0).getMax());
  999. assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
  1000. assertEquals(4, cols.getColArray(1).getMin());
  1001. assertEquals(4, cols.getColArray(1).getMax());
  1002. assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
  1003. // Save, re-load and re-check
  1004. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1005. s = wb.getSheetAt(0);
  1006. defaultStyle = wb.getCellStyleAt(defaultStyle.getIndex());
  1007. blueStyle = wb.getCellStyleAt(blueStyle.getIndex());
  1008. pinkStyle = wb.getCellStyleAt(pinkStyle.getIndex());
  1009. assertEquals(pinkStyle, s.getColumnStyle(0));
  1010. assertEquals(defaultStyle, s.getColumnStyle(2));
  1011. assertEquals(blueStyle, s.getColumnStyle(3));
  1012. wb.close();
  1013. }
  1014. /**
  1015. * Repeatedly writing a file.
  1016. * Something with the SharedStringsTable currently breaks...
  1017. */
  1018. @Test
  1019. public void bug46662() throws Exception {
  1020. // New file
  1021. XSSFWorkbook wb = new XSSFWorkbook();
  1022. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1023. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1024. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1025. // Simple file
  1026. wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  1027. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1028. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1029. XSSFTestDataSamples.writeOutAndReadBack(wb);
  1030. // Complex file
  1031. // TODO
  1032. }
  1033. /**
  1034. * Colours and styles when the list has gaps in it
  1035. */
  1036. @Test
  1037. public void bug51222() throws Exception {
  1038. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx");
  1039. XSSFSheet s = wb.getSheetAt(0);
  1040. XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0);
  1041. XSSFCell cA5_1F497D = s.getRow(4).getCell(0);
  1042. // Check the text
  1043. assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString());
  1044. assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString());
  1045. // Check the styles assigned to them
  1046. assertEquals(4, cA4_EEECE1.getCTCell().getS());
  1047. assertEquals(5, cA5_1F497D.getCTCell().getS());
  1048. // Check we look up the correct style
  1049. assertEquals(4, cA4_EEECE1.getCellStyle().getIndex());
  1050. assertEquals(5, cA5_1F497D.getCellStyle().getIndex());
  1051. // Check the fills on them at the low level
  1052. assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId());
  1053. assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId());
  1054. // These should reference themes 2 and 3
  1055. assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme());
  1056. assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme());
  1057. // Ensure we get the right colours for these themes
  1058. // TODO fix
  1059. // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex());
  1060. // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex());
  1061. // Finally check the colours on the styles
  1062. // TODO fix
  1063. // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1064. // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex());
  1065. }
  1066. @Test
  1067. public void bug51470() throws Exception {
  1068. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx");
  1069. XSSFSheet sh0 = wb.getSheetAt(0);
  1070. XSSFSheet sh1 = wb.cloneSheet(0);
  1071. List<POIXMLDocumentPart> rels0 = sh0.getRelations();
  1072. List<POIXMLDocumentPart> rels1 = sh1.getRelations();
  1073. assertEquals(1, rels0.size());
  1074. assertEquals(1, rels1.size());
  1075. assertEquals(rels0.get(0).getPackageRelationship(), rels1.get(0).getPackageRelationship());
  1076. }
  1077. /**
  1078. * Add comments to Sheet 1, when Sheet 2 already has
  1079. * comments (so /xl/comments1.xml is taken)
  1080. */
  1081. @Test
  1082. public void bug51850() {
  1083. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx");
  1084. XSSFSheet sh1 = wb.getSheetAt(0);
  1085. XSSFSheet sh2 = wb.getSheetAt(1);
  1086. // Sheet 2 has comments
  1087. assertNotNull(sh2.getCommentsTable(false));
  1088. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1089. // Sheet 1 doesn't (yet)
  1090. assertNull(sh1.getCommentsTable(false));
  1091. // Try to add comments to Sheet 1
  1092. CreationHelper factory = wb.getCreationHelper();
  1093. Drawing drawing = sh1.createDrawingPatriarch();
  1094. ClientAnchor anchor = factory.createClientAnchor();
  1095. anchor.setCol1(0);
  1096. anchor.setCol2(4);
  1097. anchor.setRow1(0);
  1098. anchor.setRow2(1);
  1099. Comment comment1 = drawing.createCellComment(anchor);
  1100. comment1.setString(
  1101. factory.createRichTextString("I like this cell. It's my favourite."));
  1102. comment1.setAuthor("Bob T. Fish");
  1103. Comment comment2 = drawing.createCellComment(anchor);
  1104. comment2.setString(
  1105. factory.createRichTextString("This is much less fun..."));
  1106. comment2.setAuthor("Bob T. Fish");
  1107. Cell c1 = sh1.getRow(0).createCell(4);
  1108. c1.setCellValue(2.3);
  1109. c1.setCellComment(comment1);
  1110. Cell c2 = sh1.getRow(0).createCell(5);
  1111. c2.setCellValue(2.1);
  1112. c2.setCellComment(comment2);
  1113. // Save and re-load
  1114. wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1115. sh1 = wb.getSheetAt(0);
  1116. sh2 = wb.getSheetAt(1);
  1117. // Check the comments
  1118. assertNotNull(sh2.getCommentsTable(false));
  1119. assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
  1120. assertNotNull(sh1.getCommentsTable(false));
  1121. assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
  1122. }
  1123. /**
  1124. * Sheet names with a , in them
  1125. */
  1126. @Test
  1127. public void bug51963() throws Exception {
  1128. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx");
  1129. XSSFSheet sheet = wb.getSheetAt(0);
  1130. assertEquals("Abc,1", sheet.getSheetName());
  1131. Name name = wb.getName("Intekon.ProdCodes");
  1132. assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula());
  1133. AreaReference ref = new AreaReference(name.getRefersToFormula());
  1134. assertEquals(0, ref.getFirstCell().getRow());
  1135. assertEquals(0, ref.getFirstCell().getCol());
  1136. assertEquals(1, ref.getLastCell().getRow());
  1137. assertEquals(0, ref.getLastCell().getCol());
  1138. }
  1139. /**
  1140. * Sum across multiple workbooks
  1141. * eg =SUM($Sheet1.C1:$Sheet4.C1)
  1142. * DISABLED As we can't currently evaluate these
  1143. */
  1144. @Ignore
  1145. public void bug48703() throws Exception {
  1146. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx");
  1147. XSSFSheet sheet = wb.getSheetAt(0);
  1148. // Contains two forms, one with a range and one a list
  1149. XSSFRow r1 = sheet.getRow(0);
  1150. XSSFRow r2 = sheet.getRow(1);
  1151. XSSFCell c1 = r1.getCell(1);
  1152. XSSFCell c2 = r2.getCell(1);
  1153. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1154. assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula());
  1155. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1156. assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula());
  1157. // Try evaluating both
  1158. XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
  1159. eval.evaluateFormulaCell(c1);
  1160. eval.evaluateFormulaCell(c2);
  1161. assertEquals(20.0, c1.getNumericCellValue(), 0);
  1162. assertEquals(20.0, c2.getNumericCellValue(), 0);
  1163. }
  1164. /**
  1165. * Bugzilla 51710: problems reading shared formuals from .xlsx
  1166. */
  1167. @Test
  1168. public void bug51710() {
  1169. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx");
  1170. final String[] columns = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
  1171. final int rowMax = 500; // bug triggers on row index 59
  1172. Sheet sheet = wb.getSheetAt(0);
  1173. // go through all formula cells
  1174. for (int rInd = 2; rInd <= rowMax; rInd++) {
  1175. Row row = sheet.getRow(rInd);
  1176. for (int cInd = 1; cInd <= 12; cInd++) {
  1177. Cell cell = row.getCell(cInd);
  1178. String formula = cell.getCellFormula();
  1179. CellReference ref = new CellReference(cell);
  1180. //simulate correct answer
  1181. String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2";
  1182. assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula);
  1183. }
  1184. }
  1185. }
  1186. /**
  1187. * Bug 53101:
  1188. */
  1189. @Test
  1190. public void bug5301(){
  1191. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx");
  1192. FormulaEvaluator evaluator =
  1193. workbook.getCreationHelper().createFormulaEvaluator();
  1194. // A1: SUM(B1: IZ1)
  1195. double a1Value =
  1196. evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(0)).getNumberValue();
  1197. // Assert
  1198. assertEquals(259.0, a1Value, 0.0);
  1199. // KY: SUM(B1: IZ1)
  1200. /*double ky1Value =*/
  1201. evaluator.evaluate(workbook.getSheetAt(0).getRow(0).getCell(310)).getNumberValue();
  1202. // Assert
  1203. assertEquals(259.0, a1Value, 0.0);
  1204. }
  1205. @Test
  1206. public void bug54436(){
  1207. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx");
  1208. if(!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")){
  1209. Function func = new Function() {
  1210. public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
  1211. return ErrorEval.NA;
  1212. }
  1213. };
  1214. WorkbookEvaluator.registerFunction("GETPIVOTDATA", func);
  1215. }
  1216. workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
  1217. }
  1218. /**
  1219. * Password Protected .xlsx files should give a helpful
  1220. * error message when called via WorkbookFactory.
  1221. * (You need to supply a password explicitly for them)
  1222. */
  1223. @Test(expected=EncryptedDocumentException.class)
  1224. public void bug55692_stream() throws Exception {
  1225. // Directly on a Stream
  1226. WorkbookFactory.create(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1227. }
  1228. @Test(expected=EncryptedDocumentException.class)
  1229. public void bug55692_poifs() throws Exception {
  1230. // Via a POIFSFileSystem
  1231. POIFSFileSystem fsP = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1232. WorkbookFactory.create(fsP);
  1233. }
  1234. @Test(expected=EncryptedDocumentException.class)
  1235. public void bug55692_npoifs() throws Exception {
  1236. // Via a NPOIFSFileSystem
  1237. NPOIFSFileSystem fsNP = new NPOIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
  1238. WorkbookFactory.create(fsNP);
  1239. }
  1240. @Test
  1241. public void bug53282() {
  1242. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx");
  1243. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1244. assertEquals("#@_#", c.getStringCellValue());
  1245. assertEquals("http://invalid.uri", c.getHyperlink().getAddress());
  1246. }
  1247. /**
  1248. * Was giving NullPointerException
  1249. * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead
  1250. * due to a lack of Styles Table
  1251. */
  1252. @Test
  1253. public void bug56278() throws Exception {
  1254. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx");
  1255. assertEquals(0, wb.getSheetIndex("Market Rates"));
  1256. // Save and re-check
  1257. Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
  1258. assertEquals(0, nwb.getSheetIndex("Market Rates"));
  1259. }
  1260. @Test
  1261. public void bug56315() {
  1262. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx");
  1263. Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
  1264. CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c);
  1265. double rounded = cv.getNumberValue();
  1266. assertEquals(0.1, rounded, 0.0);
  1267. }
  1268. @Test
  1269. public void bug56468() throws Exception {
  1270. XSSFWorkbook wb = new XSSFWorkbook();
  1271. XSSFSheet sheet = wb.createSheet();
  1272. XSSFRow row = sheet.createRow(0);
  1273. XSSFCell cell = row.createCell(0);
  1274. cell.setCellValue("Hi");
  1275. sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0));
  1276. ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
  1277. wb.write(bos);
  1278. byte firstSave[] = bos.toByteArray();
  1279. bos.reset();
  1280. wb.write(bos);
  1281. byte secondSave[] = bos.toByteArray();
  1282. assertThat(firstSave, equalTo(secondSave));
  1283. wb.close();
  1284. }
  1285. /**
  1286. * ISO-8601 style cell formats with a T in them, eg
  1287. * cell format of "yyyy-MM-ddTHH:mm:ss"
  1288. */
  1289. @Test
  1290. public void bug54034() throws IOException {
  1291. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx");
  1292. Sheet sheet = wb.getSheet("Sheet1");
  1293. Row row = sheet.getRow(1);
  1294. Cell cell = row.getCell(2);
  1295. assertTrue(DateUtil.isCellDateFormatted(cell));
  1296. DataFormatter fmt = new DataFormatter();
  1297. assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
  1298. assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
  1299. }
  1300. @Test
  1301. public void testBug53798XLSX() throws IOException {
  1302. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1303. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1304. bug53798Work(wb, xlsOutput);
  1305. }
  1306. @Ignore("Shifting rows is not yet implemented in SXSSFSheet")
  1307. @Test
  1308. public void testBug53798XLSXStream() throws IOException {
  1309. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx");
  1310. File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
  1311. bug53798Work(new SXSSFWorkbook(wb), xlsOutput);
  1312. }
  1313. @Test
  1314. public void testBug53798XLS() throws IOException {
  1315. Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls");
  1316. File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
  1317. bug53798Work(wb, xlsOutput);
  1318. }
  1319. /**
  1320. * SUMIF was throwing a NPE on some formulas
  1321. */
  1322. @Test
  1323. @Ignore("This bug is still to be fixed")
  1324. public void testBug56420SumIfNPE() throws Exception {
  1325. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx");
  1326. FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  1327. Sheet sheet = wb.getSheetAt(0);
  1328. Row r = sheet.getRow(2);
  1329. Cell c = r.getCell(2);
  1330. assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula());
  1331. evaluator.evaluateInCell(c);
  1332. }
  1333. private void bug53798Work(Workbook wb, File xlsOutput) throws IOException {
  1334. Sheet testSheet = wb.getSheetAt(0);
  1335. testSheet.shiftRows(2, 2, 1);
  1336. saveAndReloadReport(wb, xlsOutput);
  1337. // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about
  1338. // when shifted by less than -1 negative amount (try -2)
  1339. testSheet.shiftRows(3, 3, -1);
  1340. saveAndReloadReport(wb, xlsOutput);
  1341. testSheet.shiftRows(2, 2, 1);
  1342. saveAndReloadReport(wb, xlsOutput);
  1343. Row newRow = null;
  1344. Cell newCell = null;
  1345. // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted
  1346. // xlsx file with unreadable data in the negative shifted row.
  1347. // NOTE it's ok to create any other row.
  1348. newRow = testSheet.createRow(3);
  1349. saveAndReloadReport(wb, xlsOutput);
  1350. newCell = newRow.createCell(0);
  1351. saveAndReloadReport(wb, xlsOutput);
  1352. newCell.setCellValue("new Cell in row "+newRow.getRowNum());
  1353. saveAndReloadReport(wb, xlsOutput);
  1354. // 3) once a negative shift has been made any attempt to shift another group of rows
  1355. // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception:
  1356. // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException.
  1357. // NOTE: another negative shift on another group of rows is successful, provided no new rows in
  1358. // place of previously shifted rows were attempted to be created as explained above.
  1359. testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of
  1360. // the above has been tested
  1361. saveAndReloadReport(wb, xlsOutput);
  1362. }
  1363. /**
  1364. * XSSFCell.typeMismatch on certain blank cells when formatting
  1365. * with DataFormatter
  1366. */
  1367. @Test
  1368. public void bug56702() throws Exception {
  1369. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx");
  1370. Sheet sheet = wb.getSheetAt(0);
  1371. // Get wrong cell by row 8 & column 7
  1372. Cell cell = sheet.getRow(8).getCell(7);
  1373. assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType());
  1374. // Check the value - will be zero as it is <c><v/></c>
  1375. assertEquals(0.0, cell.getNumericCellValue(), 0.001);
  1376. // Try to format
  1377. DataFormatter formatter = new DataFormatter();
  1378. formatter.formatCellValue(cell);
  1379. // Check the formatting
  1380. assertEquals("0", formatter.formatCellValue(cell));
  1381. }
  1382. /**
  1383. * Formulas which reference named ranges, either in other
  1384. * sheets, or workbook scoped but in other workbooks.
  1385. * Used to fail with with errors like
  1386. * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9
  1387. * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name
  1388. */
  1389. @Test
  1390. public void bug56737() throws IOException {
  1391. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx");
  1392. // Check the named range definitions
  1393. Name nSheetScope = wb.getName("NR_To_A1");
  1394. Name nWBScope = wb.getName("NR_Global_B2");
  1395. assertNotNull(nSheetScope);
  1396. assertNotNull(nWBScope);
  1397. assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula());
  1398. assertEquals("Defines!$B$2", nWBScope.getRefersToFormula());
  1399. // Check the different kinds of formulas
  1400. Sheet s = wb.getSheetAt(0);
  1401. Cell cRefSName = s.getRow(1).getCell(3);
  1402. Cell cRefWName = s.getRow(2).getCell(3);
  1403. assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula());
  1404. // Note the formula, as stored in the file, has the external name index not filename
  1405. // TODO Provide a way to get the one with the filename
  1406. assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula());
  1407. // Try to evaluate them
  1408. FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
  1409. assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue());
  1410. assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue());
  1411. // Try to evaluate everything
  1412. eval.evaluateAll();
  1413. }
  1414. private void saveAndReloadReport(Workbook wb, File outFile) throws IOException {
  1415. // run some method on the font to verify if it is "disconnected" already
  1416. //for(short i = 0;i < 256;i++)
  1417. {
  1418. Font font = wb.getFontAt((short)0);
  1419. if(font instanceof XSSFFont) {
  1420. XSSFFont xfont = (XSSFFont) wb.getFontAt((short)0);
  1421. CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont();
  1422. assertEquals(0, ctFont.sizeOfBArray());
  1423. }
  1424. }
  1425. FileOutputStream fileOutStream = new FileOutputStream(outFile);
  1426. wb.write(fileOutStream);
  1427. fileOutStream.close();
  1428. //System.out.println("File \""+outFile.getName()+"\" has been saved successfully");
  1429. FileInputStream is = new FileInputStream(outFile);
  1430. try {
  1431. Workbook newWB = null;
  1432. try {
  1433. if(wb instanceof XSSFWorkbook) {
  1434. newWB = new XSSFWorkbook(is);
  1435. } else if(wb instanceof HSSFWorkbook) {
  1436. newWB = new HSSFWorkbook(is);
  1437. } else if(wb instanceof SXSSFWorkbook) {
  1438. newWB = new SXSSFWorkbook(new XSSFWorkbook(is));
  1439. } else {
  1440. throw new IllegalStateException("Unknown workbook: " + wb);
  1441. }
  1442. assertNotNull(newWB.getSheet("test"));
  1443. } finally {
  1444. newWB.close();
  1445. }
  1446. } finally {
  1447. is.close();
  1448. }
  1449. }
  1450. @Test
  1451. public void testBug56688_1() {
  1452. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx");
  1453. checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
  1454. }
  1455. @Test
  1456. public void testBug56688_2() {
  1457. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx");
  1458. checkValue(excel, "#VALUE!");
  1459. }
  1460. @Test
  1461. public void testBug56688_3() {
  1462. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx");
  1463. checkValue(excel, "#VALUE!");
  1464. }
  1465. @Test
  1466. public void testBug56688_4() {
  1467. XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx");
  1468. // Calendar calendar = Calendar.getInstance();
  1469. // calendar.add(Calendar.MONTH, 2);
  1470. // double excelDate = DateUtil.getExcelDate(calendar.getTime());
  1471. // NumberEval eval = new NumberEval(Math.floor(excelDate));
  1472. // checkValue(excel, eval.getStringValue() + ".0");
  1473. checkValue(excel, "41904.0");
  1474. }
  1475. private void checkValue(XSSFWorkbook excel, String expect) {
  1476. XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
  1477. evaluator.evaluateAll();
  1478. XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
  1479. CellValue value = evaluator.evaluate(cell);
  1480. assertEquals(expect, value.formatAsString());
  1481. }
  1482. }