Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  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.hssf.usermodel;
  16. import java.io.ByteArrayInputStream;
  17. import java.io.FileNotFoundException;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.io.PrintWriter;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Hashtable;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.regex.Pattern;
  29. import org.apache.poi.POIDocument;
  30. import org.apache.poi.ddf.EscherBSERecord;
  31. import org.apache.poi.ddf.EscherBitmapBlip;
  32. import org.apache.poi.ddf.EscherBlipRecord;
  33. import org.apache.poi.ddf.EscherRecord;
  34. import org.apache.poi.hssf.OldExcelFormatException;
  35. import org.apache.poi.hssf.model.HSSFFormulaParser;
  36. import org.apache.poi.hssf.model.RecordStream;
  37. import org.apache.poi.hssf.model.Sheet;
  38. import org.apache.poi.hssf.model.Workbook;
  39. import org.apache.poi.hssf.record.AbstractEscherHolderRecord;
  40. import org.apache.poi.hssf.record.BackupRecord;
  41. import org.apache.poi.hssf.record.DrawingGroupRecord;
  42. import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord;
  43. import org.apache.poi.hssf.record.ExtendedFormatRecord;
  44. import org.apache.poi.hssf.record.FontRecord;
  45. import org.apache.poi.hssf.record.LabelRecord;
  46. import org.apache.poi.hssf.record.LabelSSTRecord;
  47. import org.apache.poi.hssf.record.NameRecord;
  48. import org.apache.poi.hssf.record.ObjRecord;
  49. import org.apache.poi.hssf.record.Record;
  50. import org.apache.poi.hssf.record.RecordFactory;
  51. import org.apache.poi.hssf.record.SSTRecord;
  52. import org.apache.poi.hssf.record.UnicodeString;
  53. import org.apache.poi.hssf.record.UnknownRecord;
  54. import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
  55. import org.apache.poi.hssf.record.formula.Area3DPtg;
  56. import org.apache.poi.hssf.record.formula.MemFuncPtg;
  57. import org.apache.poi.hssf.record.formula.NameXPtg;
  58. import org.apache.poi.hssf.record.formula.Ptg;
  59. import org.apache.poi.hssf.record.formula.Ref3DPtg;
  60. import org.apache.poi.hssf.record.formula.SheetNameFormatter;
  61. import org.apache.poi.hssf.record.formula.UnionPtg;
  62. import org.apache.poi.hssf.record.formula.functions.FreeRefFunction;
  63. import org.apache.poi.hssf.util.CellReference;
  64. import org.apache.poi.poifs.filesystem.DirectoryNode;
  65. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  66. import org.apache.poi.ss.usermodel.CreationHelper;
  67. import org.apache.poi.ss.usermodel.Name;
  68. import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
  69. import org.apache.poi.ss.formula.FormulaType;
  70. import org.apache.poi.util.POILogFactory;
  71. import org.apache.poi.util.POILogger;
  72. /**
  73. * High level representation of a workbook. This is the first object most users
  74. * will construct whether they are reading or writing a workbook. It is also the
  75. * top level object for creating new sheets/etc.
  76. *
  77. * @see org.apache.poi.hssf.model.Workbook
  78. * @see org.apache.poi.hssf.usermodel.HSSFSheet
  79. * @author Andrew C. Oliver (acoliver at apache dot org)
  80. * @author Glen Stampoultzis (glens at apache.org)
  81. * @author Shawn Laubach (slaubach at apache dot org)
  82. *
  83. *
  84. * Modified 09/07/09 by Petr Udalau - added methods for work with UDFs of this Workbook.
  85. */
  86. public class HSSFWorkbook extends POIDocument implements org.apache.poi.ss.usermodel.Workbook {
  87. private static final Pattern COMMA_PATTERN = Pattern.compile(",");
  88. private static final int MAX_ROW = 0xFFFF;
  89. private static final short MAX_COLUMN = (short)0x00FF;
  90. private static final int DEBUG = POILogger.DEBUG;
  91. /**
  92. * used for compile-time performance/memory optimization. This determines the
  93. * initial capacity for the sheet collection. Its currently set to 3.
  94. * Changing it in this release will decrease performance
  95. * since you're never allowed to have more or less than three sheets!
  96. */
  97. public final static int INITIAL_CAPACITY = 3;
  98. /**
  99. * this is the reference to the low level Workbook object
  100. */
  101. private Workbook workbook;
  102. /**
  103. * this holds the HSSFSheet objects attached to this workbook
  104. */
  105. protected List _sheets;
  106. /**
  107. * this holds the HSSFName objects attached to this workbook
  108. */
  109. private ArrayList names;
  110. /**
  111. * this holds the HSSFFont objects attached to this workbook.
  112. * We only create these from the low level records as required.
  113. */
  114. private Hashtable fonts;
  115. /**
  116. * holds whether or not to preserve other nodes in the POIFS. Used
  117. * for macros and embedded objects.
  118. */
  119. private boolean preserveNodes;
  120. /**
  121. * Used to keep track of the data formatter so that all
  122. * createDataFormatter calls return the same one for a given
  123. * book. This ensures that updates from one places is visible
  124. * someplace else.
  125. */
  126. private HSSFDataFormat formatter;
  127. /**
  128. * The policy to apply in the event of missing or
  129. * blank cells when fetching from a row.
  130. * See {@link MissingCellPolicy}
  131. */
  132. private MissingCellPolicy missingCellPolicy = HSSFRow.RETURN_NULL_AND_BLANK;
  133. /** Extended windows meta file */
  134. public static final int PICTURE_TYPE_EMF = 2;
  135. /** Windows Meta File */
  136. public static final int PICTURE_TYPE_WMF = 3;
  137. /** Mac PICT format */
  138. public static final int PICTURE_TYPE_PICT = 4;
  139. /** JPEG format */
  140. public static final int PICTURE_TYPE_JPEG = 5;
  141. /** PNG format */
  142. public static final int PICTURE_TYPE_PNG = 6;
  143. /** Device independant bitmap */
  144. public static final int PICTURE_TYPE_DIB = 7;
  145. private static POILogger log = POILogFactory.getLogger(HSSFWorkbook.class);
  146. /** Map of user defined functions, key - function name, value - instance of FreeRefFunctions */
  147. private Map<String, FreeRefFunction> udfFunctions;
  148. /**
  149. * Creates new HSSFWorkbook from scratch (start here!)
  150. *
  151. */
  152. public HSSFWorkbook()
  153. {
  154. this(Workbook.createWorkbook());
  155. }
  156. protected HSSFWorkbook( Workbook book )
  157. {
  158. super(null, null);
  159. workbook = book;
  160. _sheets = new ArrayList( INITIAL_CAPACITY );
  161. names = new ArrayList( INITIAL_CAPACITY );
  162. udfFunctions = new HashMap<String, FreeRefFunction>();
  163. }
  164. public HSSFWorkbook(POIFSFileSystem fs) throws IOException {
  165. this(fs,true);
  166. }
  167. /**
  168. * given a POI POIFSFileSystem object, read in its Workbook and populate the high and
  169. * low level models. If you're reading in a workbook...start here.
  170. *
  171. * @param fs the POI filesystem that contains the Workbook stream.
  172. * @param preserveNodes whether to preseve other nodes, such as
  173. * macros. This takes more memory, so only say yes if you
  174. * need to. If set, will store all of the POIFSFileSystem
  175. * in memory
  176. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  177. * @exception IOException if the stream cannot be read
  178. */
  179. public HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes)
  180. throws IOException
  181. {
  182. this(fs.getRoot(), fs, preserveNodes);
  183. }
  184. /**
  185. * Normally, the Workbook will be in a POIFS Stream
  186. * called "Workbook". However, some weird XLS generators use "WORKBOOK"
  187. */
  188. private static final String[] WORKBOOK_DIR_ENTRY_NAMES = {
  189. "Workbook", // as per BIFF8 spec
  190. "WORKBOOK",
  191. };
  192. private static String getWorkbookDirEntryName(DirectoryNode directory) {
  193. String[] potentialNames = WORKBOOK_DIR_ENTRY_NAMES;
  194. for (int i = 0; i < potentialNames.length; i++) {
  195. String wbName = potentialNames[i];
  196. try {
  197. directory.getEntry(wbName);
  198. return wbName;
  199. } catch (FileNotFoundException e) {
  200. // continue - to try other options
  201. }
  202. }
  203. // check for previous version of file format
  204. try {
  205. directory.getEntry("Book");
  206. throw new OldExcelFormatException("The supplied spreadsheet seems to be Excel 5.0/7.0 (BIFF5) format. "
  207. + "POI only supports BIFF8 format (from Excel versions 97/2000/XP/2003)");
  208. } catch (FileNotFoundException e) {
  209. // fall through
  210. }
  211. throw new IllegalArgumentException("The supplied POIFSFileSystem does not contain a BIFF8 'Workbook' entry. "
  212. + "Is it really an excel file?");
  213. }
  214. /**
  215. * given a POI POIFSFileSystem object, and a specific directory
  216. * within it, read in its Workbook and populate the high and
  217. * low level models. If you're reading in a workbook...start here.
  218. *
  219. * @param directory the POI filesystem directory to process from
  220. * @param fs the POI filesystem that contains the Workbook stream.
  221. * @param preserveNodes whether to preseve other nodes, such as
  222. * macros. This takes more memory, so only say yes if you
  223. * need to. If set, will store all of the POIFSFileSystem
  224. * in memory
  225. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  226. * @exception IOException if the stream cannot be read
  227. */
  228. public HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes)
  229. throws IOException
  230. {
  231. super(directory, fs);
  232. String workbookName = getWorkbookDirEntryName(directory);
  233. this.preserveNodes = preserveNodes;
  234. // If we're not preserving nodes, don't track the
  235. // POIFS any more
  236. if(! preserveNodes) {
  237. this.filesystem = null;
  238. this.directory = null;
  239. }
  240. _sheets = new ArrayList(INITIAL_CAPACITY);
  241. names = new ArrayList(INITIAL_CAPACITY);
  242. udfFunctions = new HashMap<String, FreeRefFunction>();
  243. // Grab the data from the workbook stream, however
  244. // it happens to be spelled.
  245. InputStream stream = directory.createDocumentInputStream(workbookName);
  246. List records = RecordFactory.createRecords(stream);
  247. workbook = Workbook.createWorkbook(records);
  248. setPropertiesFromWorkbook(workbook);
  249. int recOffset = workbook.getNumRecords();
  250. int sheetNum = 0;
  251. // convert all LabelRecord records to LabelSSTRecord
  252. convertLabelRecords(records, recOffset);
  253. RecordStream rs = new RecordStream(records, recOffset);
  254. while (rs.hasNext()) {
  255. Sheet sheet = Sheet.createSheet(rs);
  256. _sheets.add(new HSSFSheet(this, sheet));
  257. }
  258. for (int i = 0 ; i < workbook.getNumNames() ; ++i){
  259. HSSFName name = new HSSFName(this, workbook.getNameRecord(i));
  260. names.add(name);
  261. }
  262. }
  263. public HSSFWorkbook(InputStream s) throws IOException {
  264. this(s,true);
  265. }
  266. /**
  267. * Companion to HSSFWorkbook(POIFSFileSystem), this constructs the POI filesystem around your
  268. * inputstream.
  269. *
  270. * @param s the POI filesystem that contains the Workbook stream.
  271. * @param preserveNodes whether to preseve other nodes, such as
  272. * macros. This takes more memory, so only say yes if you
  273. * need to.
  274. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  275. * @see #HSSFWorkbook(POIFSFileSystem)
  276. * @exception IOException if the stream cannot be read
  277. */
  278. public HSSFWorkbook(InputStream s, boolean preserveNodes)
  279. throws IOException
  280. {
  281. this(new POIFSFileSystem(s), preserveNodes);
  282. }
  283. /**
  284. * used internally to set the workbook properties.
  285. */
  286. private void setPropertiesFromWorkbook(Workbook book)
  287. {
  288. this.workbook = book;
  289. // none currently
  290. }
  291. /**
  292. * This is basically a kludge to deal with the now obsolete Label records. If
  293. * you have to read in a sheet that contains Label records, be aware that the rest
  294. * of the API doesn't deal with them, the low level structure only provides read-only
  295. * semi-immutable structures (the sets are there for interface conformance with NO
  296. * impelmentation). In short, you need to call this function passing it a reference
  297. * to the Workbook object. All labels will be converted to LabelSST records and their
  298. * contained strings will be written to the Shared String tabel (SSTRecord) within
  299. * the Workbook.
  300. *
  301. * @param wb sheet's matching low level Workbook structure containing the SSTRecord.
  302. * @see org.apache.poi.hssf.record.LabelRecord
  303. * @see org.apache.poi.hssf.record.LabelSSTRecord
  304. * @see org.apache.poi.hssf.record.SSTRecord
  305. */
  306. private void convertLabelRecords(List records, int offset)
  307. {
  308. if (log.check( POILogger.DEBUG ))
  309. log.log(POILogger.DEBUG, "convertLabelRecords called");
  310. for (int k = offset; k < records.size(); k++)
  311. {
  312. Record rec = ( Record ) records.get(k);
  313. if (rec.getSid() == LabelRecord.sid)
  314. {
  315. LabelRecord oldrec = ( LabelRecord ) rec;
  316. records.remove(k);
  317. LabelSSTRecord newrec = new LabelSSTRecord();
  318. int stringid =
  319. workbook.addSSTString(new UnicodeString(oldrec.getValue()));
  320. newrec.setRow(oldrec.getRow());
  321. newrec.setColumn(oldrec.getColumn());
  322. newrec.setXFIndex(oldrec.getXFIndex());
  323. newrec.setSSTIndex(stringid);
  324. records.add(k, newrec);
  325. }
  326. }
  327. if (log.check( POILogger.DEBUG ))
  328. log.log(POILogger.DEBUG, "convertLabelRecords exit");
  329. }
  330. /**
  331. * Retrieves the current policy on what to do when
  332. * getting missing or blank cells from a row.
  333. * The default is to return blank and null cells.
  334. * {@link MissingCellPolicy}
  335. */
  336. public MissingCellPolicy getMissingCellPolicy() {
  337. return missingCellPolicy;
  338. }
  339. /**
  340. * Sets the policy on what to do when
  341. * getting missing or blank cells from a row.
  342. * This will then apply to all calls to
  343. * {@link HSSFRow#getCell(int)}}. See
  344. * {@link MissingCellPolicy}.
  345. * Note that this has no effect on any
  346. * iterators, only on when fetching Cells
  347. * by their column index.
  348. */
  349. public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) {
  350. this.missingCellPolicy = missingCellPolicy;
  351. }
  352. /**
  353. * sets the order of appearance for a given sheet.
  354. *
  355. * @param sheetname the name of the sheet to reorder
  356. * @param pos the position that we want to insert the sheet into (0 based)
  357. */
  358. public void setSheetOrder(String sheetname, int pos ) {
  359. _sheets.add(pos,_sheets.remove(getSheetIndex(sheetname)));
  360. workbook.setSheetOrder(sheetname, pos);
  361. }
  362. private void validateSheetIndex(int index) {
  363. int lastSheetIx = _sheets.size() - 1;
  364. if (index < 0 || index > lastSheetIx) {
  365. throw new IllegalArgumentException("Sheet index ("
  366. + index +") is out of range (0.." + lastSheetIx + ")");
  367. }
  368. }
  369. /**
  370. * Selects a single sheet. This may be different to
  371. * the 'active' sheet (which is the sheet with focus).
  372. */
  373. public void setSelectedTab(int index) {
  374. validateSheetIndex(index);
  375. int nSheets = _sheets.size();
  376. for (int i=0; i<nSheets; i++) {
  377. getSheetAt(i).setSelected(i == index);
  378. }
  379. workbook.getWindowOne().setNumSelectedTabs((short)1);
  380. }
  381. /**
  382. * deprecated May 2008
  383. * @deprecated use setSelectedTab(int)
  384. */
  385. public void setSelectedTab(short index) {
  386. setSelectedTab((int)index);
  387. }
  388. public void setSelectedTabs(int[] indexes) {
  389. for (int i = 0; i < indexes.length; i++) {
  390. validateSheetIndex(indexes[i]);
  391. }
  392. int nSheets = _sheets.size();
  393. for (int i=0; i<nSheets; i++) {
  394. boolean bSelect = false;
  395. for (int j = 0; j < indexes.length; j++) {
  396. if (indexes[j] == i) {
  397. bSelect = true;
  398. break;
  399. }
  400. }
  401. getSheetAt(i).setSelected(bSelect);
  402. }
  403. workbook.getWindowOne().setNumSelectedTabs((short)indexes.length);
  404. }
  405. /**
  406. * Convenience method to set the active sheet. The active sheet is is the sheet
  407. * which is currently displayed when the workbook is viewed in Excel.
  408. * 'Selected' sheet(s) is a distinct concept.
  409. */
  410. public void setActiveSheet(int index) {
  411. validateSheetIndex(index);
  412. int nSheets = _sheets.size();
  413. for (int i=0; i<nSheets; i++) {
  414. getSheetAt(i).setActive(i == index);
  415. }
  416. workbook.getWindowOne().setActiveSheetIndex(index);
  417. }
  418. /**
  419. * gets the tab whose data is actually seen when the sheet is opened.
  420. * This may be different from the "selected sheet" since excel seems to
  421. * allow you to show the data of one sheet when another is seen "selected"
  422. * in the tabs (at the bottom).
  423. * @see org.apache.poi.hssf.usermodel.HSSFSheet#setSelected(boolean)
  424. */
  425. public int getActiveSheetIndex() {
  426. return workbook.getWindowOne().getActiveSheetIndex();
  427. }
  428. /**
  429. * deprecated May 2008
  430. * @deprecated - Misleading name - use getActiveSheetIndex()
  431. */
  432. public short getSelectedTab() {
  433. return (short) getActiveSheetIndex();
  434. }
  435. /**
  436. * sets the first tab that is displayed in the list of tabs
  437. * in excel.
  438. * @param index
  439. */
  440. public void setFirstVisibleTab(int index) {
  441. workbook.getWindowOne().setFirstVisibleTab(index);
  442. }
  443. /**
  444. * deprecated May 2008
  445. * @deprecated - Misleading name - use setFirstVisibleTab()
  446. */
  447. public void setDisplayedTab(short index) {
  448. setFirstVisibleTab(index);
  449. }
  450. /**
  451. * sets the first tab that is displayed in the list of tabs in excel.
  452. */
  453. public int getFirstVisibleTab() {
  454. return workbook.getWindowOne().getFirstVisibleTab();
  455. }
  456. /**
  457. * deprecated May 2008
  458. * @deprecated - Misleading name - use getFirstVisibleTab()
  459. */
  460. public short getDisplayedTab() {
  461. return (short) getFirstVisibleTab();
  462. }
  463. /**
  464. * Sets the sheet name.
  465. * Will throw IllegalArgumentException if the name is duplicated or contains /\?*[]
  466. * Note - Excel allows sheet names up to 31 chars in length but other applications allow more.
  467. * Excel does not crash with names longer than 31 chars, but silently truncates such names to
  468. * 31 chars. POI enforces uniqueness on the first 31 chars.
  469. *
  470. * @param sheetIx number (0 based)
  471. */
  472. public void setSheetName(int sheetIx, String name) {
  473. if (workbook.doesContainsSheetName(name, sheetIx)) {
  474. throw new IllegalArgumentException("The workbook already contains a sheet with this name");
  475. }
  476. validateSheetIndex(sheetIx);
  477. workbook.setSheetName(sheetIx, name);
  478. }
  479. /**
  480. * @return Sheet name for the specified index
  481. */
  482. public String getSheetName(int sheetIndex) {
  483. validateSheetIndex(sheetIndex);
  484. return workbook.getSheetName(sheetIndex);
  485. }
  486. public boolean isHidden() {
  487. return workbook.getWindowOne().getHidden();
  488. }
  489. public void setHidden(boolean hiddenFlag) {
  490. workbook.getWindowOne().setHidden(hiddenFlag);
  491. }
  492. public boolean isSheetHidden(int sheetIx) {
  493. validateSheetIndex(sheetIx);
  494. return workbook.isSheetHidden(sheetIx);
  495. }
  496. public boolean isSheetVeryHidden(int sheetIx) {
  497. validateSheetIndex(sheetIx);
  498. return workbook.isSheetVeryHidden(sheetIx);
  499. }
  500. public void setSheetHidden(int sheetIx, boolean hidden) {
  501. validateSheetIndex(sheetIx);
  502. workbook.setSheetHidden(sheetIx, hidden);
  503. }
  504. public void setSheetHidden(int sheetIx, int hidden) {
  505. validateSheetIndex(sheetIx);
  506. workbook.setSheetHidden(sheetIx, hidden);
  507. }
  508. /** Returns the index of the sheet by his name
  509. * @param name the sheet name
  510. * @return index of the sheet (0 based)
  511. */
  512. public int getSheetIndex(String name){
  513. return workbook.getSheetIndex(name);
  514. }
  515. /** Returns the index of the given sheet
  516. * @param sheet the sheet to look up
  517. * @return index of the sheet (0 based). <tt>-1</tt> if not found
  518. */
  519. public int getSheetIndex(org.apache.poi.ss.usermodel.Sheet sheet) {
  520. for(int i=0; i<_sheets.size(); i++) {
  521. if(_sheets.get(i) == sheet) {
  522. return i;
  523. }
  524. }
  525. return -1;
  526. }
  527. /**
  528. * Returns the external sheet index of the sheet
  529. * with the given internal index, creating one
  530. * if needed.
  531. * Used by some of the more obscure formula and
  532. * named range things.
  533. * @deprecated for POI internal use only (formula parsing). This method is likely to
  534. * be removed in future versions of POI.
  535. */
  536. public int getExternalSheetIndex(int internalSheetIndex) {
  537. return workbook.checkExternSheet(internalSheetIndex);
  538. }
  539. /**
  540. * @deprecated for POI internal use only (formula rendering). This method is likely to
  541. * be removed in future versions of POI.
  542. */
  543. public String findSheetNameFromExternSheet(int externSheetIndex){
  544. // TODO - don't expose internal ugliness like externSheet indexes to the user model API
  545. return workbook.findSheetNameFromExternSheet(externSheetIndex);
  546. }
  547. /**
  548. * @deprecated for POI internal use only (formula rendering). This method is likely to
  549. * be removed in future versions of POI.
  550. *
  551. * @param refIndex Index to REF entry in EXTERNSHEET record in the Link Table
  552. * @param definedNameIndex zero-based to DEFINEDNAME or EXTERNALNAME record
  553. * @return the string representation of the defined or external name
  554. */
  555. public String resolveNameXText(int refIndex, int definedNameIndex) {
  556. // TODO - make this less cryptic / move elsewhere
  557. return workbook.resolveNameXText(refIndex, definedNameIndex);
  558. }
  559. /**
  560. * create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and returns
  561. * the high level representation. Use this to create new sheets.
  562. *
  563. * @return HSSFSheet representing the new sheet.
  564. */
  565. public HSSFSheet createSheet()
  566. {
  567. HSSFSheet sheet = new HSSFSheet(this);
  568. _sheets.add(sheet);
  569. workbook.setSheetName(_sheets.size() - 1, "Sheet" + (_sheets.size() - 1));
  570. boolean isOnlySheet = _sheets.size() == 1;
  571. sheet.setSelected(isOnlySheet);
  572. sheet.setActive(isOnlySheet);
  573. return sheet;
  574. }
  575. /**
  576. * create an HSSFSheet from an existing sheet in the HSSFWorkbook.
  577. *
  578. * @return HSSFSheet representing the cloned sheet.
  579. */
  580. public HSSFSheet cloneSheet(int sheetIndex) {
  581. validateSheetIndex(sheetIndex);
  582. HSSFSheet srcSheet = (HSSFSheet) _sheets.get(sheetIndex);
  583. String srcName = workbook.getSheetName(sheetIndex);
  584. HSSFSheet clonedSheet = srcSheet.cloneSheet(this);
  585. clonedSheet.setSelected(false);
  586. clonedSheet.setActive(false);
  587. String name = getUniqueSheetName(srcName);
  588. int newSheetIndex = _sheets.size();
  589. _sheets.add(clonedSheet);
  590. workbook.setSheetName(newSheetIndex, name);
  591. // Check this sheet has an autofilter, (which has a built-in NameRecord at workbook level)
  592. int filterDbNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_FILTER_DB);
  593. if (filterDbNameIndex >=0) {
  594. NameRecord origNameRecord = workbook.getNameRecord(filterDbNameIndex);
  595. // copy original formula but adjust 3D refs to the new external sheet index
  596. int newExtSheetIx = workbook.checkExternSheet(newSheetIndex);
  597. Ptg[] ptgs = origNameRecord.getNameDefinition();
  598. for (int i=0; i< ptgs.length; i++) {
  599. Ptg ptg = ptgs[i];
  600. ptg = ptg.copy();
  601. if (ptg instanceof Area3DPtg) {
  602. Area3DPtg a3p = (Area3DPtg) ptg;
  603. a3p.setExternSheetIndex(newExtSheetIx);
  604. } else if (ptg instanceof Ref3DPtg) {
  605. Ref3DPtg r3p = (Ref3DPtg) ptg;
  606. r3p.setExternSheetIndex(newExtSheetIx);
  607. }
  608. ptgs[i] = ptg;
  609. }
  610. NameRecord newNameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_FILTER_DB, newSheetIndex+1);
  611. newNameRecord.setNameDefinition(ptgs);
  612. newNameRecord.setHidden(true);
  613. HSSFName newName = new HSSFName(this, newNameRecord);
  614. names.add(newName);
  615. workbook.cloneDrawings(clonedSheet.getSheet());
  616. }
  617. // TODO - maybe same logic required for other/all built-in name records
  618. return clonedSheet;
  619. }
  620. private String getUniqueSheetName(String srcName) {
  621. int uniqueIndex = 2;
  622. String baseName = srcName;
  623. int bracketPos = srcName.lastIndexOf('(');
  624. if (bracketPos > 0 && srcName.endsWith(")")) {
  625. String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length());
  626. try {
  627. uniqueIndex = Integer.parseInt(suffix.trim());
  628. uniqueIndex++;
  629. baseName=srcName.substring(0, bracketPos).trim();
  630. } catch (NumberFormatException e) {
  631. // contents of brackets not numeric
  632. }
  633. }
  634. while (true) {
  635. // Try and find the next sheet name that is unique
  636. String index = Integer.toString(uniqueIndex++);
  637. String name;
  638. if (baseName.length() + index.length() + 2 < 31) {
  639. name = baseName + " (" + index + ")";
  640. } else {
  641. name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")";
  642. }
  643. //If the sheet name is unique, then set it otherwise move on to the next number.
  644. if (workbook.getSheetIndex(name) == -1) {
  645. return name;
  646. }
  647. }
  648. }
  649. /**
  650. * create an HSSFSheet for this HSSFWorkbook, adds it to the sheets and
  651. * returns the high level representation. Use this to create new sheets.
  652. *
  653. * @param sheetname the name for the new sheet. Note - certain length limits
  654. * apply. See {@link #setSheetName(int, String)}.
  655. *
  656. * @return HSSFSheet representing the new sheet.
  657. * @throws IllegalArgumentException
  658. * if there is already a sheet present with a case-insensitive
  659. * match for the specified name.
  660. */
  661. public HSSFSheet createSheet(String sheetname)
  662. {
  663. if (workbook.doesContainsSheetName( sheetname, _sheets.size() ))
  664. throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
  665. HSSFSheet sheet = new HSSFSheet(this);
  666. workbook.setSheetName(_sheets.size(), sheetname);
  667. _sheets.add(sheet);
  668. boolean isOnlySheet = _sheets.size() == 1;
  669. sheet.setSelected(isOnlySheet);
  670. sheet.setActive(isOnlySheet);
  671. return sheet;
  672. }
  673. /**
  674. * get the number of spreadsheets in the workbook (this will be three after serialization)
  675. * @return number of sheets
  676. */
  677. public int getNumberOfSheets()
  678. {
  679. return _sheets.size();
  680. }
  681. public int getSheetIndexFromExternSheetIndex(int externSheetNumber) {
  682. return workbook.getSheetIndexFromExternSheetIndex(externSheetNumber);
  683. }
  684. private HSSFSheet[] getSheets() {
  685. HSSFSheet[] result = new HSSFSheet[_sheets.size()];
  686. _sheets.toArray(result);
  687. return result;
  688. }
  689. /**
  690. * Get the HSSFSheet object at the given index.
  691. * @param index of the sheet number (0-based physical & logical)
  692. * @return HSSFSheet at the provided index
  693. */
  694. public HSSFSheet getSheetAt(int index)
  695. {
  696. validateSheetIndex(index);
  697. return (HSSFSheet) _sheets.get(index);
  698. }
  699. /**
  700. * Get sheet with the given name (case insensitive match)
  701. * @param name of the sheet
  702. * @return HSSFSheet with the name provided or <code>null</code> if it does not exist
  703. */
  704. public HSSFSheet getSheet(String name)
  705. {
  706. HSSFSheet retval = null;
  707. for (int k = 0; k < _sheets.size(); k++)
  708. {
  709. String sheetname = workbook.getSheetName(k);
  710. if (sheetname.equalsIgnoreCase(name))
  711. {
  712. retval = (HSSFSheet) _sheets.get(k);
  713. }
  714. }
  715. return retval;
  716. }
  717. /**
  718. * Removes sheet at the given index.<p/>
  719. *
  720. * Care must be taken if the removed sheet is the currently active or only selected sheet in
  721. * the workbook. There are a few situations when Excel must have a selection and/or active
  722. * sheet. (For example when printing - see Bug 40414).<br/>
  723. *
  724. * This method makes sure that if the removed sheet was active, another sheet will become
  725. * active in its place. Furthermore, if the removed sheet was the only selected sheet, another
  726. * sheet will become selected. The newly active/selected sheet will have the same index, or
  727. * one less if the removed sheet was the last in the workbook.
  728. *
  729. * @param index of the sheet (0-based)
  730. */
  731. public void removeSheetAt(int index) {
  732. validateSheetIndex(index);
  733. boolean wasActive = getSheetAt(index).isActive();
  734. boolean wasSelected = getSheetAt(index).isSelected();
  735. _sheets.remove(index);
  736. workbook.removeSheet(index);
  737. // set the remaining active/selected sheet
  738. int nSheets = _sheets.size();
  739. if (nSheets < 1) {
  740. // nothing more to do if there are no sheets left
  741. return;
  742. }
  743. // the index of the closest remaining sheet to the one just deleted
  744. int newSheetIndex = index;
  745. if (newSheetIndex >= nSheets) {
  746. newSheetIndex = nSheets-1;
  747. }
  748. if (wasActive) {
  749. setActiveSheet(newSheetIndex);
  750. }
  751. if (wasSelected) {
  752. boolean someOtherSheetIsStillSelected = false;
  753. for (int i =0; i < nSheets; i++) {
  754. if (getSheetAt(i).isSelected()) {
  755. someOtherSheetIsStillSelected = true;
  756. break;
  757. }
  758. }
  759. if (!someOtherSheetIsStillSelected) {
  760. setSelectedTab(newSheetIndex);
  761. }
  762. }
  763. }
  764. /**
  765. * determine whether the Excel GUI will backup the workbook when saving.
  766. *
  767. * @param backupValue true to indicate a backup will be performed.
  768. */
  769. public void setBackupFlag(boolean backupValue)
  770. {
  771. BackupRecord backupRecord = workbook.getBackupRecord();
  772. backupRecord.setBackup(backupValue ? (short) 1
  773. : (short) 0);
  774. }
  775. /**
  776. * determine whether the Excel GUI will backup the workbook when saving.
  777. *
  778. * @return the current setting for backups.
  779. */
  780. public boolean getBackupFlag()
  781. {
  782. BackupRecord backupRecord = workbook.getBackupRecord();
  783. return (backupRecord.getBackup() == 0) ? false
  784. : true;
  785. }
  786. /**
  787. * Sets the repeating rows and columns for a sheet (as found in
  788. * 2003:File->PageSetup->Sheet, 2007:Page Layout->Print Titles).
  789. * This is function is included in the workbook
  790. * because it creates/modifies name records which are stored at the
  791. * workbook level.
  792. * <p>
  793. * To set just repeating columns:
  794. * <pre>
  795. * workbook.setRepeatingRowsAndColumns(0,0,1,-1-1);
  796. * </pre>
  797. * To set just repeating rows:
  798. * <pre>
  799. * workbook.setRepeatingRowsAndColumns(0,-1,-1,0,4);
  800. * </pre>
  801. * To remove all repeating rows and columns for a sheet.
  802. * <pre>
  803. * workbook.setRepeatingRowsAndColumns(0,-1,-1,-1,-1);
  804. * </pre>
  805. *
  806. * @param sheetIndex 0 based index to sheet.
  807. * @param startColumn 0 based start of repeating columns.
  808. * @param endColumn 0 based end of repeating columns.
  809. * @param startRow 0 based start of repeating rows.
  810. * @param endRow 0 based end of repeating rows.
  811. */
  812. public void setRepeatingRowsAndColumns(int sheetIndex,
  813. int startColumn, int endColumn,
  814. int startRow, int endRow)
  815. {
  816. // Check arguments
  817. if (startColumn == -1 && endColumn != -1) throw new IllegalArgumentException("Invalid column range specification");
  818. if (startRow == -1 && endRow != -1) throw new IllegalArgumentException("Invalid row range specification");
  819. if (startColumn < -1 || startColumn >= MAX_COLUMN) throw new IllegalArgumentException("Invalid column range specification");
  820. if (endColumn < -1 || endColumn >= MAX_COLUMN) throw new IllegalArgumentException("Invalid column range specification");
  821. if (startRow < -1 || startRow > MAX_ROW) throw new IllegalArgumentException("Invalid row range specification");
  822. if (endRow < -1 || endRow > MAX_ROW) throw new IllegalArgumentException("Invalid row range specification");
  823. if (startColumn > endColumn) throw new IllegalArgumentException("Invalid column range specification");
  824. if (startRow > endRow) throw new IllegalArgumentException("Invalid row range specification");
  825. HSSFSheet sheet = getSheetAt(sheetIndex);
  826. short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex);
  827. boolean settingRowAndColumn =
  828. startColumn != -1 && endColumn != -1 && startRow != -1 && endRow != -1;
  829. boolean removingRange =
  830. startColumn == -1 && endColumn == -1 && startRow == -1 && endRow == -1;
  831. int rowColHeaderNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_PRINT_TITLE);
  832. if (removingRange) {
  833. if (rowColHeaderNameIndex >= 0) {
  834. workbook.removeName(rowColHeaderNameIndex);
  835. }
  836. return;
  837. }
  838. boolean isNewRecord;
  839. NameRecord nameRecord;
  840. if (rowColHeaderNameIndex < 0) {
  841. //does a lot of the house keeping for builtin records, like setting lengths to zero etc
  842. nameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_TITLE, sheetIndex+1);
  843. isNewRecord = true;
  844. } else {
  845. nameRecord = workbook.getNameRecord(rowColHeaderNameIndex);
  846. isNewRecord = false;
  847. }
  848. List temp = new ArrayList();
  849. if (settingRowAndColumn) {
  850. final int exprsSize = 2 * 11 + 1; // 2 * Area3DPtg.SIZE + UnionPtg.SIZE
  851. temp.add(new MemFuncPtg(exprsSize));
  852. }
  853. if (startColumn >= 0) {
  854. Area3DPtg colArea = new Area3DPtg(0, MAX_ROW, startColumn, endColumn,
  855. false, false, false, false, externSheetIndex);
  856. temp.add(colArea);
  857. }
  858. if (startRow >= 0) {
  859. Area3DPtg rowArea = new Area3DPtg(startRow, endRow, 0, MAX_COLUMN,
  860. false, false, false, false, externSheetIndex);
  861. temp.add(rowArea);
  862. }
  863. if (settingRowAndColumn) {
  864. temp.add(UnionPtg.instance);
  865. }
  866. Ptg[] ptgs = new Ptg[temp.size()];
  867. temp.toArray(ptgs);
  868. nameRecord.setNameDefinition(ptgs);
  869. if (isNewRecord)
  870. {
  871. HSSFName newName = new HSSFName(this, nameRecord);
  872. names.add(newName);
  873. }
  874. HSSFPrintSetup printSetup = sheet.getPrintSetup();
  875. printSetup.setValidSettings(false);
  876. sheet.setActive(true);
  877. }
  878. private int findExistingBuiltinNameRecordIdx(int sheetIndex, byte builtinCode) {
  879. for(int defNameIndex =0; defNameIndex<names.size(); defNameIndex++) {
  880. NameRecord r = workbook.getNameRecord(defNameIndex);
  881. if (r == null) {
  882. throw new RuntimeException("Unable to find all defined names to iterate over");
  883. }
  884. if (!r.isBuiltInName() || r.getBuiltInName() != builtinCode) {
  885. continue;
  886. }
  887. if (r.getSheetNumber() -1 == sheetIndex) {
  888. return defNameIndex;
  889. }
  890. }
  891. return -1;
  892. }
  893. /**
  894. * create a new Font and add it to the workbook's font table
  895. * @return new font object
  896. */
  897. public HSSFFont createFont()
  898. {
  899. FontRecord font = workbook.createNewFont();
  900. short fontindex = (short) (getNumberOfFonts() - 1);
  901. if (fontindex > 3)
  902. {
  903. fontindex++; // THERE IS NO FOUR!!
  904. }
  905. if(fontindex == Short.MAX_VALUE){
  906. throw new IllegalArgumentException("Maximum number of fonts was exceeded");
  907. }
  908. // Ask getFontAt() to build it for us,
  909. // so it gets properly cached
  910. return getFontAt(fontindex);
  911. }
  912. /**
  913. * Finds a font that matches the one with the supplied attributes
  914. */
  915. public HSSFFont findFont(short boldWeight, short color, short fontHeight,
  916. String name, boolean italic, boolean strikeout,
  917. short typeOffset, byte underline)
  918. {
  919. for (short i=0; i<=getNumberOfFonts(); i++) {
  920. // Remember - there is no 4!
  921. if(i == 4) continue;
  922. HSSFFont hssfFont = getFontAt(i);
  923. if (hssfFont.getBoldweight() == boldWeight
  924. && hssfFont.getColor() == color
  925. && hssfFont.getFontHeight() == fontHeight
  926. && hssfFont.getFontName().equals(name)
  927. && hssfFont.getItalic() == italic
  928. && hssfFont.getStrikeout() == strikeout
  929. && hssfFont.getTypeOffset() == typeOffset
  930. && hssfFont.getUnderline() == underline)
  931. {
  932. return hssfFont;
  933. }
  934. }
  935. return null;
  936. }
  937. /**
  938. * get the number of fonts in the font table
  939. * @return number of fonts
  940. */
  941. public short getNumberOfFonts()
  942. {
  943. return (short) workbook.getNumberOfFontRecords();
  944. }
  945. /**
  946. * Get the font at the given index number
  947. * @param idx index number
  948. * @return HSSFFont at the index
  949. */
  950. public HSSFFont getFontAt(short idx) {
  951. if(fonts == null) fonts = new Hashtable();
  952. // So we don't confuse users, give them back
  953. // the same object every time, but create
  954. // them lazily
  955. Short sIdx = new Short(idx);
  956. if(fonts.containsKey(sIdx)) {
  957. return (HSSFFont)fonts.get(sIdx);
  958. }
  959. FontRecord font = workbook.getFontRecordAt(idx);
  960. HSSFFont retval = new HSSFFont(idx, font);
  961. fonts.put(sIdx, retval);
  962. return retval;
  963. }
  964. /**
  965. * Reset the fonts cache, causing all new calls
  966. * to getFontAt() to create new objects.
  967. * Should only be called after deleting fonts,
  968. * and that's not something you should normally do
  969. */
  970. protected void resetFontCache() {
  971. fonts = new Hashtable();
  972. }
  973. /**
  974. * create a new Cell style and add it to the workbook's style table
  975. * @return the new Cell Style object
  976. */
  977. public HSSFCellStyle createCellStyle()
  978. {
  979. ExtendedFormatRecord xfr = workbook.createCellXF();
  980. short index = (short) (getNumCellStyles() - 1);
  981. HSSFCellStyle style = new HSSFCellStyle(index, xfr, this);
  982. return style;
  983. }
  984. /**
  985. * get the number of styles the workbook contains
  986. * @return count of cell styles
  987. */
  988. public short getNumCellStyles()
  989. {
  990. return (short) workbook.getNumExFormats();
  991. }
  992. /**
  993. * get the cell style object at the given index
  994. * @param idx index within the set of styles
  995. * @return HSSFCellStyle object at the index
  996. */
  997. public HSSFCellStyle getCellStyleAt(short idx)
  998. {
  999. ExtendedFormatRecord xfr = workbook.getExFormatAt(idx);
  1000. HSSFCellStyle style = new HSSFCellStyle(idx, xfr, this);
  1001. return style;
  1002. }
  1003. /**
  1004. * Method write - write out this workbook to an Outputstream. Constructs
  1005. * a new POI POIFSFileSystem, passes in the workbook binary representation and
  1006. * writes it out.
  1007. *
  1008. * @param stream - the java OutputStream you wish to write the XLS to
  1009. *
  1010. * @exception IOException if anything can't be written.
  1011. * @see org.apache.poi.poifs.filesystem.POIFSFileSystem
  1012. */
  1013. public void write(OutputStream stream)
  1014. throws IOException
  1015. {
  1016. byte[] bytes = getBytes();
  1017. POIFSFileSystem fs = new POIFSFileSystem();
  1018. // For tracking what we've written out, used if we're
  1019. // going to be preserving nodes
  1020. List excepts = new ArrayList(1);
  1021. // Write out the Workbook stream
  1022. fs.createDocument(new ByteArrayInputStream(bytes), "Workbook");
  1023. // Write out our HPFS properties, if we have them
  1024. writeProperties(fs, excepts);
  1025. if (preserveNodes) {
  1026. // Don't write out the old Workbook, we'll be doing our new one
  1027. excepts.add("Workbook");
  1028. // If the file had WORKBOOK instead of Workbook, we'll write it
  1029. // out correctly shortly, so don't include the old one
  1030. excepts.add("WORKBOOK");
  1031. // Copy over all the other nodes to our new poifs
  1032. copyNodes(this.filesystem,fs,excepts);
  1033. }
  1034. fs.writeFilesystem(stream);
  1035. //poifs.writeFilesystem(stream);
  1036. }
  1037. /**
  1038. * Totals the sizes of all sheet records and eventually serializes them
  1039. */
  1040. private static final class SheetRecordCollector implements RecordVisitor {
  1041. private List _list;
  1042. private int _totalSize;
  1043. public SheetRecordCollector() {
  1044. _totalSize = 0;
  1045. _list = new ArrayList(128);
  1046. }
  1047. public int getTotalSize() {
  1048. return _totalSize;
  1049. }
  1050. public void visitRecord(Record r) {
  1051. _list.add(r);
  1052. _totalSize+=r.getRecordSize();
  1053. }
  1054. public int serialize(int offset, byte[] data) {
  1055. int result = 0;
  1056. int nRecs = _list.size();
  1057. for(int i=0; i<nRecs; i++) {
  1058. Record rec = (Record)_list.get(i);
  1059. result += rec.serialize(offset + result, data);
  1060. }
  1061. return result;
  1062. }
  1063. }
  1064. /**
  1065. * Method getBytes - get the bytes of just the HSSF portions of the XLS file.
  1066. * Use this to construct a POI POIFSFileSystem yourself.
  1067. *
  1068. *
  1069. * @return byte[] array containing the binary representation of this workbook and all contained
  1070. * sheets, rows, cells, etc.
  1071. *
  1072. * @see org.apache.poi.hssf.model.Workbook
  1073. * @see org.apache.poi.hssf.model.Sheet
  1074. */
  1075. public byte[] getBytes() {
  1076. if (log.check( POILogger.DEBUG )) {
  1077. log.log(DEBUG, "HSSFWorkbook.getBytes()");
  1078. }
  1079. HSSFSheet[] sheets = getSheets();
  1080. int nSheets = sheets.length;
  1081. // before getting the workbook size we must tell the sheets that
  1082. // serialization is about to occur.
  1083. for (int i = 0; i < nSheets; i++) {
  1084. sheets[i].getSheet().preSerialize();
  1085. }
  1086. int totalsize = workbook.getSize();
  1087. // pre-calculate all the sheet sizes and set BOF indexes
  1088. SheetRecordCollector[] srCollectors = new SheetRecordCollector[nSheets];
  1089. for (int k = 0; k < nSheets; k++) {
  1090. workbook.setSheetBof(k, totalsize);
  1091. SheetRecordCollector src = new SheetRecordCollector();
  1092. sheets[k].getSheet().visitContainedRecords(src, totalsize);
  1093. totalsize += src.getTotalSize();
  1094. srCollectors[k] = src;
  1095. }
  1096. byte[] retval = new byte[totalsize];
  1097. int pos = workbook.serialize(0, retval);
  1098. for (int k = 0; k < nSheets; k++) {
  1099. SheetRecordCollector src = srCollectors[k];
  1100. int serializedSize = src.serialize(pos, retval);
  1101. if (serializedSize != src.getTotalSize()) {
  1102. // Wrong offset values have been passed in the call to setSheetBof() above.
  1103. // For books with more than one sheet, this discrepancy would cause excel
  1104. // to report errors and loose data while reading the workbook
  1105. throw new IllegalStateException("Actual serialized sheet size (" + serializedSize
  1106. + ") differs from pre-calculated size (" + src.getTotalSize()
  1107. + ") for sheet (" + k + ")");
  1108. // TODO - add similar sanity check to ensure that Sheet.serializeIndexRecord() does not write mis-aligned offsets either
  1109. }
  1110. pos += serializedSize;
  1111. }
  1112. return retval;
  1113. }
  1114. /** @deprecated Do not call this method from your applications. Use the methods
  1115. * available in the HSSFRow to add string HSSFCells
  1116. */
  1117. public int addSSTString(String string)
  1118. {
  1119. return workbook.addSSTString(new UnicodeString(string));
  1120. }
  1121. /** @deprecated Do not call this method from your applications. Use the methods
  1122. * available in the HSSFRow to get string HSSFCells
  1123. */
  1124. public String getSSTString(int index)
  1125. {
  1126. return workbook.getSSTString(index).getString();
  1127. }
  1128. protected Workbook getWorkbook()
  1129. {
  1130. return workbook;
  1131. }
  1132. public int getNumberOfNames(){
  1133. int result = names.size();
  1134. return result;
  1135. }
  1136. public HSSFName getName(String name) {
  1137. int nameIndex = getNameIndex(name);
  1138. if (nameIndex < 0) {
  1139. return null;
  1140. }
  1141. return (HSSFName) names.get(nameIndex);
  1142. }
  1143. public HSSFName getNameAt(int nameIndex) {
  1144. int nNames = names.size();
  1145. if (nNames < 1) {
  1146. throw new IllegalStateException("There are no defined names in this workbook");
  1147. }
  1148. if (nameIndex < 0 || nameIndex > nNames) {
  1149. throw new IllegalArgumentException("Specified name index " + nameIndex
  1150. + " is outside the allowable range (0.." + (nNames-1) + ").");
  1151. }
  1152. return (HSSFName) names.get(nameIndex);
  1153. }
  1154. public NameRecord getNameRecord(int nameIndex) {
  1155. return getWorkbook().getNameRecord(nameIndex);
  1156. }
  1157. /** gets the named range name
  1158. * @param index the named range index (0 based)
  1159. * @return named range name
  1160. */
  1161. public String getNameName(int index){
  1162. String result = getNameAt(index).getNameName();
  1163. return result;
  1164. }
  1165. /**
  1166. * Sets the printarea for the sheet provided
  1167. * <p>
  1168. * i.e. Reference = $A$1:$B$2
  1169. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  1170. * @param reference Valid name Reference for the Print Area
  1171. */
  1172. public void setPrintArea(int sheetIndex, String reference)
  1173. {
  1174. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1175. if (name == null) {
  1176. name = workbook.createBuiltInName(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1177. // adding one here because 0 indicates a global named region; doesn't make sense for print areas
  1178. }
  1179. String[] parts = COMMA_PATTERN.split(reference);
  1180. StringBuffer sb = new StringBuffer(32);
  1181. for (int i = 0; i < parts.length; i++) {
  1182. if(i>0) {
  1183. sb.append(",");
  1184. }
  1185. SheetNameFormatter.appendFormat(sb, getSheetName(sheetIndex));
  1186. sb.append("!");
  1187. sb.append(parts[i]);
  1188. }
  1189. name.setNameDefinition(HSSFFormulaParser.parse(sb.toString(), this, FormulaType.CELL, sheetIndex));
  1190. }
  1191. /**
  1192. * For the Convenience of Java Programmers maintaining pointers.
  1193. * @see #setPrintArea(int, String)
  1194. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  1195. * @param startColumn Column to begin printarea
  1196. * @param endColumn Column to end the printarea
  1197. * @param startRow Row to begin the printarea
  1198. * @param endRow Row to end the printarea
  1199. */
  1200. public void setPrintArea(int sheetIndex, int startColumn, int endColumn,
  1201. int startRow, int endRow) {
  1202. //using absolute references because they don't get copied and pasted anyway
  1203. CellReference cell = new CellReference(startRow, startColumn, true, true);
  1204. String reference = cell.formatAsString();
  1205. cell = new CellReference(endRow, endColumn, true, true);
  1206. reference = reference+":"+cell.formatAsString();
  1207. setPrintArea(sheetIndex, reference);
  1208. }
  1209. /**
  1210. * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified.
  1211. * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java)
  1212. * @return String Null if no print area has been defined
  1213. */
  1214. public String getPrintArea(int sheetIndex) {
  1215. NameRecord name = workbook.getSpecificBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1216. //adding one here because 0 indicates a global named region; doesn't make sense for print areas
  1217. if (name == null) {
  1218. return null;
  1219. }
  1220. return HSSFFormulaParser.toFormulaString(this, name.getNameDefinition());
  1221. }
  1222. /**
  1223. * Delete the printarea for the sheet specified
  1224. * @param sheetIndex Zero-based sheet index (0 = First Sheet)
  1225. */
  1226. public void removePrintArea(int sheetIndex) {
  1227. getWorkbook().removeBuiltinRecord(NameRecord.BUILTIN_PRINT_AREA, sheetIndex+1);
  1228. }
  1229. /** creates a new named range and add it to the model
  1230. * @return named range high level
  1231. */
  1232. public HSSFName createName(){
  1233. NameRecord nameRecord = workbook.createName();
  1234. HSSFName newName = new HSSFName(this, nameRecord);
  1235. names.add(newName);
  1236. return newName;
  1237. }
  1238. public int getNameIndex(String name) {
  1239. for (int k = 0; k < names.size(); k++) {
  1240. String nameName = getNameName(k);
  1241. if (nameName.equalsIgnoreCase(name)) {
  1242. return k;
  1243. }
  1244. }
  1245. return -1;
  1246. }
  1247. public void removeName(int index){
  1248. names.remove(index);
  1249. workbook.removeName(index);
  1250. }
  1251. /**
  1252. * Returns the instance of HSSFDataFormat for this workbook.
  1253. * @return the HSSFDataFormat object
  1254. * @see org.apache.poi.hssf.record.FormatRecord
  1255. * @see org.apache.poi.hssf.record.Record
  1256. */
  1257. public HSSFDataFormat createDataFormat() {
  1258. if (formatter == null)
  1259. formatter = new HSSFDataFormat(workbook);
  1260. return formatter;
  1261. }
  1262. public void removeName(String name) {
  1263. int index = getNameIndex(name);
  1264. removeName(index);
  1265. }
  1266. public HSSFPalette getCustomPalette()
  1267. {
  1268. return new HSSFPalette(workbook.getCustomPalette());
  1269. }
  1270. /** Test only. Do not use */
  1271. public void insertChartRecord()
  1272. {
  1273. int loc = workbook.findFirstRecordLocBySid(SSTRecord.sid);
  1274. byte[] data = {
  1275. (byte)0x0F, (byte)0x00, (byte)0x00, (byte)0xF0, (byte)0x52,
  1276. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
  1277. (byte)0x06, (byte)0xF0, (byte)0x18, (byte)0x00, (byte)0x00,
  1278. (byte)0x00, (byte)0x01, (byte)0x08, (byte)0x00, (byte)0x00,
  1279. (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02,
  1280. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00,
  1281. (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00,
  1282. (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x00, (byte)0x00,
  1283. (byte)0x33, (byte)0x00, (byte)0x0B, (byte)0xF0, (byte)0x12,
  1284. (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xBF, (byte)0x00,
  1285. (byte)0x08, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x81,
  1286. (byte)0x01, (byte)0x09, (byte)0x00, (byte)0x00, (byte)0x08,
  1287. (byte)0xC0, (byte)0x01, (byte)0x40, (byte)0x00, (byte)0x00,
  1288. (byte)0x08, (byte)0x40, (byte)0x00, (byte)0x1E, (byte)0xF1,
  1289. (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0D,
  1290. (byte)0x00, (byte)0x00, (byte)0x08, (byte)0x0C, (byte)0x00,
  1291. (byte)0x00, (byte)0x08, (byte)0x17, (byte)0x00, (byte)0x00,
  1292. (byte)0x08, (byte)0xF7, (byte)0x00, (byte)0x00, (byte)0x10,
  1293. };
  1294. UnknownRecord r = new UnknownRecord((short)0x00EB, data);
  1295. workbook.getRecords().add(loc, r);
  1296. }
  1297. /**
  1298. * Spits out a list of all the drawing records in the workbook.
  1299. */
  1300. public void dumpDrawingGroupRecords(boolean fat)
  1301. {
  1302. DrawingGroupRecord r = (DrawingGroupRecord) workbook.findFirstRecordBySid( DrawingGroupRecord.sid );
  1303. r.decode();
  1304. List escherRecords = r.getEscherRecords();
  1305. PrintWriter w = new PrintWriter(System.out);
  1306. for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
  1307. {
  1308. EscherRecord escherRecord = (EscherRecord) iterator.next();
  1309. if (fat)
  1310. System.out.println(escherRecord.toString());
  1311. else
  1312. escherRecord.display(w, 0);
  1313. }
  1314. w.flush();
  1315. }
  1316. /**
  1317. * Adds a picture to the workbook.
  1318. *
  1319. * @param pictureData The bytes of the picture
  1320. * @param format The format of the picture. One of <code>PICTURE_TYPE_*</code>
  1321. *
  1322. * @return the index to this picture (1 based).
  1323. */
  1324. public int addPicture(byte[] pictureData, int format)
  1325. {
  1326. byte[] uid = newUID();
  1327. EscherBitmapBlip blipRecord = new EscherBitmapBlip();
  1328. blipRecord.setRecordId( (short) ( EscherBitmapBlip.RECORD_ID_START + format ) );
  1329. switch (format)
  1330. {
  1331. case PICTURE_TYPE_EMF:
  1332. blipRecord.setOptions(HSSFPictureData.MSOBI_EMF);
  1333. break;
  1334. case PICTURE_TYPE_WMF:
  1335. blipRecord.setOptions(HSSFPictureData.MSOBI_WMF);
  1336. break;
  1337. case PICTURE_TYPE_PICT:
  1338. blipRecord.setOptions(HSSFPictureData.MSOBI_PICT);
  1339. break;
  1340. case PICTURE_TYPE_PNG:
  1341. blipRecord.setOptions(HSSFPictureData.MSOBI_PNG);
  1342. break;
  1343. case HSSFWorkbook.PICTURE_TYPE_JPEG:
  1344. blipRecord.setOptions(HSSFPictureData.MSOBI_JPEG);
  1345. break;
  1346. case HSSFWorkbook.PICTURE_TYPE_DIB:
  1347. blipRecord.setOptions(HSSFPictureData.MSOBI_DIB);
  1348. break;
  1349. }
  1350. blipRecord.setUID( uid );
  1351. blipRecord.setMarker( (byte) 0xFF );
  1352. blipRecord.setPictureData( pictureData );
  1353. EscherBSERecord r = new EscherBSERecord();
  1354. r.setRecordId( EscherBSERecord.RECORD_ID );
  1355. r.setOptions( (short) ( 0x0002 | ( format << 4 ) ) );
  1356. r.setBlipTypeMacOS( (byte) format );
  1357. r.setBlipTypeWin32( (byte) format );
  1358. r.setUid( uid );
  1359. r.setTag( (short) 0xFF );
  1360. r.setSize( pictureData.length + 25 );
  1361. r.setRef( 1 );
  1362. r.setOffset( 0 );
  1363. r.setBlipRecord( blipRecord );
  1364. return workbook.addBSERecord( r );
  1365. }
  1366. /**
  1367. * Gets all pictures from the Workbook.
  1368. *
  1369. * @return the list of pictures (a list of {@link HSSFPictureData} objects.)
  1370. */
  1371. public List<HSSFPictureData> getAllPictures()
  1372. {
  1373. // The drawing group record always exists at the top level, so we won't need to do this recursively.
  1374. List<HSSFPictureData> pictures = new ArrayList<HSSFPictureData>();
  1375. Iterator recordIter = workbook.getRecords().iterator();
  1376. while (recordIter.hasNext())
  1377. {
  1378. Object obj = recordIter.next();
  1379. if (obj instanceof AbstractEscherHolderRecord)
  1380. {
  1381. ((AbstractEscherHolderRecord) obj).decode();
  1382. List escherRecords = ((AbstractEscherHolderRecord) obj).getEscherRecords();
  1383. searchForPictures(escherRecords, pictures);
  1384. }
  1385. }
  1386. return pictures;
  1387. }
  1388. /**
  1389. * Performs a recursive search for pictures in the given list of escher records.
  1390. *
  1391. * @param escherRecords the escher records.
  1392. * @param pictures the list to populate with the pictures.
  1393. */
  1394. private void searchForPictures(List escherRecords, List<HSSFPictureData> pictures)
  1395. {
  1396. Iterator recordIter = escherRecords.iterator();
  1397. while (recordIter.hasNext())
  1398. {
  1399. Object obj = recordIter.next();
  1400. if (obj instanceof EscherRecord)
  1401. {
  1402. EscherRecord escherRecord = (EscherRecord) obj;
  1403. if (escherRecord instanceof EscherBSERecord)
  1404. {
  1405. EscherBlipRecord blip = ((EscherBSERecord) escherRecord).getBlipRecord();
  1406. if (blip != null)
  1407. {
  1408. // TODO: Some kind of structure.
  1409. pictures.add(new HSSFPictureData(blip));
  1410. }
  1411. }
  1412. // Recursive call.
  1413. searchForPictures(escherRecord.getChildRecords(), pictures);
  1414. }
  1415. }
  1416. }
  1417. public FreeRefFunction getUserDefinedFunction(String functionName) {
  1418. return udfFunctions.get(functionName);
  1419. }
  1420. public void registerUserDefinedFunction(String functionName, FreeRefFunction freeRefFunction) {
  1421. Name udfDeclaration = getName(functionName);
  1422. if (udfDeclaration == null) {
  1423. udfDeclaration = createName();
  1424. }
  1425. udfDeclaration.setNameName(functionName);
  1426. udfDeclaration.setFunction(true);
  1427. udfFunctions.put(functionName, freeRefFunction);
  1428. }
  1429. public List<String> getUserDefinedFunctionNames() {
  1430. return new ArrayList<String>(udfFunctions.keySet());
  1431. }
  1432. /**
  1433. * Is the workbook protected with a password (not encrypted)?
  1434. */
  1435. public boolean isWriteProtected() {
  1436. return this.workbook.isWriteProtected();
  1437. }
  1438. /**
  1439. * protect a workbook with a password (not encypted, just sets writeprotect
  1440. * flags and the password.
  1441. * @param password to set
  1442. */
  1443. public void writeProtectWorkbook( String password, String username ) {
  1444. this.workbook.writeProtectWorkbook(password, username);
  1445. }
  1446. /**
  1447. * removes the write protect flag
  1448. */
  1449. public void unwriteProtectWorkbook() {
  1450. this.workbook.unwriteProtectWorkbook();
  1451. }
  1452. /**
  1453. * Gets all embedded OLE2 objects from the Workbook.
  1454. *
  1455. * @return the list of embedded objects (a list of {@link HSSFObjectData} objects.)
  1456. */
  1457. public List<HSSFObjectData> getAllEmbeddedObjects()
  1458. {
  1459. List<HSSFObjectData> objects = new ArrayList<HSSFObjectData>();
  1460. for (int i = 0; i < getNumberOfSheets(); i++)
  1461. {
  1462. getAllEmbeddedObjects(getSheetAt(i).getSheet().getRecords(), objects);
  1463. }
  1464. return objects;
  1465. }
  1466. /**
  1467. * Gets all embedded OLE2 objects from the Workbook.
  1468. *
  1469. * @param records the list of records to search.
  1470. * @param objects the list of embedded objects to populate.
  1471. */
  1472. private void getAllEmbeddedObjects(List records, List<HSSFObjectData> objects)
  1473. {
  1474. Iterator recordIter = records.iterator();
  1475. while (recordIter.hasNext())
  1476. {
  1477. Object obj = recordIter.next();
  1478. if (obj instanceof ObjRecord)
  1479. {
  1480. // TODO: More convenient way of determining if there is stored binary.
  1481. // TODO: Link to the data stored in the other stream.
  1482. Iterator subRecordIter = ((ObjRecord) obj).getSubRecords().iterator();
  1483. while (subRecordIter.hasNext())
  1484. {
  1485. Object sub = subRecordIter.next();
  1486. if (sub instanceof EmbeddedObjectRefSubRecord)
  1487. {
  1488. objects.add(new HSSFObjectData((ObjRecord) obj, filesystem));
  1489. }
  1490. }
  1491. }
  1492. }
  1493. }
  1494. public CreationHelper getCreationHelper() {
  1495. return new HSSFCreationHelper(this);
  1496. }
  1497. private static byte[] newUID() {
  1498. return new byte[16];
  1499. }
  1500. /**
  1501. * Note - This method should only used by POI internally.
  1502. * It may get deleted or change definition in future POI versions
  1503. */
  1504. public NameXPtg getNameXPtg(String name) {
  1505. return workbook.getNameXPtg(name);
  1506. }
  1507. }