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

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