Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TestXSSFBugs.java 62KB

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