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.

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