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.

TestXSSFWorkbook.java 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.usermodel;
  16. import static org.junit.Assert.assertArrayEquals;
  17. import static org.junit.Assert.assertEquals;
  18. import static org.junit.Assert.assertFalse;
  19. import static org.junit.Assert.assertNotNull;
  20. import static org.junit.Assert.assertNull;
  21. import static org.junit.Assert.assertSame;
  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.io.OutputStream;
  31. import java.util.Date;
  32. import java.util.Iterator;
  33. import java.util.List;
  34. import java.util.zip.CRC32;
  35. import org.apache.poi.POIDataSamples;
  36. import org.apache.poi.hssf.HSSFTestDataSamples;
  37. import org.apache.poi.ooxml.POIXMLProperties;
  38. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  39. import org.apache.poi.openxml4j.opc.ContentTypes;
  40. import org.apache.poi.openxml4j.opc.OPCPackage;
  41. import org.apache.poi.openxml4j.opc.PackageAccess;
  42. import org.apache.poi.openxml4j.opc.PackagePart;
  43. import org.apache.poi.openxml4j.opc.PackagePartName;
  44. import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
  45. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  46. import org.apache.poi.openxml4j.opc.internal.FileHelper;
  47. import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart;
  48. import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
  49. import org.apache.poi.ss.usermodel.BaseTestXWorkbook;
  50. import org.apache.poi.ss.usermodel.Cell;
  51. import org.apache.poi.ss.usermodel.CellStyle;
  52. import org.apache.poi.ss.usermodel.Font;
  53. import org.apache.poi.ss.usermodel.RichTextString;
  54. import org.apache.poi.ss.usermodel.Row;
  55. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  56. import org.apache.poi.ss.usermodel.Sheet;
  57. import org.apache.poi.ss.usermodel.Workbook;
  58. import org.apache.poi.ss.usermodel.WorkbookFactory;
  59. import org.apache.poi.ss.util.AreaReference;
  60. import org.apache.poi.ss.util.CellReference;
  61. import org.apache.poi.util.IOUtils;
  62. import org.apache.poi.util.LocaleUtil;
  63. import org.apache.poi.util.TempFile;
  64. import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
  65. import org.apache.poi.xddf.usermodel.chart.XDDFChartData;
  66. import org.apache.poi.xssf.XSSFITestDataProvider;
  67. import org.apache.poi.xssf.XSSFTestDataSamples;
  68. import org.apache.poi.xssf.model.StylesTable;
  69. import org.junit.Test;
  70. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr;
  71. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache;
  72. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
  73. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
  74. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode;
  75. public final class TestXSSFWorkbook extends BaseTestXWorkbook {
  76. public TestXSSFWorkbook() {
  77. super(XSSFITestDataProvider.instance);
  78. }
  79. /**
  80. * Tests that we can save, and then re-load a new document
  81. */
  82. @Test
  83. public void saveLoadNew() throws IOException, InvalidFormatException {
  84. XSSFWorkbook wb1 = new XSSFWorkbook();
  85. //check that the default date system is set to 1900
  86. CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr();
  87. assertNotNull(pr);
  88. assertTrue(pr.isSetDate1904());
  89. assertFalse("XSSF must use the 1900 date system", pr.getDate1904());
  90. Sheet sheet1 = wb1.createSheet("sheet1");
  91. Sheet sheet2 = wb1.createSheet("sheet2");
  92. wb1.createSheet("sheet3");
  93. RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world");
  94. sheet1.createRow(0).createCell((short)0).setCellValue(1.2);
  95. sheet1.createRow(1).createCell((short)0).setCellValue(rts);
  96. sheet2.createRow(0);
  97. assertEquals(0, wb1.getSheetAt(0).getFirstRowNum());
  98. assertEquals(1, wb1.getSheetAt(0).getLastRowNum());
  99. assertEquals(0, wb1.getSheetAt(1).getFirstRowNum());
  100. assertEquals(0, wb1.getSheetAt(1).getLastRowNum());
  101. assertEquals(0, wb1.getSheetAt(2).getFirstRowNum());
  102. assertEquals(0, wb1.getSheetAt(2).getLastRowNum());
  103. File file = TempFile.createTempFile("poi-", ".xlsx");
  104. OutputStream out = new FileOutputStream(file);
  105. wb1.write(out);
  106. out.close();
  107. // Check the package contains what we'd expect it to
  108. OPCPackage pkg = OPCPackage.open(file.toString());
  109. PackagePart wbRelPart =
  110. pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels"));
  111. assertNotNull(wbRelPart);
  112. assertTrue(wbRelPart.isRelationshipPart());
  113. assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType());
  114. PackagePart wbPart =
  115. pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
  116. // Links to the three sheets, shared strings and styles
  117. assertTrue(wbPart.hasRelationships());
  118. assertEquals(5, wbPart.getRelationships().size());
  119. wb1.close();
  120. // Load back the XSSFWorkbook
  121. @SuppressWarnings("resource")
  122. XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
  123. assertEquals(3, wb2.getNumberOfSheets());
  124. assertNotNull(wb2.getSheetAt(0));
  125. assertNotNull(wb2.getSheetAt(1));
  126. assertNotNull(wb2.getSheetAt(2));
  127. assertNotNull(wb2.getSharedStringSource());
  128. assertNotNull(wb2.getStylesSource());
  129. assertEquals(0, wb2.getSheetAt(0).getFirstRowNum());
  130. assertEquals(1, wb2.getSheetAt(0).getLastRowNum());
  131. assertEquals(0, wb2.getSheetAt(1).getFirstRowNum());
  132. assertEquals(0, wb2.getSheetAt(1).getLastRowNum());
  133. assertEquals(0, wb2.getSheetAt(2).getFirstRowNum());
  134. assertEquals(0, wb2.getSheetAt(2).getLastRowNum());
  135. sheet1 = wb2.getSheetAt(0);
  136. assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001);
  137. assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString());
  138. pkg.close();
  139. }
  140. @Test
  141. public void existing() throws Exception {
  142. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
  143. assertNotNull(workbook.getSharedStringSource());
  144. assertNotNull(workbook.getStylesSource());
  145. // And check a few low level bits too
  146. OPCPackage pkg = OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx"));
  147. PackagePart wbPart =
  148. pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
  149. // Links to the three sheets, shared, styles and themes
  150. assertTrue(wbPart.hasRelationships());
  151. assertEquals(6, wbPart.getRelationships().size());
  152. pkg.close();
  153. workbook.close();
  154. }
  155. @Test
  156. public void getCellStyleAt() throws IOException{
  157. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  158. short i = 0;
  159. //get default style
  160. CellStyle cellStyleAt = workbook.getCellStyleAt(i);
  161. assertNotNull(cellStyleAt);
  162. //get custom style
  163. StylesTable styleSource = workbook.getStylesSource();
  164. XSSFCellStyle customStyle = new XSSFCellStyle(styleSource);
  165. XSSFFont font = new XSSFFont();
  166. font.setFontName("Verdana");
  167. customStyle.setFont(font);
  168. int x = styleSource.putStyle(customStyle);
  169. cellStyleAt = workbook.getCellStyleAt((short) x);
  170. assertNotNull(cellStyleAt);
  171. }
  172. }
  173. @Test
  174. public void getFontAt() throws IOException{
  175. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  176. StylesTable styleSource = workbook.getStylesSource();
  177. short i = 0;
  178. //get default font
  179. Font fontAt = workbook.getFontAt(i);
  180. assertNotNull(fontAt);
  181. //get customized font
  182. XSSFFont customFont = new XSSFFont();
  183. customFont.setItalic(true);
  184. int x = styleSource.putFont(customFont);
  185. fontAt = workbook.getFontAt((short) x);
  186. assertNotNull(fontAt);
  187. }
  188. }
  189. @Test
  190. public void getNumCellStyles() throws IOException{
  191. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  192. //get default cellStyles
  193. assertEquals(1, workbook.getNumCellStyles());
  194. }
  195. }
  196. @Test
  197. public void loadSave() throws IOException {
  198. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
  199. assertEquals(3, workbook.getNumberOfSheets());
  200. assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString());
  201. assertNotNull(workbook.getSharedStringSource());
  202. assertNotNull(workbook.getStylesSource());
  203. // Write out, and check
  204. // Load up again, check all still there
  205. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  206. assertEquals(3, wb2.getNumberOfSheets());
  207. assertNotNull(wb2.getSheetAt(0));
  208. assertNotNull(wb2.getSheetAt(1));
  209. assertNotNull(wb2.getSheetAt(2));
  210. assertEquals("dd/mm/yyyy", wb2.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString());
  211. assertEquals("yyyy/mm/dd", wb2.getSheetAt(0).getRow(2).getCell(0).getRichStringCellValue().getString());
  212. assertEquals("yyyy-mm-dd", wb2.getSheetAt(0).getRow(3).getCell(0).getRichStringCellValue().getString());
  213. assertEquals("yy/mm/dd", wb2.getSheetAt(0).getRow(4).getCell(0).getRichStringCellValue().getString());
  214. assertNotNull(wb2.getSharedStringSource());
  215. assertNotNull(wb2.getStylesSource());
  216. workbook.close();
  217. wb2.close();
  218. }
  219. @Test
  220. public void styles() throws IOException {
  221. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
  222. StylesTable ss = wb1.getStylesSource();
  223. assertNotNull(ss);
  224. StylesTable st = ss;
  225. // Has 8 number formats
  226. assertEquals(8, st.getNumDataFormats());
  227. // Has 2 fonts
  228. assertEquals(2, st.getFonts().size());
  229. // Has 2 fills
  230. assertEquals(2, st.getFills().size());
  231. // Has 1 border
  232. assertEquals(1, st.getBorders().size());
  233. // Add two more styles
  234. assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
  235. st.putNumberFormat("testFORMAT"));
  236. assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
  237. st.putNumberFormat("testFORMAT"));
  238. assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9,
  239. st.putNumberFormat("testFORMAT2"));
  240. assertEquals(10, st.getNumDataFormats());
  241. // Save, load back in again, and check
  242. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  243. wb1.close();
  244. ss = wb2.getStylesSource();
  245. assertNotNull(ss);
  246. assertEquals(10, st.getNumDataFormats());
  247. assertEquals(2, st.getFonts().size());
  248. assertEquals(2, st.getFills().size());
  249. assertEquals(1, st.getBorders().size());
  250. wb2.close();
  251. }
  252. @Test
  253. public void incrementSheetId() throws IOException {
  254. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  255. int sheetId = (int) wb.createSheet().sheet.getSheetId();
  256. assertEquals(1, sheetId);
  257. sheetId = (int) wb.createSheet().sheet.getSheetId();
  258. assertEquals(2, sheetId);
  259. //test file with gaps in the sheetId sequence
  260. try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) {
  261. int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
  262. sheetId = (int) wbBack.createSheet().sheet.getSheetId();
  263. assertEquals(lastSheetId + 1, sheetId);
  264. }
  265. }
  266. }
  267. /**
  268. * Test setting of core properties such as Title and Author
  269. */
  270. @Test
  271. public void workbookProperties() throws IOException {
  272. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  273. POIXMLProperties props = workbook.getProperties();
  274. assertNotNull(props);
  275. //the Application property must be set for new workbooks, see Bugzilla #47559
  276. assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication());
  277. PackagePropertiesPart opcProps = props.getCoreProperties().getUnderlyingProperties();
  278. assertNotNull(opcProps);
  279. opcProps.setTitleProperty("Testing Bugzilla #47460");
  280. assertEquals("Apache POI", opcProps.getCreatorProperty().get());
  281. opcProps.setCreatorProperty("poi-dev@poi.apache.org");
  282. XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  283. assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication());
  284. opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties();
  285. assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().get());
  286. assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().get());
  287. wbBack.close();
  288. }
  289. }
  290. /**
  291. * Verify that the attached test data was not modified. If this test method
  292. * fails, the test data is not working properly.
  293. */
  294. @Test
  295. public void bug47668() throws Exception {
  296. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("47668.xlsx");
  297. List<XSSFPictureData> allPictures = workbook.getAllPictures();
  298. assertEquals(1, allPictures.size());
  299. PackagePartName imagePartName = PackagingURIHelper
  300. .createPartName("/xl/media/image1.jpeg");
  301. PackagePart imagePart = workbook.getPackage().getPart(imagePartName);
  302. assertNotNull(imagePart);
  303. for (XSSFPictureData pictureData : allPictures) {
  304. PackagePart picturePart = pictureData.getPackagePart();
  305. assertSame(imagePart, picturePart);
  306. }
  307. XSSFSheet sheet0 = workbook.getSheetAt(0);
  308. XSSFDrawing drawing0 = sheet0.createDrawingPatriarch();
  309. XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0);
  310. byte[] data0 = pictureData0.getData();
  311. CRC32 crc0 = new CRC32();
  312. crc0.update(data0);
  313. XSSFSheet sheet1 = workbook.getSheetAt(1);
  314. XSSFDrawing drawing1 = sheet1.createDrawingPatriarch();
  315. XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0);
  316. byte[] data1 = pictureData1.getData();
  317. CRC32 crc1 = new CRC32();
  318. crc1.update(data1);
  319. assertEquals(crc0.getValue(), crc1.getValue());
  320. workbook.close();
  321. }
  322. /**
  323. * When deleting a sheet make sure that we adjust sheet indices of named ranges
  324. */
  325. @SuppressWarnings("deprecation")
  326. @Test
  327. public void bug47737() throws IOException {
  328. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx");
  329. assertEquals(2, wb.getNumberOfNames());
  330. assertNotNull(wb.getCalculationChain());
  331. XSSFName nm0 = wb.getNameAt(0);
  332. assertTrue(nm0.getCTName().isSetLocalSheetId());
  333. assertEquals(0, nm0.getCTName().getLocalSheetId());
  334. XSSFName nm1 = wb.getNameAt(1);
  335. assertTrue(nm1.getCTName().isSetLocalSheetId());
  336. assertEquals(1, nm1.getCTName().getLocalSheetId());
  337. wb.removeSheetAt(0);
  338. assertEquals(1, wb.getNumberOfNames());
  339. XSSFName nm2 = wb.getNameAt(0);
  340. assertTrue(nm2.getCTName().isSetLocalSheetId());
  341. assertEquals(0, nm2.getCTName().getLocalSheetId());
  342. //calculation chain is removed as well
  343. assertNull(wb.getCalculationChain());
  344. wb.close();
  345. }
  346. /**
  347. * Problems with XSSFWorkbook.removeSheetAt when workbook contains charts
  348. */
  349. @Test
  350. public void bug47813() throws IOException {
  351. XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx");
  352. assertEquals(3, wb1.getNumberOfSheets());
  353. assertNotNull(wb1.getCalculationChain());
  354. assertEquals("Numbers", wb1.getSheetName(0));
  355. //the second sheet is of type 'chartsheet'
  356. assertEquals("Chart", wb1.getSheetName(1));
  357. assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet);
  358. assertEquals("SomeJunk", wb1.getSheetName(2));
  359. wb1.removeSheetAt(2);
  360. assertEquals(2, wb1.getNumberOfSheets());
  361. assertNull(wb1.getCalculationChain());
  362. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  363. assertEquals(2, wb2.getNumberOfSheets());
  364. assertNull(wb2.getCalculationChain());
  365. assertEquals("Numbers", wb2.getSheetName(0));
  366. assertEquals("Chart", wb2.getSheetName(1));
  367. wb2.close();
  368. wb1.close();
  369. }
  370. /**
  371. * Problems with the count of the number of styles
  372. * coming out wrong
  373. */
  374. @Test
  375. public void bug49702() throws IOException {
  376. // First try with a new file
  377. XSSFWorkbook wb1 = new XSSFWorkbook();
  378. // Should have one style
  379. assertEquals(1, wb1.getNumCellStyles());
  380. wb1.getCellStyleAt((short)0);
  381. assertNull("Shouldn't be able to get style at 0 that doesn't exist",
  382. wb1.getCellStyleAt((short)1));
  383. // Add another one
  384. CellStyle cs = wb1.createCellStyle();
  385. cs.setDataFormat((short)11);
  386. // Re-check
  387. assertEquals(2, wb1.getNumCellStyles());
  388. wb1.getCellStyleAt((short)0);
  389. wb1.getCellStyleAt((short)1);
  390. assertNull("Shouldn't be able to get style at 2 that doesn't exist",
  391. wb1.getCellStyleAt((short)2));
  392. // Save and reload
  393. XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  394. assertEquals(2, nwb.getNumCellStyles());
  395. nwb.getCellStyleAt((short)0);
  396. nwb.getCellStyleAt((short)1);
  397. assertNull("Shouldn't be able to get style at 2 that doesn't exist",
  398. nwb.getCellStyleAt((short)2));
  399. // Now with an existing file
  400. XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx");
  401. assertEquals(3, wb2.getNumCellStyles());
  402. wb2.getCellStyleAt((short)0);
  403. wb2.getCellStyleAt((short)1);
  404. wb2.getCellStyleAt((short)2);
  405. assertNull("Shouldn't be able to get style at 3 that doesn't exist",
  406. wb2.getCellStyleAt((short)3));
  407. wb2.close();
  408. wb1.close();
  409. nwb.close();
  410. }
  411. @Test
  412. public void recalcId() throws IOException {
  413. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  414. assertFalse(wb.getForceFormulaRecalculation());
  415. CTWorkbook ctWorkbook = wb.getCTWorkbook();
  416. assertFalse(ctWorkbook.isSetCalcPr());
  417. wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero
  418. CTCalcPr calcPr = ctWorkbook.getCalcPr();
  419. assertNotNull(calcPr);
  420. assertEquals(0, (int) calcPr.getCalcId());
  421. calcPr.setCalcId(100);
  422. assertTrue(wb.getForceFormulaRecalculation());
  423. wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero
  424. assertEquals(0, (int) calcPr.getCalcId());
  425. assertFalse(wb.getForceFormulaRecalculation());
  426. // calcMode="manual" is unset when forceFormulaRecalculation=true
  427. calcPr.setCalcMode(STCalcMode.MANUAL);
  428. wb.setForceFormulaRecalculation(true);
  429. assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
  430. }
  431. }
  432. @Test
  433. public void changeSheetNameWithSharedFormulas() throws IOException {
  434. changeSheetNameWithSharedFormulas("shared_formulas.xlsx");
  435. }
  436. @Test
  437. public void columnWidthPOI52233() throws Exception {
  438. XSSFWorkbook workbook = new XSSFWorkbook();
  439. XSSFSheet sheet = workbook.createSheet();
  440. XSSFRow row = sheet.createRow(0);
  441. XSSFCell cell = row.createCell(0);
  442. cell.setCellValue("hello world");
  443. sheet = workbook.createSheet();
  444. sheet.setColumnWidth(4, 5000);
  445. sheet.setColumnWidth(5, 5000);
  446. sheet.groupColumn((short) 4, (short) 5);
  447. accessWorkbook(workbook);
  448. try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
  449. workbook.write(stream);
  450. }
  451. accessWorkbook(workbook);
  452. workbook.close();
  453. }
  454. private void accessWorkbook(XSSFWorkbook workbook) {
  455. workbook.getSheetAt(1).setColumnGroupCollapsed(4, true);
  456. workbook.getSheetAt(1).setColumnGroupCollapsed(4, false);
  457. assertEquals("hello world", workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
  458. assertEquals(2048, workbook.getSheetAt(0).getColumnWidth(0)); // <-works
  459. }
  460. @Test
  461. public void bug48495() throws IOException {
  462. Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx");
  463. assertSheetOrder(wb, "Sheet1");
  464. Sheet sheet = wb.getSheetAt(0);
  465. sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false);
  466. Row newRow = sheet.getRow(2);
  467. if (newRow == null) {
  468. newRow = sheet.createRow(2);
  469. }
  470. newRow.createCell(0).setCellValue(" Another Header");
  471. wb.cloneSheet(0);
  472. assertSheetOrder(wb, "Sheet1", "Sheet1 (2)");
  473. // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx");
  474. // try {
  475. // wb.write(fileOut);
  476. // } finally {
  477. // fileOut.close();
  478. // }
  479. Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
  480. assertNotNull(read);
  481. assertSheetOrder(read, "Sheet1", "Sheet1 (2)");
  482. read.close();
  483. wb.close();
  484. }
  485. @Test
  486. public void bug47090a() throws IOException {
  487. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
  488. assertSheetOrder(workbook, "Sheet1", "Sheet2");
  489. workbook.removeSheetAt(0);
  490. assertSheetOrder(workbook, "Sheet2");
  491. workbook.createSheet();
  492. assertSheetOrder(workbook, "Sheet2", "Sheet1");
  493. Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  494. assertSheetOrder(read, "Sheet2", "Sheet1");
  495. read.close();
  496. workbook.close();
  497. }
  498. @Test
  499. public void bug47090b() throws IOException {
  500. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
  501. assertSheetOrder(workbook, "Sheet1", "Sheet2");
  502. workbook.removeSheetAt(1);
  503. assertSheetOrder(workbook, "Sheet1");
  504. workbook.createSheet();
  505. assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point!
  506. Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  507. assertSheetOrder(read, "Sheet1", "Sheet0");
  508. read.close();
  509. workbook.close();
  510. }
  511. @Test
  512. public void bug47090c() throws IOException {
  513. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
  514. assertSheetOrder(workbook, "Sheet1", "Sheet2");
  515. workbook.removeSheetAt(0);
  516. assertSheetOrder(workbook, "Sheet2");
  517. workbook.cloneSheet(0);
  518. assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)");
  519. Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  520. assertSheetOrder(read, "Sheet2", "Sheet2 (2)");
  521. read.close();
  522. workbook.close();
  523. }
  524. @Test
  525. public void bug47090d() throws IOException {
  526. Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
  527. assertSheetOrder(workbook, "Sheet1", "Sheet2");
  528. workbook.createSheet();
  529. assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0");
  530. workbook.removeSheetAt(0);
  531. assertSheetOrder(workbook, "Sheet2", "Sheet0");
  532. workbook.createSheet();
  533. assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1");
  534. Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
  535. assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1");
  536. read.close();
  537. workbook.close();
  538. }
  539. @Test
  540. public void bug51158() throws IOException {
  541. // create a workbook
  542. final XSSFWorkbook wb1 = new XSSFWorkbook();
  543. XSSFSheet sheet = wb1.createSheet("Test Sheet");
  544. XSSFRow row = sheet.createRow(2);
  545. XSSFCell cell = row.createCell(3);
  546. cell.setCellValue("test1");
  547. //XSSFCreationHelper helper = workbook.getCreationHelper();
  548. //cell.setHyperlink(helper.createHyperlink(0));
  549. XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor());
  550. assertNotNull(comment);
  551. comment.setString("some comment");
  552. // CellStyle cs = workbook.createCellStyle();
  553. // cs.setShrinkToFit(false);
  554. // row.createCell(0).setCellStyle(cs);
  555. // write the first excel file
  556. XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
  557. assertNotNull(wb2);
  558. sheet = wb2.getSheetAt(0);
  559. row = sheet.getRow(2);
  560. assertEquals("test1", row.getCell(3).getStringCellValue());
  561. assertNull(row.getCell(4));
  562. // add a new cell to the sheet
  563. cell = row.createCell(4);
  564. cell.setCellValue("test2");
  565. // write the second excel file
  566. XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
  567. assertNotNull(wb3);
  568. sheet = wb3.getSheetAt(0);
  569. row = sheet.getRow(2);
  570. assertEquals("test1", row.getCell(3).getStringCellValue());
  571. assertEquals("test2", row.getCell(4).getStringCellValue());
  572. wb3.close();
  573. wb2.close();
  574. wb1.close();
  575. }
  576. @Test
  577. public void bug51158a() throws IOException {
  578. // create a workbook
  579. try (XSSFWorkbook workbook = new XSSFWorkbook()) {
  580. workbook.createSheet("Test Sheet");
  581. XSSFSheet sheetBack = workbook.getSheetAt(0);
  582. // committing twice did add the XML twice without clearing the part in between
  583. sheetBack.commit();
  584. // ensure that a memory based package part does not have lingering data from previous commit() calls
  585. if (sheetBack.getPackagePart() instanceof MemoryPackagePart) {
  586. sheetBack.getPackagePart().clear();
  587. }
  588. sheetBack.commit();
  589. String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8");
  590. assertEquals(1, countMatches(str, "<worksheet"));
  591. }
  592. }
  593. @Test
  594. public void bug60509() throws Exception {
  595. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60509.xlsx");
  596. assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3");
  597. int sheetIndex = wb.getSheetIndex("Sheet1");
  598. wb.setSheetName(sheetIndex, "Sheet1-Renamed");
  599. Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
  600. assertNotNull(read);
  601. assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3");
  602. XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed");
  603. XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries().get(0);
  604. assertTrue("should be a bar chart data series", series instanceof XDDFBarChartData.Series);
  605. String formula = ((XDDFBarChartData.Series) series).getCategoryData().getFormula();
  606. assertTrue("should contain new sheet name", formula.startsWith("'Sheet1-Renamed'!"));
  607. read.close();
  608. wb.close();
  609. }
  610. private static final int INDEX_NOT_FOUND = -1;
  611. private static boolean isEmpty(CharSequence cs) {
  612. return cs == null || cs.length() == 0;
  613. }
  614. private static int countMatches(CharSequence str, CharSequence sub) {
  615. if (isEmpty(str) || isEmpty(sub)) {
  616. return 0;
  617. }
  618. int count = 0;
  619. int idx = 0;
  620. while ((idx = indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
  621. count++;
  622. idx += sub.length();
  623. }
  624. return count;
  625. }
  626. private static int indexOf(CharSequence cs, CharSequence searchChar, int start) {
  627. return cs.toString().indexOf(searchChar.toString(), start);
  628. }
  629. @Test
  630. public void testAddPivotCache() throws IOException {
  631. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  632. CTWorkbook ctWb = wb.getCTWorkbook();
  633. CTPivotCache pivotCache = wb.addPivotCache("0");
  634. //Ensures that pivotCaches is initiated
  635. assertTrue(ctWb.isSetPivotCaches());
  636. assertSame(pivotCache, ctWb.getPivotCaches().getPivotCacheArray(0));
  637. assertEquals("0", pivotCache.getId());
  638. }
  639. }
  640. protected void setPivotData(XSSFWorkbook wb){
  641. XSSFSheet sheet = wb.createSheet();
  642. Row row1 = sheet.createRow(0);
  643. // Create a cell and put a value in it.
  644. Cell cell = row1.createCell(0);
  645. cell.setCellValue("Names");
  646. Cell cell2 = row1.createCell(1);
  647. cell2.setCellValue("#");
  648. Cell cell7 = row1.createCell(2);
  649. cell7.setCellValue("Data");
  650. Row row2 = sheet.createRow(1);
  651. Cell cell3 = row2.createCell(0);
  652. cell3.setCellValue("Jan");
  653. Cell cell4 = row2.createCell(1);
  654. cell4.setCellValue(10);
  655. Cell cell8 = row2.createCell(2);
  656. cell8.setCellValue("Apa");
  657. Row row3 = sheet.createRow(2);
  658. Cell cell5 = row3.createCell(0);
  659. cell5.setCellValue("Ben");
  660. Cell cell6 = row3.createCell(1);
  661. cell6.setCellValue(9);
  662. Cell cell9 = row3.createCell(2);
  663. cell9.setCellValue("Bepa");
  664. AreaReference source = wb.getCreationHelper().createAreaReference("A1:B2");
  665. sheet.createPivotTable(source, new CellReference("H5"));
  666. }
  667. @Test
  668. public void testLoadWorkbookWithPivotTable() throws Exception {
  669. File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
  670. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  671. setPivotData(wb);
  672. FileOutputStream fileOut = new FileOutputStream(file);
  673. wb.write(fileOut);
  674. fileOut.close();
  675. }
  676. try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
  677. assertTrue(wb2.getPivotTables().size() == 1);
  678. }
  679. assertTrue(file.delete());
  680. }
  681. @Test
  682. public void testAddPivotTableToWorkbookWithLoadedPivotTable() throws Exception {
  683. File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx");
  684. try (XSSFWorkbook wb = new XSSFWorkbook()) {
  685. setPivotData(wb);
  686. try (FileOutputStream fileOut = new FileOutputStream(file)) {
  687. wb.write(fileOut);
  688. }
  689. }
  690. try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) {
  691. setPivotData(wb2);
  692. assertTrue(wb2.getPivotTables().size() == 2);
  693. }
  694. assertTrue(file.delete());
  695. }
  696. @Test
  697. public void testSetFirstVisibleTab_57373() throws IOException {
  698. try (Workbook wb = new XSSFWorkbook()) {
  699. /*Sheet sheet1 =*/
  700. wb.createSheet();
  701. Sheet sheet2 = wb.createSheet();
  702. int idx2 = wb.getSheetIndex(sheet2);
  703. Sheet sheet3 = wb.createSheet();
  704. int idx3 = wb.getSheetIndex(sheet3);
  705. // add many sheets so "first visible" is relevant
  706. for (int i = 0; i < 30; i++) {
  707. wb.createSheet();
  708. }
  709. wb.setFirstVisibleTab(idx2);
  710. wb.setActiveSheet(idx3);
  711. //wb.write(new FileOutputStream(new File("C:\\temp\\test.xlsx")));
  712. assertEquals(idx2, wb.getFirstVisibleTab());
  713. assertEquals(idx3, wb.getActiveSheetIndex());
  714. Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
  715. sheet2 = wbBack.getSheetAt(idx2);
  716. assertNotNull(sheet2);
  717. sheet3 = wbBack.getSheetAt(idx3);
  718. assertNotNull(sheet3);
  719. assertEquals(idx2, wb.getFirstVisibleTab());
  720. assertEquals(idx3, wb.getActiveSheetIndex());
  721. wbBack.close();
  722. }
  723. }
  724. /**
  725. * Tests that we can save a workbook with macros and reload it.
  726. */
  727. @Test
  728. public void testSetVBAProject() throws Exception {
  729. File file;
  730. final byte[] allBytes = new byte[256];
  731. for (int i = 0; i < 256; i++) {
  732. allBytes[i] = (byte) (i - 128);
  733. }
  734. XSSFWorkbook wb1 = new XSSFWorkbook();
  735. wb1.createSheet();
  736. wb1.setVBAProject(new ByteArrayInputStream(allBytes));
  737. file = TempFile.createTempFile("poi-", ".xlsm");
  738. OutputStream out = new FileOutputStream(file);
  739. wb1.write(out);
  740. out.close();
  741. wb1.close();
  742. // Check the package contains what we'd expect it to
  743. OPCPackage pkg = OPCPackage.open(file.toString());
  744. PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
  745. assertTrue(wbPart.hasRelationships());
  746. final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation());
  747. assertEquals(1, relationships.size());
  748. assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationships.getRelationship(0).getTargetURI().toString());
  749. PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName()));
  750. assertNotNull(vbaPart);
  751. assertFalse(vbaPart.isRelationshipPart());
  752. assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType());
  753. final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream());
  754. assertArrayEquals(allBytes, fromFile);
  755. // Load back the XSSFWorkbook just to check nothing explodes
  756. @SuppressWarnings("resource")
  757. XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
  758. assertEquals(1, wb2.getNumberOfSheets());
  759. assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType());
  760. pkg.close();
  761. }
  762. @Test
  763. public void testBug54399() throws IOException {
  764. XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54399.xlsx");
  765. for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
  766. workbook.setSheetName(i, "SheetRenamed" + (i + 1));
  767. }
  768. workbook.close();
  769. }
  770. /**
  771. * Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30
  772. * and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator
  773. *
  774. * In order to make code for looping over sheets in workbooks standard, regardless
  775. * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously
  776. * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator
  777. * have been replaced with Iterator<Sheet> {@link Sheet#iterator} and
  778. * Iterator<Sheet> {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook
  779. * similar to iterating over rows in a sheet and cells in a row.
  780. *
  781. * Note: this breaks backwards compatibility! Existing codebases will need to
  782. * upgrade their code with either of the following options presented in this test case.
  783. *
  784. */
  785. @SuppressWarnings("unchecked")
  786. @Test
  787. public void bug58245_XSSFSheetIterator() throws IOException {
  788. final XSSFWorkbook wb = new XSSFWorkbook();
  789. wb.createSheet();
  790. // =====================================================================
  791. // Case 1: Existing code uses XSSFSheet for-each loop
  792. // =====================================================================
  793. // Original code (no longer valid)
  794. /*
  795. for (XSSFSheet sh : wb) {
  796. sh.createRow(0);
  797. }
  798. */
  799. // Option A:
  800. for (XSSFSheet sh : (Iterable<XSSFSheet>) (Iterable<? extends Sheet>) wb) {
  801. sh.createRow(0);
  802. }
  803. // Option B (preferred for new code):
  804. for (Sheet sh : wb) {
  805. sh.createRow(0);
  806. }
  807. // =====================================================================
  808. // Case 2: Existing code creates an iterator variable
  809. // =====================================================================
  810. // Original code (no longer valid)
  811. /*
  812. Iterator<XSSFSheet> it = wb.iterator();
  813. XSSFSheet sh = it.next();
  814. sh.createRow(0);
  815. */
  816. // Option A:
  817. {
  818. Iterator<XSSFSheet> it = (Iterator<XSSFSheet>) (Iterator<? extends Sheet>) wb.iterator();
  819. XSSFSheet sh = it.next();
  820. sh.createRow(0);
  821. }
  822. // Option B (preferred for new code):
  823. {
  824. Iterator<Sheet> it = wb.iterator();
  825. Sheet sh = it.next();
  826. sh.createRow(0);
  827. }
  828. wb.close();
  829. }
  830. @Test
  831. public void testBug56957CloseWorkbook() throws Exception {
  832. File file = TempFile.createTempFile("TestBug56957_", ".xlsx");
  833. final Date dateExp = LocaleUtil.getLocaleCalendar(2014, 10, 9).getTime();
  834. try {
  835. // as the file is written to, we make a copy before actually working on it
  836. FileHelper.copyFile(HSSFTestDataSamples.getSampleFile("56957.xlsx"), file);
  837. assertTrue(file.exists());
  838. // read-only mode works!
  839. Workbook workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ));
  840. Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue();
  841. assertEquals(dateExp, dateAct);
  842. workbook.close();
  843. workbook = null;
  844. workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ));
  845. dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue();
  846. assertEquals(dateExp, dateAct);
  847. workbook.close();
  848. workbook = null;
  849. // now check read/write mode
  850. workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE));
  851. dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue();
  852. assertEquals(dateExp, dateAct);
  853. workbook.close();
  854. workbook = null;
  855. workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE));
  856. dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue();
  857. assertEquals(dateExp, dateAct);
  858. workbook.close();
  859. workbook = null;
  860. } finally {
  861. assertTrue(file.exists());
  862. assertTrue(file.delete());
  863. }
  864. }
  865. @Test
  866. public void closeDoesNotModifyWorkbook() throws IOException, InvalidFormatException {
  867. final String filename = "SampleSS.xlsx";
  868. final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename);
  869. Workbook wb;
  870. // Some tests commented out because close() modifies the file
  871. // See bug 58779
  872. // String
  873. //wb = new XSSFWorkbook(file.getPath());
  874. //assertCloseDoesNotModifyFile(filename, wb);
  875. // File
  876. //wb = new XSSFWorkbook(file);
  877. //assertCloseDoesNotModifyFile(filename, wb);
  878. // InputStream
  879. wb = new XSSFWorkbook(new FileInputStream(file));
  880. assertCloseDoesNotModifyFile(filename, wb);
  881. // OPCPackage
  882. //wb = new XSSFWorkbook(OPCPackage.open(file));
  883. //assertCloseDoesNotModifyFile(filename, wb);
  884. }
  885. @Test
  886. public void testCloseBeforeWrite() throws IOException {
  887. Workbook wb = new XSSFWorkbook();
  888. wb.createSheet("somesheet");
  889. // test what happens if we close the Workbook before we write it out
  890. wb.close();
  891. try {
  892. XSSFTestDataSamples.writeOutAndReadBack(wb);
  893. fail("Expecting IOException here");
  894. } catch (RuntimeException e) {
  895. // expected here
  896. assertTrue("Had: " + e.getCause(), e.getCause() instanceof IOException);
  897. }
  898. }
  899. /**
  900. * See bug #57840 test data tables
  901. */
  902. @Test
  903. public void getTable() throws IOException {
  904. XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx");
  905. XSSFTable table1 = wb.getTable("Tabella1");
  906. assertNotNull("Tabella1 was not found in workbook", table1);
  907. assertEquals("Table name", "Tabella1", table1.getName());
  908. assertEquals("Sheet name", "Foglio1", table1.getSheetName());
  909. // Table lookup should be case-insensitive
  910. assertSame("Case insensitive table name lookup", table1, wb.getTable("TABELLA1"));
  911. // If workbook does not contain any data tables matching the provided name, getTable should return null
  912. assertNull("Null table name should not throw NPE", wb.getTable(null));
  913. assertNull("Should not be able to find non-existent table", wb.getTable("Foglio1"));
  914. // If a table is added after getTable is called it should still be reachable by XSSFWorkbook.getTable
  915. // This test makes sure that if any caching is done that getTable never uses a stale cache
  916. XSSFTable table2 = wb.getSheet("Foglio2").createTable();
  917. table2.setName("Table2");
  918. assertSame("Did not find Table2", table2, wb.getTable("Table2"));
  919. // If table name is modified after getTable is called, the table can only be found by its new name
  920. // This test makes sure that if any caching is done that getTable never uses a stale cache
  921. table1.setName("Table1");
  922. assertSame("Did not find Tabella1 renamed to Table1", table1, wb.getTable("TABLE1"));
  923. wb.close();
  924. }
  925. @SuppressWarnings("deprecation")
  926. @Test
  927. public void testRemoveSheet() throws IOException {
  928. // Test removing a sheet maintains the named ranges correctly
  929. XSSFWorkbook wb = new XSSFWorkbook();
  930. wb.createSheet("Sheet1");
  931. wb.createSheet("Sheet2");
  932. XSSFName sheet1Name = wb.createName();
  933. sheet1Name.setNameName("name1");
  934. sheet1Name.setSheetIndex(0);
  935. sheet1Name.setRefersToFormula("Sheet1!$A$1");
  936. XSSFName sheet2Name = wb.createName();
  937. sheet2Name.setNameName("name1");
  938. sheet2Name.setSheetIndex(1);
  939. sheet2Name.setRefersToFormula("Sheet2!$A$1");
  940. assertTrue(wb.getAllNames().contains(sheet1Name));
  941. assertTrue(wb.getAllNames().contains(sheet2Name));
  942. assertEquals(2, wb.getNames("name1").size());
  943. assertEquals(sheet1Name, wb.getNames("name1").get(0));
  944. assertEquals(sheet2Name, wb.getNames("name1").get(1));
  945. // Remove sheet1, we should only have sheet2Name now
  946. wb.removeSheetAt(0);
  947. assertFalse(wb.getAllNames().contains(sheet1Name));
  948. assertTrue(wb.getAllNames().contains(sheet2Name));
  949. assertEquals(1, wb.getNames("name1").size());
  950. assertEquals(sheet2Name, wb.getNames("name1").get(0));
  951. // Check by index as well for sanity
  952. assertEquals(1, wb.getNumberOfNames());
  953. assertEquals(0, wb.getNameIndex("name1"));
  954. assertEquals(sheet2Name, wb.getNameAt(0));
  955. wb.close();
  956. }
  957. }