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.

SXSSFWorkbook.java 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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.streaming;
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.InputStreamReader;
  21. import java.io.OutputStream;
  22. import java.io.OutputStreamWriter;
  23. import java.nio.charset.StandardCharsets;
  24. import java.util.Enumeration;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.NoSuchElementException;
  30. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  31. import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
  32. import org.apache.poi.openxml4j.opc.OPCPackage;
  33. import org.apache.poi.openxml4j.util.ZipArchiveThresholdInputStream;
  34. import org.apache.poi.openxml4j.util.ZipEntrySource;
  35. import org.apache.poi.openxml4j.util.ZipFileZipEntrySource;
  36. import org.apache.poi.openxml4j.util.ZipSecureFile;
  37. import org.apache.poi.ss.SpreadsheetVersion;
  38. import org.apache.poi.ss.formula.udf.UDFFinder;
  39. import org.apache.poi.ss.usermodel.CellStyle;
  40. import org.apache.poi.ss.usermodel.CreationHelper;
  41. import org.apache.poi.ss.usermodel.DataFormat;
  42. import org.apache.poi.ss.usermodel.Font;
  43. import org.apache.poi.ss.usermodel.Name;
  44. import org.apache.poi.ss.usermodel.PictureData;
  45. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  46. import org.apache.poi.ss.usermodel.Sheet;
  47. import org.apache.poi.ss.usermodel.SheetVisibility;
  48. import org.apache.poi.ss.usermodel.Workbook;
  49. import org.apache.poi.util.IOUtils;
  50. import org.apache.poi.util.Internal;
  51. import org.apache.poi.util.NotImplemented;
  52. import org.apache.poi.util.POILogFactory;
  53. import org.apache.poi.util.POILogger;
  54. import org.apache.poi.util.Removal;
  55. import org.apache.poi.util.TempFile;
  56. import org.apache.poi.xssf.model.SharedStringsTable;
  57. import org.apache.poi.xssf.usermodel.XSSFChartSheet;
  58. import org.apache.poi.xssf.usermodel.XSSFSheet;
  59. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  60. /**
  61. * Streaming version of XSSFWorkbook implementing the "BigGridDemo" strategy.
  62. *
  63. * This allows to write very large files without running out of memory as only
  64. * a configurable portion of the rows are kept in memory at any one time.
  65. *
  66. * You can provide a template workbook which is used as basis for the written
  67. * data.
  68. *
  69. * See https://poi.apache.org/spreadsheet/how-to.html#sxssf for details.
  70. *
  71. * Please note that there are still things that still may consume a large
  72. * amount of memory based on which features you are using, e.g. merged regions,
  73. * comments, ... are still only stored in memory and thus may require a lot of
  74. * memory if used extensively.
  75. *
  76. * SXSSFWorkbook defaults to using inline strings instead of a shared strings
  77. * table. This is very efficient, since no document content needs to be kept in
  78. * memory, but is also known to produce documents that are incompatible with
  79. * some clients. With shared strings enabled all unique strings in the document
  80. * has to be kept in memory. Depending on your document content this could use
  81. * a lot more resources than with shared strings disabled.
  82. *
  83. * Carefully review your memory budget and compatibility needs before deciding
  84. * whether to enable shared strings or not.
  85. */
  86. public class SXSSFWorkbook implements Workbook {
  87. /**
  88. * Specifies how many rows can be accessed at most via {@link SXSSFSheet#getRow}.
  89. * When a new node is created via {@link SXSSFSheet#createRow} and the total number
  90. * of unflushed records would exceed the specified value, then the
  91. * row with the lowest index value is flushed and cannot be accessed
  92. * via {@link SXSSFSheet#getRow} anymore.
  93. */
  94. public static final int DEFAULT_WINDOW_SIZE = 100;
  95. private static final POILogger logger = POILogFactory.getLogger(SXSSFWorkbook.class);
  96. private final XSSFWorkbook _wb;
  97. private final Map<SXSSFSheet,XSSFSheet> _sxFromXHash = new HashMap<>();
  98. private final Map<XSSFSheet,SXSSFSheet> _xFromSxHash = new HashMap<>();
  99. private int _randomAccessWindowSize = DEFAULT_WINDOW_SIZE;
  100. /**
  101. * whether temp files should be compressed.
  102. */
  103. private boolean _compressTmpFiles;
  104. /**
  105. * shared string table - a cache of strings in this workbook
  106. */
  107. private final SharedStringsTable _sharedStringSource;
  108. /**
  109. * Construct a new workbook with default row window size
  110. */
  111. public SXSSFWorkbook(){
  112. this(null /*workbook*/);
  113. }
  114. /**
  115. * <p>Construct a workbook from a template.</p>
  116. *
  117. * There are three use-cases to use SXSSFWorkbook(XSSFWorkbook) :
  118. * <ol>
  119. * <li>
  120. * Append new sheets to existing workbooks. You can open existing
  121. * workbook from a file or create on the fly with XSSF.
  122. * </li>
  123. * <li>
  124. * Append rows to existing sheets. The row number MUST be greater
  125. * than {@code max(rownum)} in the template sheet.
  126. * </li>
  127. * <li>
  128. * Use existing workbook as a template and re-use global objects such
  129. * as cell styles, formats, images, etc.
  130. * </li>
  131. * </ol>
  132. * All three use cases can work in a combination.
  133. *
  134. * What is not supported:
  135. * <ul>
  136. * <li>
  137. * Access initial cells and rows in the template. After constructing
  138. * all internal windows are empty and {@link SXSSFSheet#getRow} and
  139. * {@link SXSSFRow#getCell} return <code>null</code>.
  140. * </li>
  141. * <li>
  142. * Override existing cells and rows. The API silently allows that but
  143. * the output file is invalid and Excel cannot read it.
  144. * </li>
  145. * </ul>
  146. *
  147. * @param workbook the template workbook
  148. */
  149. public SXSSFWorkbook(XSSFWorkbook workbook){
  150. this(workbook, DEFAULT_WINDOW_SIZE);
  151. }
  152. /**
  153. * Constructs an workbook from an existing workbook.
  154. * <p>
  155. * When a new node is created via {@link SXSSFSheet#createRow} and the total number
  156. * of unflushed records would exceed the specified value, then the
  157. * row with the lowest index value is flushed and cannot be accessed
  158. * via {@link SXSSFSheet#getRow} anymore.
  159. * </p>
  160. * <p>
  161. * A value of <code>-1</code> indicates unlimited access. In this case all
  162. * records that have not been flushed by a call to <code>flush()</code> are available
  163. * for random access.
  164. * </p>
  165. * <p>
  166. * A value of <code>0</code> is not allowed because it would flush any newly created row
  167. * without having a chance to specify any cells.
  168. * </p>
  169. *
  170. * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above.
  171. */
  172. public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize){
  173. this(workbook,rowAccessWindowSize, false);
  174. }
  175. /**
  176. * Constructs an workbook from an existing workbook.
  177. * <p>
  178. * When a new node is created via {@link SXSSFSheet#createRow} and the total number
  179. * of unflushed records would exceed the specified value, then the
  180. * row with the lowest index value is flushed and cannot be accessed
  181. * via {@link SXSSFSheet#getRow} anymore.
  182. * </p>
  183. * <p>
  184. * A value of <code>-1</code> indicates unlimited access. In this case all
  185. * records that have not been flushed by a call to <code>flush()</code> are available
  186. * for random access.
  187. * </p>
  188. * <p>
  189. * A value of <code>0</code> is not allowed because it would flush any newly created row
  190. * without having a chance to specify any cells.
  191. * </p>
  192. *
  193. * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above.
  194. * @param compressTmpFiles whether to use gzip compression for temporary files
  195. */
  196. public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles){
  197. this(workbook,rowAccessWindowSize, compressTmpFiles, false);
  198. }
  199. /**
  200. * Constructs an workbook from an existing workbook.
  201. * <p>
  202. * When a new node is created via {@link SXSSFSheet#createRow} and the total number
  203. * of unflushed records would exceed the specified value, then the
  204. * row with the lowest index value is flushed and cannot be accessed
  205. * via {@link SXSSFSheet#getRow} anymore.
  206. * </p>
  207. * <p>
  208. * A value of <code>-1</code> indicates unlimited access. In this case all
  209. * records that have not been flushed by a call to <code>flush()</code> are available
  210. * for random access.
  211. * </p>
  212. * <p>
  213. * A value of <code>0</code> is not allowed because it would flush any newly created row
  214. * without having a chance to specify any cells.
  215. * </p>
  216. *
  217. * @param workbook the template workbook
  218. * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above.
  219. * @param compressTmpFiles whether to use gzip compression for temporary files
  220. * @param useSharedStringsTable whether to use a shared strings table
  221. */
  222. public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable){
  223. setRandomAccessWindowSize(rowAccessWindowSize);
  224. setCompressTempFiles(compressTmpFiles);
  225. if (workbook == null) {
  226. _wb=new XSSFWorkbook();
  227. _sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null;
  228. } else {
  229. _wb=workbook;
  230. _sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null;
  231. for ( Sheet sheet : _wb ) {
  232. createAndRegisterSXSSFSheet( (XSSFSheet)sheet );
  233. }
  234. }
  235. }
  236. /**
  237. * Construct an empty workbook and specify the window for row access.
  238. * <p>
  239. * When a new node is created via {@link SXSSFSheet#createRow} and the total number
  240. * of unflushed records would exceed the specified value, then the
  241. * row with the lowest index value is flushed and cannot be accessed
  242. * via {@link SXSSFSheet#getRow} anymore.
  243. * </p>
  244. * <p>
  245. * A value of <code>-1</code> indicates unlimited access. In this case all
  246. * records that have not been flushed by a call to <code>flush()</code> are available
  247. * for random access.
  248. * </p>
  249. * <p>
  250. * A value of <code>0</code> is not allowed because it would flush any newly created row
  251. * without having a chance to specify any cells.
  252. * </p>
  253. *
  254. * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above.
  255. */
  256. public SXSSFWorkbook(int rowAccessWindowSize){
  257. this(null /*workbook*/, rowAccessWindowSize);
  258. }
  259. /**
  260. * See the constructors for a more detailed description of the sliding window of rows.
  261. *
  262. * @return The number of rows that are kept in memory at once before flushing them out.
  263. */
  264. public int getRandomAccessWindowSize() {
  265. return _randomAccessWindowSize;
  266. }
  267. private void setRandomAccessWindowSize(int rowAccessWindowSize) {
  268. if(rowAccessWindowSize == 0 || rowAccessWindowSize < -1) {
  269. throw new IllegalArgumentException("rowAccessWindowSize must be greater than 0 or -1");
  270. }
  271. _randomAccessWindowSize = rowAccessWindowSize;
  272. }
  273. /**
  274. * Get whether temp files should be compressed.
  275. *
  276. * @return whether to compress temp files
  277. */
  278. public boolean isCompressTempFiles() {
  279. return _compressTmpFiles;
  280. }
  281. /**
  282. * Set whether temp files should be compressed.
  283. * <p>
  284. * SXSSF writes sheet data in temporary files (a temp file per-sheet)
  285. * and the size of these temp files can grow to to a very large size,
  286. * e.g. for a 20 MB csv data the size of the temp xml file become few GB large.
  287. * If the "compress" flag is set to <code>true</code> then the temporary XML is gzipped.
  288. * </p>
  289. * <p>
  290. * Please note the the "compress" option may cause performance penalty.
  291. * </p>
  292. * <p>
  293. * Setting this option only affects compression for subsequent <code>createSheet()</code>
  294. * calls.
  295. * </p>
  296. * @param compress whether to compress temp files
  297. */
  298. public void setCompressTempFiles(boolean compress) {
  299. _compressTmpFiles = compress;
  300. }
  301. @Internal
  302. protected SharedStringsTable getSharedStringSource() {
  303. return _sharedStringSource;
  304. }
  305. protected SheetDataWriter createSheetDataWriter() throws IOException {
  306. if(_compressTmpFiles) {
  307. return new GZIPSheetDataWriter(_sharedStringSource);
  308. }
  309. return new SheetDataWriter(_sharedStringSource);
  310. }
  311. XSSFSheet getXSSFSheet(SXSSFSheet sheet)
  312. {
  313. return _sxFromXHash.get(sheet);
  314. }
  315. SXSSFSheet getSXSSFSheet(XSSFSheet sheet)
  316. {
  317. return _xFromSxHash.get(sheet);
  318. }
  319. void registerSheetMapping(SXSSFSheet sxSheet,XSSFSheet xSheet)
  320. {
  321. _sxFromXHash.put(sxSheet,xSheet);
  322. _xFromSxHash.put(xSheet,sxSheet);
  323. }
  324. void deregisterSheetMapping(XSSFSheet xSheet)
  325. {
  326. SXSSFSheet sxSheet=getSXSSFSheet(xSheet);
  327. // ensure that the writer is closed in all cases to not have lingering writers
  328. try {
  329. sxSheet.getSheetDataWriter().close();
  330. } catch (IOException e) {
  331. // ignore exception here
  332. }
  333. _sxFromXHash.remove(sxSheet);
  334. _xFromSxHash.remove(xSheet);
  335. }
  336. private XSSFSheet getSheetFromZipEntryName(String sheetRef)
  337. {
  338. for(XSSFSheet sheet : _sxFromXHash.values())
  339. {
  340. if(sheetRef.equals(sheet.getPackagePart().getPartName().getName().substring(1))) {
  341. return sheet;
  342. }
  343. }
  344. return null;
  345. }
  346. protected void injectData(ZipEntrySource zipEntrySource, OutputStream out) throws IOException {
  347. ZipArchiveOutputStream zos = new ZipArchiveOutputStream(out);
  348. try {
  349. Enumeration<? extends ZipArchiveEntry> en = zipEntrySource.getEntries();
  350. while (en.hasMoreElements()) {
  351. ZipArchiveEntry ze = en.nextElement();
  352. zos.putArchiveEntry(new ZipArchiveEntry(ze.getName()));
  353. try (final InputStream is = zipEntrySource.getInputStream(ze)) {
  354. if (is instanceof ZipArchiveThresholdInputStream) {
  355. // #59743 - disable Threshold handling for SXSSF copy
  356. // as users tend to put too much repetitive data in when using SXSSF :)
  357. ((ZipArchiveThresholdInputStream)is).setGuardState(false);
  358. }
  359. XSSFSheet xSheet = getSheetFromZipEntryName(ze.getName());
  360. // See bug 56557, we should not inject data into the special ChartSheets
  361. if (xSheet != null && !(xSheet instanceof XSSFChartSheet)) {
  362. SXSSFSheet sxSheet = getSXSSFSheet(xSheet);
  363. try (InputStream xis = sxSheet.getWorksheetXMLInputStream()) {
  364. copyStreamAndInjectWorksheet(is, zos, xis);
  365. }
  366. } else {
  367. IOUtils.copy(is, zos);
  368. }
  369. } finally {
  370. zos.closeArchiveEntry();
  371. }
  372. }
  373. } finally {
  374. zos.finish();
  375. zipEntrySource.close();
  376. }
  377. }
  378. private static void copyStreamAndInjectWorksheet(InputStream in, OutputStream out, InputStream worksheetData) throws IOException {
  379. InputStreamReader inReader = new InputStreamReader(in, StandardCharsets.UTF_8);
  380. OutputStreamWriter outWriter = new OutputStreamWriter(out, StandardCharsets.UTF_8);
  381. boolean needsStartTag = true;
  382. int c;
  383. int pos=0;
  384. String s="<sheetData";
  385. int n=s.length();
  386. //Copy from "in" to "out" up to the string "<sheetData/>" or "</sheetData>" (excluding).
  387. while(((c=inReader.read())!=-1))
  388. {
  389. if(c==s.charAt(pos))
  390. {
  391. pos++;
  392. if(pos==n)
  393. {
  394. if ("<sheetData".equals(s))
  395. {
  396. c = inReader.read();
  397. if (c == -1)
  398. {
  399. outWriter.write(s);
  400. break;
  401. }
  402. if (c == '>')
  403. {
  404. // Found <sheetData>
  405. outWriter.write(s);
  406. outWriter.write(c);
  407. s = "</sheetData>";
  408. n = s.length();
  409. pos = 0;
  410. needsStartTag = false;
  411. continue;
  412. }
  413. if (c == '/')
  414. {
  415. // Found <sheetData/
  416. c = inReader.read();
  417. if (c == -1)
  418. {
  419. outWriter.write(s);
  420. break;
  421. }
  422. if (c == '>')
  423. {
  424. // Found <sheetData/>
  425. break;
  426. }
  427. outWriter.write(s);
  428. outWriter.write('/');
  429. outWriter.write(c);
  430. pos = 0;
  431. continue;
  432. }
  433. outWriter.write(s);
  434. outWriter.write('/');
  435. outWriter.write(c);
  436. pos = 0;
  437. continue;
  438. }
  439. else
  440. {
  441. // Found </sheetData>
  442. break;
  443. }
  444. }
  445. }
  446. else
  447. {
  448. if(pos>0) {
  449. outWriter.write(s,0,pos);
  450. }
  451. if(c==s.charAt(0))
  452. {
  453. pos=1;
  454. }
  455. else
  456. {
  457. outWriter.write(c);
  458. pos=0;
  459. }
  460. }
  461. }
  462. outWriter.flush();
  463. if (needsStartTag)
  464. {
  465. outWriter.write("<sheetData>\n");
  466. outWriter.flush();
  467. }
  468. //Copy the worksheet data to "out".
  469. IOUtils.copy(worksheetData,out);
  470. outWriter.write("</sheetData>");
  471. outWriter.flush();
  472. //Copy the rest of "in" to "out".
  473. while(((c=inReader.read())!=-1)) {
  474. outWriter.write(c);
  475. }
  476. outWriter.flush();
  477. }
  478. public XSSFWorkbook getXSSFWorkbook()
  479. {
  480. return _wb;
  481. }
  482. //start of interface implementation
  483. /**
  484. * Convenience method to get the active sheet. The active sheet is is the sheet
  485. * which is currently displayed when the workbook is viewed in Excel.
  486. * 'Selected' sheet(s) is a distinct concept.
  487. *
  488. * @return the index of the active sheet (0-based)
  489. */
  490. @Override
  491. public int getActiveSheetIndex()
  492. {
  493. return _wb.getActiveSheetIndex();
  494. }
  495. /**
  496. * Convenience method to set the active sheet. The active sheet is is the sheet
  497. * which is currently displayed when the workbook is viewed in Excel.
  498. * 'Selected' sheet(s) is a distinct concept.
  499. *
  500. * @param sheetIndex index of the active sheet (0-based)
  501. */
  502. @Override
  503. public void setActiveSheet(int sheetIndex)
  504. {
  505. _wb.setActiveSheet(sheetIndex);
  506. }
  507. /**
  508. * Gets the first tab that is displayed in the list of tabs in excel.
  509. *
  510. * @return the first tab that to display in the list of tabs (0-based).
  511. */
  512. @Override
  513. public int getFirstVisibleTab()
  514. {
  515. return _wb.getFirstVisibleTab();
  516. }
  517. /**
  518. * Sets the first tab that is displayed in the list of tabs in excel.
  519. *
  520. * @param sheetIndex the first tab that to display in the list of tabs (0-based)
  521. */
  522. @Override
  523. public void setFirstVisibleTab(int sheetIndex)
  524. {
  525. _wb.setFirstVisibleTab(sheetIndex);
  526. }
  527. /**
  528. * Sets the order of appearance for a given sheet.
  529. *
  530. * @param sheetname the name of the sheet to reorder
  531. * @param pos the position that we want to insert the sheet into (0 based)
  532. */
  533. @Override
  534. public void setSheetOrder(String sheetname, int pos)
  535. {
  536. _wb.setSheetOrder(sheetname,pos);
  537. }
  538. /**
  539. * Sets the tab whose data is actually seen when the sheet is opened.
  540. * This may be different from the "selected sheet" since excel seems to
  541. * allow you to show the data of one sheet when another is seen "selected"
  542. * in the tabs (at the bottom).
  543. *
  544. * @see Sheet#setSelected(boolean)
  545. * @param index the index of the sheet to select (0 based)
  546. */
  547. @Override
  548. public void setSelectedTab(int index)
  549. {
  550. _wb.setSelectedTab(index);
  551. }
  552. /**
  553. * Set the sheet name.
  554. *
  555. * @param sheet number (0 based)
  556. * @throws IllegalArgumentException if the name is greater than 31 chars or contains <code>/\?*[]</code>
  557. */
  558. @Override
  559. public void setSheetName(int sheet, String name)
  560. {
  561. _wb.setSheetName(sheet,name);
  562. }
  563. /**
  564. * Set the sheet name
  565. *
  566. * @param sheet sheet number (0 based)
  567. * @return Sheet name
  568. */
  569. @Override
  570. public String getSheetName(int sheet)
  571. {
  572. return _wb.getSheetName(sheet);
  573. }
  574. /**
  575. * Returns the index of the sheet by his name
  576. *
  577. * @param name the sheet name
  578. * @return index of the sheet (0 based)
  579. */
  580. @Override
  581. public int getSheetIndex(String name)
  582. {
  583. return _wb.getSheetIndex(name);
  584. }
  585. /**
  586. * Returns the index of the given sheet
  587. *
  588. * @param sheet the sheet to look up
  589. * @return index of the sheet (0 based)
  590. */
  591. @Override
  592. public int getSheetIndex(Sheet sheet)
  593. {
  594. return _wb.getSheetIndex(getXSSFSheet((SXSSFSheet)sheet));
  595. }
  596. /**
  597. * Sreate an Sheet for this Workbook, adds it to the sheets and returns
  598. * the high level representation. Use this to create new sheets.
  599. *
  600. * @return Sheet representing the new sheet.
  601. */
  602. @Override
  603. public SXSSFSheet createSheet()
  604. {
  605. return createAndRegisterSXSSFSheet(_wb.createSheet());
  606. }
  607. SXSSFSheet createAndRegisterSXSSFSheet(XSSFSheet xSheet)
  608. {
  609. final SXSSFSheet sxSheet;
  610. try
  611. {
  612. sxSheet=new SXSSFSheet(this,xSheet);
  613. }
  614. catch (IOException ioe)
  615. {
  616. throw new RuntimeException(ioe);
  617. }
  618. registerSheetMapping(sxSheet,xSheet);
  619. return sxSheet;
  620. }
  621. /**
  622. * Create an Sheet for this Workbook, adds it to the sheets and returns
  623. * the high level representation. Use this to create new sheets.
  624. *
  625. * @param sheetname sheetname to set for the sheet.
  626. * @return Sheet representing the new sheet.
  627. * @throws IllegalArgumentException if the name is greater than 31 chars or contains <code>/\?*[]</code>
  628. */
  629. @Override
  630. public SXSSFSheet createSheet(String sheetname)
  631. {
  632. return createAndRegisterSXSSFSheet(_wb.createSheet(sheetname));
  633. }
  634. /**
  635. * <i>Not implemented for SXSSFWorkbook</i>
  636. *
  637. * Create an Sheet from an existing sheet in the Workbook.
  638. *
  639. * @return Sheet representing the cloned sheet.
  640. */
  641. @Override
  642. @NotImplemented
  643. public Sheet cloneSheet(int sheetNum) {
  644. throw new RuntimeException("Not Implemented");
  645. }
  646. /**
  647. * Get the number of spreadsheets in the workbook
  648. *
  649. * @return the number of sheets
  650. */
  651. @Override
  652. public int getNumberOfSheets()
  653. {
  654. return _wb.getNumberOfSheets();
  655. }
  656. /**
  657. * Returns an iterator of the sheets in the workbook
  658. * in sheet order. Includes hidden and very hidden sheets.
  659. *
  660. * @return an iterator of the sheets.
  661. */
  662. @Override
  663. public Iterator<Sheet> sheetIterator() {
  664. return new SheetIterator<>();
  665. }
  666. private final class SheetIterator<T extends Sheet> implements Iterator<T> {
  667. final private Iterator<XSSFSheet> it;
  668. @SuppressWarnings("unchecked")
  669. public SheetIterator() {
  670. it = (Iterator<XSSFSheet>)(Iterator<? extends Sheet>) _wb.iterator();
  671. }
  672. @Override
  673. public boolean hasNext() {
  674. return it.hasNext();
  675. }
  676. @Override
  677. @SuppressWarnings("unchecked")
  678. public T next() throws NoSuchElementException {
  679. final XSSFSheet xssfSheet = it.next();
  680. return (T) getSXSSFSheet(xssfSheet);
  681. }
  682. /**
  683. * Unexpected behavior may occur if sheets are reordered after iterator
  684. * has been created. Support for the remove method may be added in the future
  685. * if someone can figure out a reliable implementation.
  686. */
  687. @Override
  688. public void remove() throws IllegalStateException {
  689. throw new UnsupportedOperationException("remove method not supported on XSSFWorkbook.iterator(). "+
  690. "Use Sheet.removeSheetAt(int) instead.");
  691. }
  692. }
  693. /**
  694. * Alias for {@link #sheetIterator()} to allow
  695. * foreach loops
  696. */
  697. @Override
  698. public Iterator<Sheet> iterator() {
  699. return sheetIterator();
  700. }
  701. /**
  702. * Get the Sheet object at the given index.
  703. *
  704. * @param index of the sheet number (0-based physical and logical)
  705. * @return Sheet at the provided index
  706. */
  707. @Override
  708. public SXSSFSheet getSheetAt(int index)
  709. {
  710. return getSXSSFSheet(_wb.getSheetAt(index));
  711. }
  712. /**
  713. * Get sheet with the given name
  714. *
  715. * @param name of the sheet
  716. * @return Sheet with the name provided or <code>null</code> if it does not exist
  717. */
  718. @Override
  719. public SXSSFSheet getSheet(String name)
  720. {
  721. return getSXSSFSheet(_wb.getSheet(name));
  722. }
  723. /**
  724. * Removes sheet at the given index
  725. *
  726. * @param index of the sheet to remove (0-based)
  727. */
  728. @Override
  729. public void removeSheetAt(int index)
  730. {
  731. // Get the sheet to be removed
  732. XSSFSheet xSheet = _wb.getSheetAt(index);
  733. SXSSFSheet sxSheet = getSXSSFSheet(xSheet);
  734. // De-register it
  735. _wb.removeSheetAt(index);
  736. deregisterSheetMapping(xSheet);
  737. // Clean up temporary resources
  738. try {
  739. sxSheet.dispose();
  740. } catch (IOException e) {
  741. logger.log(POILogger.WARN, e);
  742. }
  743. }
  744. /**
  745. * Create a new Font and add it to the workbook's font table
  746. *
  747. * @return new font object
  748. */
  749. @Override
  750. public Font createFont()
  751. {
  752. return _wb.createFont();
  753. }
  754. /**
  755. * Finds a font that matches the one with the supplied attributes
  756. *
  757. * @return the font with the matched attributes or <code>null</code>
  758. */
  759. @Override
  760. public Font findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline)
  761. {
  762. return _wb.findFont(bold, color, fontHeight, name, italic, strikeout, typeOffset, underline);
  763. }
  764. @Override
  765. @Deprecated
  766. public short getNumberOfFonts() {
  767. return (short)getNumberOfFontsAsInt();
  768. }
  769. @Override
  770. public int getNumberOfFontsAsInt()
  771. {
  772. return _wb.getNumberOfFontsAsInt();
  773. }
  774. @Override
  775. @Deprecated
  776. public Font getFontAt(short idx)
  777. {
  778. return getFontAt((int)idx);
  779. }
  780. @Override
  781. public Font getFontAt(int idx)
  782. {
  783. return _wb.getFontAt(idx);
  784. }
  785. /**
  786. * Create a new Cell style and add it to the workbook's style table
  787. *
  788. * @return the new Cell Style object
  789. */
  790. @Override
  791. public CellStyle createCellStyle()
  792. {
  793. return _wb.createCellStyle();
  794. }
  795. /**
  796. * Get the number of styles the workbook contains
  797. *
  798. * @return count of cell styles
  799. */
  800. @Override
  801. public int getNumCellStyles()
  802. {
  803. return _wb.getNumCellStyles();
  804. }
  805. /**
  806. * Get the cell style object at the given index
  807. *
  808. * @param idx index within the set of styles (0-based)
  809. * @return CellStyle object at the index
  810. */
  811. @Override
  812. public CellStyle getCellStyleAt(int idx)
  813. {
  814. return _wb.getCellStyleAt(idx);
  815. }
  816. /**
  817. * Closes the underlying {@link XSSFWorkbook} and {@link OPCPackage}
  818. * on which this Workbook is based, if any.
  819. *
  820. * <p>Once this has been called, no further
  821. * operations, updates or reads should be performed on the
  822. * Workbook.
  823. */
  824. @Override
  825. public void close() throws IOException {
  826. // ensure that any lingering writer is closed
  827. for (SXSSFSheet sheet : _xFromSxHash.values())
  828. {
  829. try {
  830. sheet.getSheetDataWriter().close();
  831. } catch (IOException e) {
  832. logger.log(POILogger.WARN,
  833. "An exception occurred while closing sheet data writer for sheet "
  834. + sheet.getSheetName() + ".", e);
  835. }
  836. }
  837. // Tell the base workbook to close, does nothing if
  838. // it's a newly created one
  839. _wb.close();
  840. }
  841. /**
  842. * Write out this workbook to an OutputStream.
  843. *
  844. * @param stream - the java OutputStream you wish to write to
  845. * @exception IOException if anything can't be written.
  846. */
  847. @Override
  848. public void write(OutputStream stream) throws IOException {
  849. flushSheets();
  850. //Save the template
  851. File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");
  852. boolean deleted;
  853. try {
  854. try (FileOutputStream os = new FileOutputStream(tmplFile)) {
  855. _wb.write(os);
  856. }
  857. //Substitute the template entries with the generated sheet data files
  858. try (ZipSecureFile zf = new ZipSecureFile(tmplFile);
  859. ZipFileZipEntrySource source = new ZipFileZipEntrySource(zf)) {
  860. injectData(source, stream);
  861. }
  862. } finally {
  863. deleted = tmplFile.delete();
  864. }
  865. if(!deleted) {
  866. throw new IOException("Could not delete temporary file after processing: " + tmplFile);
  867. }
  868. }
  869. protected void flushSheets() throws IOException {
  870. for (SXSSFSheet sheet : _xFromSxHash.values())
  871. {
  872. sheet.flushRows();
  873. }
  874. }
  875. /**
  876. * Dispose of temporary files backing this workbook on disk.
  877. * Calling this method will render the workbook unusable.
  878. * @return true if all temporary files were deleted successfully.
  879. */
  880. public boolean dispose()
  881. {
  882. boolean success = true;
  883. for (SXSSFSheet sheet : _sxFromXHash.keySet())
  884. {
  885. try {
  886. success = sheet.dispose() && success;
  887. } catch (IOException e) {
  888. logger.log(POILogger.WARN, e);
  889. success = false;
  890. }
  891. }
  892. return success;
  893. }
  894. /**
  895. * @return the total number of defined names in this workbook
  896. */
  897. @Override
  898. public int getNumberOfNames()
  899. {
  900. return _wb.getNumberOfNames();
  901. }
  902. /**
  903. * @param name the name of the defined name
  904. * @return the defined name with the specified name. <code>null</code> if not found.
  905. */
  906. @Override
  907. public Name getName(String name)
  908. {
  909. return _wb.getName(name);
  910. }
  911. /**
  912. * Returns all defined names with the given name.
  913. *
  914. * @param name the name of the defined name
  915. * @return a list of the defined names with the specified name. An empty list is returned if none is found.
  916. */
  917. @Override
  918. public List<? extends Name> getNames(String name) {
  919. return _wb.getNames(name);
  920. }
  921. /**
  922. * Returns all defined names
  923. *
  924. * @return all defined names
  925. */
  926. @Override
  927. public List<? extends Name> getAllNames()
  928. {
  929. return _wb.getAllNames();
  930. }
  931. /**
  932. * Creates a new (uninitialised) defined name in this workbook
  933. *
  934. * @return new defined name object
  935. */
  936. @Override
  937. public Name createName()
  938. {
  939. return _wb.createName();
  940. }
  941. /**
  942. * Remove the given defined name
  943. *
  944. * @param name the name to remove
  945. */
  946. @Override
  947. public void removeName(Name name)
  948. {
  949. _wb.removeName(name);
  950. }
  951. /**
  952. * Sets the printarea for the sheet provided
  953. * <p>
  954. * i.e. Reference = $A$1:$B$2
  955. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  956. * @param reference Valid name Reference for the Print Area
  957. */
  958. @Override
  959. public void setPrintArea(int sheetIndex, String reference)
  960. {
  961. _wb.setPrintArea(sheetIndex,reference);
  962. }
  963. /**
  964. * For the Convenience of Java Programmers maintaining pointers.
  965. * @see #setPrintArea(int, String)
  966. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  967. * @param startColumn Column to begin printarea
  968. * @param endColumn Column to end the printarea
  969. * @param startRow Row to begin the printarea
  970. * @param endRow Row to end the printarea
  971. */
  972. @Override
  973. public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow)
  974. {
  975. _wb.setPrintArea(sheetIndex, startColumn, endColumn, startRow, endRow);
  976. }
  977. /**
  978. * Retrieves the reference for the printarea of the specified sheet,
  979. * the sheet name is appended to the reference even if it was not specified.
  980. *
  981. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  982. * @return String Null if no print area has been defined
  983. */
  984. @Override
  985. public String getPrintArea(int sheetIndex)
  986. {
  987. return _wb.getPrintArea(sheetIndex);
  988. }
  989. /**
  990. * Delete the printarea for the sheet specified
  991. *
  992. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  993. */
  994. @Override
  995. public void removePrintArea(int sheetIndex)
  996. {
  997. _wb.removePrintArea(sheetIndex);
  998. }
  999. /**
  1000. * Retrieves the current policy on what to do when
  1001. * getting missing or blank cells from a row.
  1002. * <p>
  1003. * The default is to return blank and null cells.
  1004. * {@link MissingCellPolicy}
  1005. * </p>
  1006. */
  1007. @Override
  1008. public MissingCellPolicy getMissingCellPolicy()
  1009. {
  1010. return _wb.getMissingCellPolicy();
  1011. }
  1012. /**
  1013. * Sets the policy on what to do when
  1014. * getting missing or blank cells from a row.
  1015. *
  1016. * This will then apply to all calls to
  1017. * {@link org.apache.poi.ss.usermodel.Row#getCell(int)}. See
  1018. * {@link MissingCellPolicy}
  1019. */
  1020. @Override
  1021. public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy)
  1022. {
  1023. _wb.setMissingCellPolicy(missingCellPolicy);
  1024. }
  1025. /**
  1026. * Returns the instance of DataFormat for this workbook.
  1027. *
  1028. * @return the DataFormat object
  1029. */
  1030. @Override
  1031. public DataFormat createDataFormat()
  1032. {
  1033. return _wb.createDataFormat();
  1034. }
  1035. /**
  1036. * Adds a picture to the workbook.
  1037. *
  1038. * @param pictureData The bytes of the picture
  1039. * @param format The format of the picture.
  1040. *
  1041. * @return the index to this picture (1 based).
  1042. * @see #PICTURE_TYPE_EMF
  1043. * @see #PICTURE_TYPE_WMF
  1044. * @see #PICTURE_TYPE_PICT
  1045. * @see #PICTURE_TYPE_JPEG
  1046. * @see #PICTURE_TYPE_PNG
  1047. * @see #PICTURE_TYPE_DIB
  1048. */
  1049. @Override
  1050. public int addPicture(byte[] pictureData, int format)
  1051. {
  1052. return _wb.addPicture(pictureData,format);
  1053. }
  1054. /**
  1055. * Gets all pictures from the Workbook.
  1056. *
  1057. * @return the list of pictures (a list of {@link PictureData} objects.)
  1058. */
  1059. @Override
  1060. public List<? extends PictureData> getAllPictures()
  1061. {
  1062. return _wb.getAllPictures();
  1063. }
  1064. /**
  1065. * Returns an object that handles instantiating concrete
  1066. * classes of the various instances one needs for HSSF, XSSF
  1067. * and SXSSF.
  1068. */
  1069. @Override
  1070. public CreationHelper getCreationHelper() {
  1071. return new SXSSFCreationHelper(this);
  1072. }
  1073. protected boolean isDate1904() {
  1074. return _wb.isDate1904();
  1075. }
  1076. @Override
  1077. @NotImplemented("XSSFWorkbook#isHidden is not implemented")
  1078. public boolean isHidden()
  1079. {
  1080. return _wb.isHidden();
  1081. }
  1082. @Override
  1083. @NotImplemented("XSSFWorkbook#setHidden is not implemented")
  1084. public void setHidden(boolean hiddenFlag)
  1085. {
  1086. _wb.setHidden(hiddenFlag);
  1087. }
  1088. @Override
  1089. public boolean isSheetHidden(int sheetIx)
  1090. {
  1091. return _wb.isSheetHidden(sheetIx);
  1092. }
  1093. @Override
  1094. public boolean isSheetVeryHidden(int sheetIx)
  1095. {
  1096. return _wb.isSheetVeryHidden(sheetIx);
  1097. }
  1098. @Override
  1099. public SheetVisibility getSheetVisibility(int sheetIx) {
  1100. return _wb.getSheetVisibility(sheetIx);
  1101. }
  1102. @Override
  1103. public void setSheetHidden(int sheetIx, boolean hidden)
  1104. {
  1105. _wb.setSheetHidden(sheetIx,hidden);
  1106. }
  1107. @Override
  1108. public void setSheetVisibility(int sheetIx, SheetVisibility visibility) {
  1109. _wb.setSheetVisibility(sheetIx, visibility);
  1110. }
  1111. /**
  1112. * @param nameIndex position of the named range (0-based)
  1113. * @return the defined name at the specified index
  1114. * @throws IllegalArgumentException if the supplied index is invalid
  1115. * @deprecated 3.16. New projects should avoid accessing named ranges by index.
  1116. */
  1117. @Override
  1118. @Deprecated
  1119. @Removal(version="3.20")
  1120. public Name getNameAt(int nameIndex) {
  1121. //noinspection deprecation
  1122. return _wb.getNameAt(nameIndex);
  1123. }
  1124. /**
  1125. * Gets the defined name index by name
  1126. *
  1127. * <i>Note:</i> Excel defined names are case-insensitive and
  1128. * this method performs a case-insensitive search.
  1129. *
  1130. * @param name the name of the defined name
  1131. * @return zero based index of the defined name. <code>-1</code> if not found.
  1132. *
  1133. * @deprecated 3.16. New projects should avoid accessing named ranges by index.
  1134. * Use {@link #getName(String)} instead.
  1135. */
  1136. @Override
  1137. @Deprecated
  1138. @Removal(version="3.20")
  1139. public int getNameIndex(String name) {
  1140. //noinspection deprecation
  1141. return _wb.getNameIndex(name);
  1142. }
  1143. /**
  1144. * Remove the defined name at the specified index
  1145. * @param index named range index (0 based)
  1146. *
  1147. * @deprecated 3.16. New projects should use {@link #removeName(Name)}.
  1148. */
  1149. @Override
  1150. @Deprecated
  1151. @Removal(version="3.20")
  1152. public void removeName(int index) {
  1153. //noinspection deprecation
  1154. _wb.removeName(index);
  1155. }
  1156. /**
  1157. * Remove a defined name by name
  1158. *
  1159. * @param name the name of the defined name
  1160. *
  1161. * @deprecated 3.16. New projects should use {@link #removeName(Name)}.
  1162. */
  1163. @Override
  1164. @Deprecated
  1165. @Removal(version="3.20")
  1166. public void removeName(String name) {
  1167. //noinspection deprecation
  1168. _wb.removeName(name);
  1169. }
  1170. /**
  1171. * <i>Not implemented for SXSSFWorkbook</i>
  1172. *
  1173. * Adds the LinkTable records required to allow formulas referencing
  1174. * the specified external workbook to be added to this one. Allows
  1175. * formulas such as "[MyOtherWorkbook]Sheet3!$A$5" to be added to the
  1176. * file, for workbooks not already referenced.
  1177. *
  1178. * Note: this is not implemented and thus currently throws an Exception stating this.
  1179. *
  1180. * @param name The name the workbook will be referenced as in formulas
  1181. * @param workbook The open workbook to fetch the link required information from
  1182. *
  1183. * @throws RuntimeException stating that this method is not implemented yet.
  1184. */
  1185. @Override
  1186. @NotImplemented
  1187. public int linkExternalWorkbook(String name, Workbook workbook) {
  1188. throw new RuntimeException("Not Implemented");
  1189. }
  1190. /**
  1191. * Register a new toolpack in this workbook.
  1192. *
  1193. * @param toopack the toolpack to register
  1194. */
  1195. @Override
  1196. public void addToolPack(UDFFinder toopack)
  1197. {
  1198. _wb.addToolPack(toopack);
  1199. }
  1200. /**
  1201. * Whether the application shall perform a full recalculation when the workbook is opened.
  1202. * <p>
  1203. * Typically you want to force formula recalculation when you modify cell formulas or values
  1204. * of a workbook previously created by Excel. When set to 0, this flag will tell Excel
  1205. * that it needs to recalculate all formulas in the workbook the next time the file is opened.
  1206. * </p>
  1207. *
  1208. * @param value true if the application will perform a full recalculation of
  1209. * workbook values when the workbook is opened
  1210. * @since 3.8
  1211. */
  1212. @Override
  1213. public void setForceFormulaRecalculation(boolean value){
  1214. _wb.setForceFormulaRecalculation(value);
  1215. }
  1216. /**
  1217. * Whether Excel will be asked to recalculate all formulas when the workbook is opened.
  1218. */
  1219. @Override
  1220. public boolean getForceFormulaRecalculation(){
  1221. return _wb.getForceFormulaRecalculation();
  1222. }
  1223. /**
  1224. * Returns the spreadsheet version (EXCLE2007) of this workbook
  1225. *
  1226. * @return EXCEL2007 SpreadsheetVersion enum
  1227. * @since 3.14 beta 2
  1228. */
  1229. @Override
  1230. public SpreadsheetVersion getSpreadsheetVersion() {
  1231. return SpreadsheetVersion.EXCEL2007;
  1232. }
  1233. @Override
  1234. public int addOlePackage(byte[] oleData, String label, String fileName, String command) throws IOException {
  1235. return _wb.addOlePackage(oleData, label, fileName, command);
  1236. }
  1237. //end of interface implementation
  1238. }