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

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