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.

InternalWorkbook.java 89KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455
  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.model;
  16. import java.security.AccessControlException;
  17. import java.util.ArrayList;
  18. import java.util.Iterator;
  19. import java.util.LinkedHashMap;
  20. import java.util.List;
  21. import java.util.Locale;
  22. import java.util.Map;
  23. import java.util.Map.Entry;
  24. import org.apache.poi.ddf.*;
  25. import org.apache.poi.hssf.record.*;
  26. import org.apache.poi.hssf.record.common.UnicodeString;
  27. import org.apache.poi.hssf.util.HSSFColor;
  28. import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalName;
  29. import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalSheet;
  30. import org.apache.poi.ss.formula.FormulaShifter;
  31. import org.apache.poi.ss.formula.ptg.Area3DPtg;
  32. import org.apache.poi.ss.formula.ptg.NameXPtg;
  33. import org.apache.poi.ss.formula.ptg.OperandPtg;
  34. import org.apache.poi.ss.formula.ptg.Ptg;
  35. import org.apache.poi.ss.formula.ptg.Ref3DPtg;
  36. import org.apache.poi.ss.formula.udf.UDFFinder;
  37. import org.apache.poi.ss.usermodel.BuiltinFormats;
  38. import org.apache.poi.util.Internal;
  39. import org.apache.poi.util.POILogFactory;
  40. import org.apache.poi.util.POILogger;
  41. /**
  42. * Low level model implementation of a Workbook. Provides creational methods
  43. * for settings and objects contained in the workbook object.
  44. * <P>
  45. * This file contains the low level binary records starting at the workbook's BOF and
  46. * ending with the workbook's EOF. Use HSSFWorkbook for a high level representation.
  47. * <P>
  48. * The structures of the highlevel API use references to this to perform most of their
  49. * operations. Its probably unwise to use these low level structures directly unless you
  50. * really know what you're doing. I recommend you read the Microsoft Excel 97 Developer's
  51. * Kit (Microsoft Press) and the documentation at http://sc.openoffice.org/excelfileformat.pdf
  52. * before even attempting to use this.
  53. *
  54. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook
  55. */
  56. @Internal
  57. public final class InternalWorkbook {
  58. /**
  59. * Excel silently truncates long sheet names to 31 chars.
  60. * This constant is used to ensure uniqueness in the first 31 chars
  61. */
  62. private static final int MAX_SENSITIVE_SHEET_NAME_LEN = 31;
  63. private static final POILogger log = POILogFactory.getLogger(InternalWorkbook.class);
  64. private static final int DEBUG = POILogger.DEBUG;
  65. /**
  66. * constant used to set the "codepage" wherever "codepage" is set in records
  67. * (which is duplicated in more than one record)
  68. */
  69. private final static short CODEPAGE = 0x04B0;
  70. /**
  71. * this contains the Worksheet record objects
  72. */
  73. private final WorkbookRecordList records;
  74. /**
  75. * this contains a reference to the SSTRecord so that new stings can be added
  76. * to it.
  77. */
  78. protected SSTRecord sst;
  79. private LinkTable linkTable; // optionally occurs if there are references in the document. (4.10.3)
  80. /**
  81. * holds the "boundsheet" records (aka bundlesheet) so that they can have their
  82. * reference to their "BOF" marker
  83. */
  84. private final List<BoundSheetRecord> boundsheets;
  85. private final List<FormatRecord> formats;
  86. private final List<HyperlinkRecord> hyperlinks;
  87. /** the number of extended format records */
  88. private int numxfs;
  89. /** the number of font records */
  90. private int numfonts;
  91. /** holds the max format id */
  92. private int maxformatid;
  93. /** whether 1904 date windowing is being used */
  94. private boolean uses1904datewindowing;
  95. private DrawingManager2 drawingManager;
  96. private List<EscherBSERecord> escherBSERecords;
  97. private WindowOneRecord windowOne;
  98. private FileSharingRecord fileShare;
  99. private WriteAccessRecord writeAccess;
  100. private WriteProtectRecord writeProtect;
  101. /**
  102. * Hold the {@link NameCommentRecord}s indexed by the name of the {@link NameRecord} to which they apply.
  103. */
  104. private final Map<String, NameCommentRecord> commentRecords;
  105. private InternalWorkbook() {
  106. records = new WorkbookRecordList();
  107. boundsheets = new ArrayList<BoundSheetRecord>();
  108. formats = new ArrayList<FormatRecord>();
  109. hyperlinks = new ArrayList<HyperlinkRecord>();
  110. numxfs = 0;
  111. numfonts = 0;
  112. maxformatid = -1;
  113. uses1904datewindowing = false;
  114. escherBSERecords = new ArrayList<EscherBSERecord>();
  115. commentRecords = new LinkedHashMap<String, NameCommentRecord>();
  116. }
  117. /**
  118. * read support for low level
  119. * API. Pass in an array of Record objects, A Workbook
  120. * object is constructed and passed back with all of its initialization set
  121. * to the passed in records and references to those records held. Unlike Sheet
  122. * workbook does not use an offset (its assumed to be 0) since its first in a file.
  123. * If you need an offset then construct a new array with a 0 offset or write your
  124. * own ;-p.
  125. *
  126. * @param recs an array of Record objects
  127. * @return Workbook object
  128. */
  129. public static InternalWorkbook createWorkbook(List<Record> recs) {
  130. if (log.check( POILogger.DEBUG ))
  131. log.log(DEBUG, "Workbook (readfile) created with reclen=",
  132. Integer.valueOf(recs.size()));
  133. InternalWorkbook retval = new InternalWorkbook();
  134. List<Record> records = new ArrayList<Record>(recs.size() / 3);
  135. retval.records.setRecords(records);
  136. int k;
  137. for (k = 0; k < recs.size(); k++) {
  138. Record rec = recs.get(k);
  139. if (rec.getSid() == EOFRecord.sid) {
  140. records.add(rec);
  141. if (log.check( POILogger.DEBUG ))
  142. log.log(DEBUG, "found workbook eof record at " + k);
  143. break;
  144. }
  145. switch (rec.getSid()) {
  146. case BoundSheetRecord.sid :
  147. if (log.check( POILogger.DEBUG ))
  148. log.log(DEBUG, "found boundsheet record at " + k);
  149. retval.boundsheets.add((BoundSheetRecord) rec);
  150. retval.records.setBspos( k );
  151. break;
  152. case SSTRecord.sid :
  153. if (log.check( POILogger.DEBUG ))
  154. log.log(DEBUG, "found sst record at " + k);
  155. retval.sst = ( SSTRecord ) rec;
  156. break;
  157. case FontRecord.sid :
  158. if (log.check( POILogger.DEBUG ))
  159. log.log(DEBUG, "found font record at " + k);
  160. retval.records.setFontpos( k );
  161. retval.numfonts++;
  162. break;
  163. case ExtendedFormatRecord.sid :
  164. if (log.check( POILogger.DEBUG ))
  165. log.log(DEBUG, "found XF record at " + k);
  166. retval.records.setXfpos( k );
  167. retval.numxfs++;
  168. break;
  169. case TabIdRecord.sid :
  170. if (log.check( POILogger.DEBUG ))
  171. log.log(DEBUG, "found tabid record at " + k);
  172. retval.records.setTabpos( k );
  173. break;
  174. case ProtectRecord.sid :
  175. if (log.check( POILogger.DEBUG ))
  176. log.log(DEBUG, "found protect record at " + k);
  177. retval.records.setProtpos( k );
  178. break;
  179. case BackupRecord.sid :
  180. if (log.check( POILogger.DEBUG ))
  181. log.log(DEBUG, "found backup record at " + k);
  182. retval.records.setBackuppos( k );
  183. break;
  184. case ExternSheetRecord.sid :
  185. throw new RuntimeException("Extern sheet is part of LinkTable");
  186. case NameRecord.sid :
  187. case SupBookRecord.sid :
  188. // LinkTable can start with either of these
  189. if (log.check( POILogger.DEBUG ))
  190. log.log(DEBUG, "found SupBook record at " + k);
  191. retval.linkTable = new LinkTable(recs, k, retval.records, retval.commentRecords);
  192. k+=retval.linkTable.getRecordCount() - 1;
  193. continue;
  194. case FormatRecord.sid :
  195. if (log.check( POILogger.DEBUG ))
  196. log.log(DEBUG, "found format record at " + k);
  197. retval.formats.add((FormatRecord) rec);
  198. retval.maxformatid = retval.maxformatid >= ((FormatRecord)rec).getIndexCode() ? retval.maxformatid : ((FormatRecord)rec).getIndexCode();
  199. break;
  200. case DateWindow1904Record.sid :
  201. if (log.check( POILogger.DEBUG ))
  202. log.log(DEBUG, "found datewindow1904 record at " + k);
  203. retval.uses1904datewindowing = ((DateWindow1904Record)rec).getWindowing() == 1;
  204. break;
  205. case PaletteRecord.sid:
  206. if (log.check( POILogger.DEBUG ))
  207. log.log(DEBUG, "found palette record at " + k);
  208. retval.records.setPalettepos( k );
  209. break;
  210. case WindowOneRecord.sid:
  211. if (log.check( POILogger.DEBUG ))
  212. log.log(DEBUG, "found WindowOneRecord at " + k);
  213. retval.windowOne = (WindowOneRecord) rec;
  214. break;
  215. case WriteAccessRecord.sid:
  216. if (log.check( POILogger.DEBUG ))
  217. log.log(DEBUG, "found WriteAccess at " + k);
  218. retval.writeAccess = (WriteAccessRecord) rec;
  219. break;
  220. case WriteProtectRecord.sid:
  221. if (log.check( POILogger.DEBUG ))
  222. log.log(DEBUG, "found WriteProtect at " + k);
  223. retval.writeProtect = (WriteProtectRecord) rec;
  224. break;
  225. case FileSharingRecord.sid:
  226. if (log.check( POILogger.DEBUG ))
  227. log.log(DEBUG, "found FileSharing at " + k);
  228. retval.fileShare = (FileSharingRecord) rec;
  229. break;
  230. case NameCommentRecord.sid:
  231. final NameCommentRecord ncr = (NameCommentRecord) rec;
  232. if (log.check( POILogger.DEBUG ))
  233. log.log(DEBUG, "found NameComment at " + k);
  234. retval.commentRecords.put(ncr.getNameText(), ncr);
  235. default :
  236. }
  237. records.add(rec);
  238. }
  239. //What if we dont have any ranges and supbooks
  240. // if (retval.records.supbookpos == 0) {
  241. // retval.records.supbookpos = retval.records.bspos + 1;
  242. // retval.records.namepos = retval.records.supbookpos + 1;
  243. // }
  244. // Look for other interesting values that
  245. // follow the EOFRecord
  246. for ( ; k < recs.size(); k++) {
  247. Record rec = recs.get(k);
  248. switch (rec.getSid()) {
  249. case HyperlinkRecord.sid:
  250. retval.hyperlinks.add((HyperlinkRecord)rec);
  251. break;
  252. }
  253. }
  254. if (retval.windowOne == null) {
  255. retval.windowOne = createWindowOne();
  256. }
  257. if (log.check( POILogger.DEBUG ))
  258. log.log(DEBUG, "exit create workbook from existing file function");
  259. return retval;
  260. }
  261. /**
  262. * Creates an empty workbook object with three blank sheets and all the empty
  263. * fields. Use this to create a workbook from scratch.
  264. */
  265. public static InternalWorkbook createWorkbook()
  266. {
  267. if (log.check( POILogger.DEBUG ))
  268. log.log( DEBUG, "creating new workbook from scratch" );
  269. InternalWorkbook retval = new InternalWorkbook();
  270. List<Record> records = new ArrayList<Record>( 30 );
  271. retval.records.setRecords(records);
  272. List<FormatRecord> formats = retval.formats;
  273. records.add(createBOF());
  274. records.add(new InterfaceHdrRecord(CODEPAGE));
  275. records.add(createMMS());
  276. records.add(InterfaceEndRecord.instance);
  277. records.add(createWriteAccess());
  278. records.add(createCodepage());
  279. records.add(createDSF());
  280. records.add(createTabId());
  281. retval.records.setTabpos(records.size() - 1);
  282. records.add(createFnGroupCount());
  283. records.add(createWindowProtect());
  284. records.add(createProtect());
  285. retval.records.setProtpos(records.size() - 1);
  286. records.add(createPassword());
  287. records.add(createProtectionRev4());
  288. records.add(createPasswordRev4());
  289. retval.windowOne = createWindowOne();
  290. records.add(retval.windowOne);
  291. records.add(createBackup());
  292. retval.records.setBackuppos(records.size() - 1);
  293. records.add(createHideObj());
  294. records.add(createDateWindow1904());
  295. records.add(createPrecision());
  296. records.add(createRefreshAll());
  297. records.add(createBookBool());
  298. records.add(createFont());
  299. records.add(createFont());
  300. records.add(createFont());
  301. records.add(createFont());
  302. retval.records.setFontpos( records.size() - 1 ); // last font record position
  303. retval.numfonts = 4;
  304. // set up format records
  305. for (int i = 0; i <= 7; i++) {
  306. FormatRecord rec = createFormat(i);
  307. retval.maxformatid = retval.maxformatid >= rec.getIndexCode() ? retval.maxformatid : rec.getIndexCode();
  308. formats.add(rec);
  309. records.add(rec);
  310. }
  311. for (int k = 0; k < 21; k++) {
  312. records.add(InternalWorkbook.createExtendedFormat(k));
  313. retval.numxfs++;
  314. }
  315. retval.records.setXfpos( records.size() - 1 );
  316. for (int k = 0; k < 6; k++) {
  317. records.add(InternalWorkbook.createStyle(k));
  318. }
  319. records.add(InternalWorkbook.createUseSelFS());
  320. int nBoundSheets = 1; // now just do 1
  321. for (int k = 0; k < nBoundSheets; k++) {
  322. BoundSheetRecord bsr = createBoundSheet(k);
  323. records.add(bsr);
  324. retval.boundsheets.add(bsr);
  325. retval.records.setBspos(records.size() - 1);
  326. }
  327. records.add( InternalWorkbook.createCountry() );
  328. for ( int k = 0; k < nBoundSheets; k++ ) {
  329. retval.getOrCreateLinkTable().checkExternSheet(k);
  330. }
  331. retval.sst = new SSTRecord();
  332. records.add(retval.sst);
  333. records.add(InternalWorkbook.createExtendedSST());
  334. records.add(EOFRecord.instance);
  335. if (log.check( POILogger.DEBUG ))
  336. log.log( DEBUG, "exit create new workbook from scratch" );
  337. return retval;
  338. }
  339. /**Retrieves the Builtin NameRecord that matches the name and index
  340. * There shouldn't be too many names to make the sequential search too slow
  341. * @param name byte representation of the builtin name to match
  342. * @param sheetNumber 1-based sheet number
  343. * @return null if no builtin NameRecord matches
  344. */
  345. public NameRecord getSpecificBuiltinRecord(byte name, int sheetNumber)
  346. {
  347. return getOrCreateLinkTable().getSpecificBuiltinRecord(name, sheetNumber);
  348. }
  349. /**
  350. * Removes the specified Builtin NameRecord that matches the name and index
  351. * @param name byte representation of the builtin to match
  352. * @param sheetIndex zero-based sheet reference
  353. */
  354. public void removeBuiltinRecord(byte name, int sheetIndex) {
  355. linkTable.removeBuiltinRecord(name, sheetIndex);
  356. // TODO - do we need "this.records.remove(...);" similar to that in this.removeName(int namenum) {}?
  357. }
  358. public int getNumRecords() {
  359. return records.size();
  360. }
  361. /**
  362. * gets the font record at the given index in the font table. Remember
  363. * "There is No Four" (someone at M$ must have gone to Rocky Horror one too
  364. * many times)
  365. *
  366. * @param idx the index to look at (0 or greater but NOT 4)
  367. * @return FontRecord located at the given index
  368. */
  369. public FontRecord getFontRecordAt(int idx) {
  370. int index = idx;
  371. if (index > 4) {
  372. index -= 1; // adjust for "There is no 4"
  373. }
  374. if (index > (numfonts - 1)) {
  375. throw new ArrayIndexOutOfBoundsException(
  376. "There are only " + numfonts
  377. + " font records, you asked for " + idx);
  378. }
  379. FontRecord retval =
  380. ( FontRecord ) records.get((records.getFontpos() - (numfonts - 1)) + index);
  381. return retval;
  382. }
  383. /**
  384. * Retrieves the index of the given font
  385. */
  386. public int getFontIndex(FontRecord font) {
  387. for(int i=0; i<=numfonts; i++) {
  388. FontRecord thisFont =
  389. ( FontRecord ) records.get((records.getFontpos() - (numfonts - 1)) + i);
  390. if(thisFont == font) {
  391. // There is no 4!
  392. if(i > 3) {
  393. return (i+1);
  394. }
  395. return i;
  396. }
  397. }
  398. throw new IllegalArgumentException("Could not find that font!");
  399. }
  400. /**
  401. * creates a new font record and adds it to the "font table". This causes the
  402. * boundsheets to move down one, extended formats to move down (so this function moves
  403. * those pointers as well)
  404. *
  405. * @return FontRecord that was just created
  406. */
  407. public FontRecord createNewFont() {
  408. FontRecord rec = createFont();
  409. records.add(records.getFontpos()+1, rec);
  410. records.setFontpos( records.getFontpos() + 1 );
  411. numfonts++;
  412. return rec;
  413. }
  414. /**
  415. * Removes the given font record from the
  416. * file's list. This will make all
  417. * subsequent font indicies drop by one,
  418. * so you'll need to update those yourself!
  419. */
  420. public void removeFontRecord(FontRecord rec) {
  421. records.remove(rec); // this updates FontPos for us
  422. numfonts--;
  423. }
  424. /**
  425. * gets the number of font records
  426. *
  427. * @return number of font records in the "font table"
  428. */
  429. public int getNumberOfFontRecords() {
  430. return numfonts;
  431. }
  432. /**
  433. * Sets the BOF for a given sheet
  434. *
  435. * @param sheetIndex the number of the sheet to set the positing of the bof for
  436. * @param pos the actual bof position
  437. */
  438. public void setSheetBof(int sheetIndex, int pos) {
  439. if (log.check( POILogger.DEBUG ))
  440. log.log(DEBUG, "setting bof for sheetnum =", Integer.valueOf(sheetIndex),
  441. " at pos=", Integer.valueOf(pos));
  442. checkSheets(sheetIndex);
  443. getBoundSheetRec(sheetIndex)
  444. .setPositionOfBof(pos);
  445. }
  446. private BoundSheetRecord getBoundSheetRec(int sheetIndex) {
  447. return boundsheets.get(sheetIndex);
  448. }
  449. /**
  450. * Returns the position of the backup record.
  451. */
  452. public BackupRecord getBackupRecord() {
  453. return ( BackupRecord ) records.get(records.getBackuppos());
  454. }
  455. /**
  456. * sets the name for a given sheet. If the boundsheet record doesn't exist and
  457. * its only one more than we have, go ahead and create it. If it's > 1 more than
  458. * we have, except
  459. *
  460. * @param sheetnum the sheet number (0 based)
  461. * @param sheetname the name for the sheet
  462. */
  463. public void setSheetName(int sheetnum, String sheetname) {
  464. checkSheets(sheetnum);
  465. // YK: Mimic Excel and silently truncate sheet names longer than 31 characters
  466. if(sheetname.length() > 31) sheetname = sheetname.substring(0, 31);
  467. BoundSheetRecord sheet = boundsheets.get(sheetnum);
  468. sheet.setSheetname(sheetname);
  469. }
  470. /**
  471. * Determines whether a workbook contains the provided sheet name. For the purpose of
  472. * comparison, long names are truncated to 31 chars.
  473. *
  474. * @param name the name to test (case insensitive match)
  475. * @param excludeSheetIdx the sheet to exclude from the check or -1 to include all sheets in the check.
  476. * @return true if the sheet contains the name, false otherwise.
  477. */
  478. public boolean doesContainsSheetName(String name, int excludeSheetIdx) {
  479. String aName = name;
  480. if (aName.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
  481. aName = aName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
  482. }
  483. for (int i = 0; i < boundsheets.size(); i++) {
  484. BoundSheetRecord boundSheetRecord = getBoundSheetRec(i);
  485. if (excludeSheetIdx == i) {
  486. continue;
  487. }
  488. String bName = boundSheetRecord.getSheetname();
  489. if (bName.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
  490. bName = bName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN);
  491. }
  492. if (aName.equalsIgnoreCase(bName)) {
  493. return true;
  494. }
  495. }
  496. return false;
  497. }
  498. /**
  499. * sets the order of appearance for a given sheet.
  500. *
  501. * @param sheetname the name of the sheet to reorder
  502. * @param pos the position that we want to insert the sheet into (0 based)
  503. */
  504. public void setSheetOrder(String sheetname, int pos ) {
  505. int sheetNumber = getSheetIndex(sheetname);
  506. //remove the sheet that needs to be reordered and place it in the spot we want
  507. boundsheets.add(pos, boundsheets.remove(sheetNumber));
  508. // also adjust order of Records, calculate the position of the Boundsheets via getBspos()...
  509. int pos0 = records.getBspos() - (boundsheets.size() - 1);
  510. Record removed = records.get(pos0 + sheetNumber);
  511. records.remove(pos0 + sheetNumber);
  512. records.add(pos0 + pos, removed);
  513. }
  514. /**
  515. * gets the name for a given sheet.
  516. *
  517. * @param sheetIndex the sheet number (0 based)
  518. * @return sheetname the name for the sheet
  519. */
  520. public String getSheetName(int sheetIndex) {
  521. return getBoundSheetRec(sheetIndex).getSheetname();
  522. }
  523. /**
  524. * Gets the hidden flag for a given sheet.
  525. * Note that a sheet could instead be
  526. * set to be very hidden, which is different
  527. * ({@link #isSheetVeryHidden(int)})
  528. *
  529. * @param sheetnum the sheet number (0 based)
  530. * @return True if sheet is hidden
  531. */
  532. public boolean isSheetHidden(int sheetnum) {
  533. return getBoundSheetRec(sheetnum).isHidden();
  534. }
  535. /**
  536. * Gets the very hidden flag for a given sheet.
  537. * This is different from the normal
  538. * hidden flag
  539. * ({@link #isSheetHidden(int)})
  540. *
  541. * @param sheetnum the sheet number (0 based)
  542. * @return True if sheet is very hidden
  543. */
  544. public boolean isSheetVeryHidden(int sheetnum) {
  545. return getBoundSheetRec(sheetnum).isVeryHidden();
  546. }
  547. /**
  548. * Hide or unhide a sheet
  549. *
  550. * @param sheetnum The sheet number
  551. * @param hidden True to mark the sheet as hidden, false otherwise
  552. */
  553. public void setSheetHidden(int sheetnum, boolean hidden) {
  554. getBoundSheetRec(sheetnum).setHidden(hidden);
  555. }
  556. /**
  557. * Hide or unhide a sheet.
  558. * 0 = not hidden
  559. * 1 = hidden
  560. * 2 = very hidden.
  561. *
  562. * @param sheetnum The sheet number
  563. * @param hidden 0 for not hidden, 1 for hidden, 2 for very hidden
  564. */
  565. public void setSheetHidden(int sheetnum, int hidden) {
  566. BoundSheetRecord bsr = getBoundSheetRec(sheetnum);
  567. boolean h = false;
  568. boolean vh = false;
  569. if(hidden == 0) {
  570. } else if(hidden == 1) {
  571. h = true;
  572. } else if(hidden == 2) {
  573. vh = true;
  574. } else {
  575. throw new IllegalArgumentException("Invalid hidden flag " + hidden + " given, must be 0, 1 or 2");
  576. }
  577. bsr.setHidden(h);
  578. bsr.setVeryHidden(vh);
  579. }
  580. /**
  581. * get the sheet's index
  582. * @param name sheet name
  583. * @return sheet index or -1 if it was not found.
  584. */
  585. public int getSheetIndex(String name) {
  586. int retval = -1;
  587. for (int k = 0; k < boundsheets.size(); k++) {
  588. String sheet = getSheetName(k);
  589. if (sheet.equalsIgnoreCase(name)) {
  590. retval = k;
  591. break;
  592. }
  593. }
  594. return retval;
  595. }
  596. /**
  597. * if we're trying to address one more sheet than we have, go ahead and add it! if we're
  598. * trying to address >1 more than we have throw an exception!
  599. */
  600. private void checkSheets(int sheetnum) {
  601. if ((boundsheets.size()) <= sheetnum) { // if we're short one add another..
  602. if ((boundsheets.size() + 1) <= sheetnum) {
  603. throw new RuntimeException("Sheet number out of bounds!");
  604. }
  605. BoundSheetRecord bsr = createBoundSheet(sheetnum);
  606. records.add(records.getBspos()+1, bsr);
  607. records.setBspos( records.getBspos() + 1 );
  608. boundsheets.add(bsr);
  609. getOrCreateLinkTable().checkExternSheet(sheetnum);
  610. fixTabIdRecord();
  611. }
  612. }
  613. /**
  614. * @param sheetIndex zero based sheet index
  615. */
  616. public void removeSheet(int sheetIndex) {
  617. if (boundsheets.size() > sheetIndex) {
  618. records.remove(records.getBspos() - (boundsheets.size() - 1) + sheetIndex);
  619. boundsheets.remove(sheetIndex);
  620. fixTabIdRecord();
  621. }
  622. // Within NameRecords, it's ok to have the formula
  623. // part point at deleted sheets. It's also ok to
  624. // have the ExternSheetNumber point at deleted
  625. // sheets.
  626. // However, the sheet index must be adjusted, or
  627. // excel will break. (Sheet index is either 0 for
  628. // global, or 1 based index to sheet)
  629. int sheetNum1Based = sheetIndex + 1;
  630. for(int i=0; i<getNumNames(); i++) {
  631. NameRecord nr = getNameRecord(i);
  632. if(nr.getSheetNumber() == sheetNum1Based) {
  633. // Excel re-writes these to point to no sheet
  634. nr.setSheetNumber(0);
  635. } else if(nr.getSheetNumber() > sheetNum1Based) {
  636. // Bump down by one, so still points
  637. // at the same sheet
  638. nr.setSheetNumber(nr.getSheetNumber()-1);
  639. // also update the link-table as otherwise references might point at invalid sheets
  640. linkTable.updateIndexToInternalSheet(i, -1);
  641. }
  642. }
  643. }
  644. /**
  645. * make the tabid record look like the current situation.
  646. *
  647. * @return number of bytes written in the TabIdRecord
  648. */
  649. private int fixTabIdRecord() {
  650. TabIdRecord tir = ( TabIdRecord ) records.get(records.getTabpos());
  651. int sz = tir.getRecordSize();
  652. short[] tia = new short[ boundsheets.size() ];
  653. for (short k = 0; k < tia.length; k++) {
  654. tia[ k ] = k;
  655. }
  656. tir.setTabIdArray(tia);
  657. return tir.getRecordSize() - sz;
  658. }
  659. /**
  660. * returns the number of boundsheet objects contained in this workbook.
  661. *
  662. * @return number of BoundSheet records
  663. */
  664. public int getNumSheets() {
  665. if (log.check( POILogger.DEBUG ))
  666. log.log(DEBUG, "getNumSheets=", Integer.valueOf(boundsheets.size()));
  667. return boundsheets.size();
  668. }
  669. /**
  670. * get the number of ExtendedFormat records contained in this workbook.
  671. *
  672. * @return int count of ExtendedFormat records
  673. */
  674. public int getNumExFormats() {
  675. if (log.check( POILogger.DEBUG ))
  676. log.log(DEBUG, "getXF=", Integer.valueOf(numxfs));
  677. return numxfs;
  678. }
  679. /**
  680. * gets the ExtendedFormatRecord at the given 0-based index
  681. *
  682. * @param index of the Extended format record (0-based)
  683. * @return ExtendedFormatRecord at the given index
  684. */
  685. public ExtendedFormatRecord getExFormatAt(int index) {
  686. int xfptr = records.getXfpos() - (numxfs - 1);
  687. xfptr += index;
  688. ExtendedFormatRecord retval =
  689. ( ExtendedFormatRecord ) records.get(xfptr);
  690. return retval;
  691. }
  692. /**
  693. * Removes the given ExtendedFormatRecord record from the
  694. * file's list. This will make all
  695. * subsequent font indicies drop by one,
  696. * so you'll need to update those yourself!
  697. */
  698. public void removeExFormatRecord(ExtendedFormatRecord rec) {
  699. records.remove(rec); // this updates XfPos for us
  700. numxfs--;
  701. }
  702. /**
  703. * Removes ExtendedFormatRecord record with given index from the
  704. * file's list. This will make all
  705. * subsequent font indicies drop by one,
  706. * so you'll need to update those yourself!
  707. * @param index of the Extended format record (0-based)
  708. */
  709. public void removeExFormatRecord(int index) {
  710. int xfptr = records.getXfpos() - (numxfs - 1) + index;
  711. records.remove(xfptr); // this updates XfPos for us
  712. numxfs--;
  713. }
  714. /**
  715. * creates a new Cell-type Extneded Format Record and adds it to the end of
  716. * ExtendedFormatRecords collection
  717. *
  718. * @return ExtendedFormatRecord that was created
  719. */
  720. public ExtendedFormatRecord createCellXF() {
  721. ExtendedFormatRecord xf = createExtendedFormat();
  722. records.add(records.getXfpos()+1, xf);
  723. records.setXfpos( records.getXfpos() + 1 );
  724. numxfs++;
  725. return xf;
  726. }
  727. /**
  728. * Returns the StyleRecord for the given
  729. * xfIndex, or null if that ExtendedFormat doesn't
  730. * have a Style set.
  731. */
  732. public StyleRecord getStyleRecord(int xfIndex) {
  733. // Style records always follow after
  734. // the ExtendedFormat records
  735. for(int i=records.getXfpos(); i<records.size(); i++) {
  736. Record r = records.get(i);
  737. if(r instanceof ExtendedFormatRecord) {
  738. continue;
  739. }
  740. if(!(r instanceof StyleRecord)) {
  741. continue;
  742. }
  743. StyleRecord sr = (StyleRecord)r;
  744. if(sr.getXFIndex() == xfIndex) {
  745. return sr;
  746. }
  747. }
  748. return null;
  749. }
  750. /**
  751. * Creates a new StyleRecord, for the given Extended
  752. * Format index, and adds it onto the end of the
  753. * records collection
  754. */
  755. public StyleRecord createStyleRecord(int xfIndex) {
  756. // Style records always follow after
  757. // the ExtendedFormat records
  758. StyleRecord newSR = new StyleRecord();
  759. newSR.setXFIndex(xfIndex);
  760. // Find the spot
  761. int addAt = -1;
  762. for(int i=records.getXfpos(); i<records.size() &&
  763. addAt == -1; i++) {
  764. Record r = records.get(i);
  765. if(r instanceof ExtendedFormatRecord ||
  766. r instanceof StyleRecord) {
  767. // Keep going
  768. } else {
  769. addAt = i;
  770. }
  771. }
  772. if(addAt == -1) {
  773. throw new IllegalStateException("No XF Records found!");
  774. }
  775. records.add(addAt, newSR);
  776. return newSR;
  777. }
  778. /**
  779. * Adds a string to the SST table and returns its index (if its a duplicate
  780. * just returns its index and update the counts) ASSUMES compressed unicode
  781. * (meaning 8bit)
  782. *
  783. * @param string the string to be added to the SSTRecord
  784. *
  785. * @return index of the string within the SSTRecord
  786. */
  787. public int addSSTString(UnicodeString string) {
  788. if (log.check( POILogger.DEBUG ))
  789. log.log(DEBUG, "insert to sst string='", string);
  790. if (sst == null) {
  791. insertSST();
  792. }
  793. return sst.addString(string);
  794. }
  795. /**
  796. * given an index into the SST table, this function returns the corresponding String value
  797. * @return String containing the SST String
  798. */
  799. public UnicodeString getSSTString(int str) {
  800. if (sst == null) {
  801. insertSST();
  802. }
  803. UnicodeString retval = sst.getString(str);
  804. if (log.check( POILogger.DEBUG ))
  805. log.log(DEBUG, "Returning SST for index=", Integer.valueOf(str),
  806. " String= ", retval);
  807. return retval;
  808. }
  809. /**
  810. * use this function to add a Shared String Table to an existing sheet (say
  811. * generated by a different java api) without an sst....
  812. * @see #createExtendedSST()
  813. * @see org.apache.poi.hssf.record.SSTRecord
  814. */
  815. public void insertSST() {
  816. if (log.check( POILogger.DEBUG ))
  817. log.log(DEBUG, "creating new SST via insertSST!");
  818. sst = new SSTRecord();
  819. records.add(records.size() - 1, createExtendedSST());
  820. records.add(records.size() - 2, sst);
  821. }
  822. /**
  823. * Serializes all records int the worksheet section into a big byte array. Use
  824. * this to write the Workbook out.
  825. *
  826. * @return byte array containing the HSSF-only portions of the POIFS file.
  827. */
  828. // GJS: Not used so why keep it.
  829. // public byte [] serialize() {
  830. // log.log(DEBUG, "Serializing Workbook!");
  831. // byte[] retval = null;
  832. //
  833. //// ArrayList bytes = new ArrayList(records.size());
  834. // int arraysize = getSize();
  835. // int pos = 0;
  836. //
  837. // retval = new byte[ arraysize ];
  838. // for (int k = 0; k < records.size(); k++) {
  839. //
  840. // Record record = records.get(k);
  841. //// Let's skip RECALCID records, as they are only use for optimization
  842. // if(record.getSid() != RecalcIdRecord.sid || ((RecalcIdRecord)record).isNeeded()) {
  843. // pos += record.serialize(pos, retval); // rec.length;
  844. // }
  845. // }
  846. // log.log(DEBUG, "Exiting serialize workbook");
  847. // return retval;
  848. // }
  849. /**
  850. * Serializes all records int the worksheet section into a big byte array. Use
  851. * this to write the Workbook out.
  852. * @param offset of the data to be written
  853. * @param data array of bytes to write this to
  854. */
  855. public int serialize( int offset, byte[] data )
  856. {
  857. if (log.check( POILogger.DEBUG ))
  858. log.log( DEBUG, "Serializing Workbook with offsets" );
  859. int pos = 0;
  860. SSTRecord sst = null;
  861. int sstPos = 0;
  862. boolean wroteBoundSheets = false;
  863. for ( int k = 0; k < records.size(); k++ )
  864. {
  865. Record record = records.get( k );
  866. int len = 0;
  867. if (record instanceof SSTRecord)
  868. {
  869. sst = (SSTRecord)record;
  870. sstPos = pos;
  871. }
  872. if (record.getSid() == ExtSSTRecord.sid && sst != null)
  873. {
  874. record = sst.createExtSSTRecord(sstPos + offset);
  875. }
  876. if (record instanceof BoundSheetRecord) {
  877. if(!wroteBoundSheets) {
  878. for (int i = 0; i < boundsheets.size(); i++) {
  879. len+= getBoundSheetRec(i)
  880. .serialize(pos+offset+len, data);
  881. }
  882. wroteBoundSheets = true;
  883. }
  884. } else {
  885. len = record.serialize( pos + offset, data );
  886. }
  887. ///// DEBUG BEGIN /////
  888. // if (len != record.getRecordSize())
  889. // throw new IllegalStateException("Record size does not match serialized bytes. Serialized size = " + len + " but getRecordSize() returns " + record.getRecordSize());
  890. ///// DEBUG END /////
  891. pos += len; // rec.length;
  892. }
  893. if (log.check( POILogger.DEBUG ))
  894. log.log( DEBUG, "Exiting serialize workbook" );
  895. return pos;
  896. }
  897. /**
  898. * Perform any work necessary before the workbook is about to be serialized.
  899. *
  900. * Include in it ant code that modifies the workbook record stream and affects its size.
  901. */
  902. public void preSerialize(){
  903. // Ensure we have enough tab IDs
  904. // Can be a few short if new sheets were added
  905. if(records.getTabpos() > 0) {
  906. TabIdRecord tir = ( TabIdRecord ) records.get(records.getTabpos());
  907. if(tir._tabids.length < boundsheets.size()) {
  908. fixTabIdRecord();
  909. }
  910. }
  911. }
  912. public int getSize()
  913. {
  914. int retval = 0;
  915. SSTRecord sst = null;
  916. for ( int k = 0; k < records.size(); k++ )
  917. {
  918. Record record = records.get( k );
  919. if (record instanceof SSTRecord)
  920. sst = (SSTRecord)record;
  921. if (record.getSid() == ExtSSTRecord.sid && sst != null)
  922. retval += sst.calcExtSSTRecordSize();
  923. else
  924. retval += record.getRecordSize();
  925. }
  926. return retval;
  927. }
  928. private static BOFRecord createBOF() {
  929. BOFRecord retval = new BOFRecord();
  930. retval.setVersion(( short ) 0x600);
  931. retval.setType(BOFRecord.TYPE_WORKBOOK);
  932. retval.setBuild(( short ) 0x10d3);
  933. retval.setBuildYear(( short ) 1996);
  934. retval.setHistoryBitMask(0x41); // was c1 before verify
  935. retval.setRequiredVersion(0x6);
  936. return retval;
  937. }
  938. private static MMSRecord createMMS() {
  939. MMSRecord retval = new MMSRecord();
  940. retval.setAddMenuCount(( byte ) 0);
  941. retval.setDelMenuCount(( byte ) 0);
  942. return retval;
  943. }
  944. /**
  945. * creates the WriteAccess record containing the logged in user's name
  946. */
  947. private static WriteAccessRecord createWriteAccess() {
  948. WriteAccessRecord retval = new WriteAccessRecord();
  949. String defaultUserName = "POI";
  950. try {
  951. String username = System.getProperty("user.name");
  952. // Google App engine returns null for user.name, see Bug 53974
  953. if(username == null) username = defaultUserName;
  954. retval.setUsername(username);
  955. } catch (AccessControlException e) {
  956. // AccessControlException can occur in a restricted context
  957. // (client applet/jws application or restricted security server)
  958. retval.setUsername(defaultUserName);
  959. }
  960. return retval;
  961. }
  962. private static CodepageRecord createCodepage() {
  963. CodepageRecord retval = new CodepageRecord();
  964. retval.setCodepage(CODEPAGE);
  965. return retval;
  966. }
  967. private static DSFRecord createDSF() {
  968. return new DSFRecord(false); // we don't even support double stream files
  969. }
  970. /**
  971. * creates the TabId record containing an array
  972. */
  973. private static TabIdRecord createTabId() {
  974. return new TabIdRecord();
  975. }
  976. /**
  977. * creates the FnGroupCount record containing the Magic number constant of 14.
  978. */
  979. private static FnGroupCountRecord createFnGroupCount() {
  980. FnGroupCountRecord retval = new FnGroupCountRecord();
  981. retval.setCount(( short ) 14);
  982. return retval;
  983. }
  984. /**
  985. * @return a new WindowProtect record with protect set to false.
  986. */
  987. private static WindowProtectRecord createWindowProtect() {
  988. // by default even when we support it we won't
  989. // want it to be protected
  990. return new WindowProtectRecord(false);
  991. }
  992. /**
  993. * @return a new Protect record with protect set to false.
  994. */
  995. private static ProtectRecord createProtect() {
  996. // by default even when we support it we won't
  997. // want it to be protected
  998. return new ProtectRecord(false);
  999. }
  1000. /**
  1001. * @return a new Password record with password set to 0x0000 (no password).
  1002. */
  1003. private static PasswordRecord createPassword() {
  1004. return new PasswordRecord(0x0000); // no password by default!
  1005. }
  1006. /**
  1007. * @return a new ProtectionRev4 record with protect set to false.
  1008. */
  1009. private static ProtectionRev4Record createProtectionRev4() {
  1010. return new ProtectionRev4Record(false);
  1011. }
  1012. /**
  1013. * @return a new PasswordRev4 record with password set to 0.
  1014. */
  1015. private static PasswordRev4Record createPasswordRev4() {
  1016. return new PasswordRev4Record(0x0000);
  1017. }
  1018. /**
  1019. * creates the WindowOne record with the following magic values: <P>
  1020. * horizontal hold - 0x168 <P>
  1021. * vertical hold - 0x10e <P>
  1022. * width - 0x3a5c <P>
  1023. * height - 0x23be <P>
  1024. * options - 0x38 <P>
  1025. * selected tab - 0 <P>
  1026. * displayed tab - 0 <P>
  1027. * num selected tab- 0 <P>
  1028. * tab width ratio - 0x258 <P>
  1029. */
  1030. private static WindowOneRecord createWindowOne() {
  1031. WindowOneRecord retval = new WindowOneRecord();
  1032. retval.setHorizontalHold(( short ) 0x168);
  1033. retval.setVerticalHold(( short ) 0x10e);
  1034. retval.setWidth(( short ) 0x3a5c);
  1035. retval.setHeight(( short ) 0x23be);
  1036. retval.setOptions(( short ) 0x38);
  1037. retval.setActiveSheetIndex( 0x0);
  1038. retval.setFirstVisibleTab(0x0);
  1039. retval.setNumSelectedTabs(( short ) 1);
  1040. retval.setTabWidthRatio(( short ) 0x258);
  1041. return retval;
  1042. }
  1043. /**
  1044. * creates the Backup record with backup set to 0. (loose the data, who cares)
  1045. */
  1046. private static BackupRecord createBackup() {
  1047. BackupRecord retval = new BackupRecord();
  1048. retval.setBackup(( short ) 0); // by default DONT save backups of files...just loose data
  1049. return retval;
  1050. }
  1051. /**
  1052. * creates the HideObj record with hide object set to 0. (don't hide)
  1053. */
  1054. private static HideObjRecord createHideObj() {
  1055. HideObjRecord retval = new HideObjRecord();
  1056. retval.setHideObj(( short ) 0); // by default set hide object off
  1057. return retval;
  1058. }
  1059. /**
  1060. * creates the DateWindow1904 record with windowing set to 0. (don't window)
  1061. */
  1062. private static DateWindow1904Record createDateWindow1904() {
  1063. DateWindow1904Record retval = new DateWindow1904Record();
  1064. retval.setWindowing(( short ) 0); // don't EVER use 1904 date windowing...tick tock..
  1065. return retval;
  1066. }
  1067. /**
  1068. * creates the Precision record with precision set to true. (full precision)
  1069. */
  1070. private static PrecisionRecord createPrecision() {
  1071. PrecisionRecord retval = new PrecisionRecord();
  1072. retval.setFullPrecision(true); // always use real numbers in calculations!
  1073. return retval;
  1074. }
  1075. /**
  1076. * @return a new RefreshAll record with refreshAll set to false. (do not refresh all calcs)
  1077. */
  1078. private static RefreshAllRecord createRefreshAll() {
  1079. return new RefreshAllRecord(false);
  1080. }
  1081. /**
  1082. * creates the BookBool record with saveLinkValues set to 0. (don't save link values)
  1083. */
  1084. private static BookBoolRecord createBookBool() {
  1085. BookBoolRecord retval = new BookBoolRecord();
  1086. retval.setSaveLinkValues(( short ) 0);
  1087. return retval;
  1088. }
  1089. /**
  1090. * creates a Font record with the following magic values: <P>
  1091. * fontheight = 0xc8<P>
  1092. * attributes = 0x0<P>
  1093. * color palette index = 0x7fff<P>
  1094. * bold weight = 0x190<P>
  1095. * Font Name Length = 5 <P>
  1096. * Font Name = Arial <P>
  1097. */
  1098. private static FontRecord createFont() {
  1099. FontRecord retval = new FontRecord();
  1100. retval.setFontHeight(( short ) 0xc8);
  1101. retval.setAttributes(( short ) 0x0);
  1102. retval.setColorPaletteIndex(( short ) 0x7fff);
  1103. retval.setBoldWeight(( short ) 0x190);
  1104. retval.setFontName("Arial");
  1105. return retval;
  1106. }
  1107. /**
  1108. * Creates a FormatRecord object
  1109. * @param id the number of the format record to create (meaning its position in
  1110. * a file as M$ Excel would create it.)
  1111. */
  1112. private static FormatRecord createFormat(int id) {
  1113. // we'll need multiple editions for
  1114. // the different formats
  1115. switch (id) {
  1116. case 0: return new FormatRecord(5, BuiltinFormats.getBuiltinFormat(5));
  1117. case 1: return new FormatRecord(6, BuiltinFormats.getBuiltinFormat(6));
  1118. case 2: return new FormatRecord(7, BuiltinFormats.getBuiltinFormat(7));
  1119. case 3: return new FormatRecord(8, BuiltinFormats.getBuiltinFormat(8));
  1120. case 4: return new FormatRecord(0x2a, BuiltinFormats.getBuiltinFormat(0x2a));
  1121. case 5: return new FormatRecord(0x29, BuiltinFormats.getBuiltinFormat(0x29));
  1122. case 6: return new FormatRecord(0x2c, BuiltinFormats.getBuiltinFormat(0x2c));
  1123. case 7: return new FormatRecord(0x2b, BuiltinFormats.getBuiltinFormat(0x2b));
  1124. }
  1125. throw new IllegalArgumentException("Unexpected id " + id);
  1126. }
  1127. /**
  1128. * Creates an ExtendedFormatRecord object
  1129. * @param id the number of the extended format record to create (meaning its position in
  1130. * a file as MS Excel would create it.)
  1131. */
  1132. private static ExtendedFormatRecord createExtendedFormat(int id) { // we'll need multiple editions
  1133. ExtendedFormatRecord retval = new ExtendedFormatRecord();
  1134. switch (id) {
  1135. case 0 :
  1136. retval.setFontIndex(( short ) 0);
  1137. retval.setFormatIndex(( short ) 0);
  1138. retval.setCellOptions(( short ) 0xfffffff5);
  1139. retval.setAlignmentOptions(( short ) 0x20);
  1140. retval.setIndentionOptions(( short ) 0);
  1141. retval.setBorderOptions(( short ) 0);
  1142. retval.setPaletteOptions(( short ) 0);
  1143. retval.setAdtlPaletteOptions(( short ) 0);
  1144. retval.setFillPaletteOptions(( short ) 0x20c0);
  1145. break;
  1146. case 1 :
  1147. retval.setFontIndex(( short ) 1);
  1148. retval.setFormatIndex(( short ) 0);
  1149. retval.setCellOptions(( short ) 0xfffffff5);
  1150. retval.setAlignmentOptions(( short ) 0x20);
  1151. retval.setIndentionOptions(( short ) 0xfffff400);
  1152. retval.setBorderOptions(( short ) 0);
  1153. retval.setPaletteOptions(( short ) 0);
  1154. retval.setAdtlPaletteOptions(( short ) 0);
  1155. retval.setFillPaletteOptions(( short ) 0x20c0);
  1156. break;
  1157. case 2 :
  1158. retval.setFontIndex(( short ) 1);
  1159. retval.setFormatIndex(( short ) 0);
  1160. retval.setCellOptions(( short ) 0xfffffff5);
  1161. retval.setAlignmentOptions(( short ) 0x20);
  1162. retval.setIndentionOptions(( short ) 0xfffff400);
  1163. retval.setBorderOptions(( short ) 0);
  1164. retval.setPaletteOptions(( short ) 0);
  1165. retval.setAdtlPaletteOptions(( short ) 0);
  1166. retval.setFillPaletteOptions(( short ) 0x20c0);
  1167. break;
  1168. case 3 :
  1169. retval.setFontIndex(( short ) 2);
  1170. retval.setFormatIndex(( short ) 0);
  1171. retval.setCellOptions(( short ) 0xfffffff5);
  1172. retval.setAlignmentOptions(( short ) 0x20);
  1173. retval.setIndentionOptions(( short ) 0xfffff400);
  1174. retval.setBorderOptions(( short ) 0);
  1175. retval.setPaletteOptions(( short ) 0);
  1176. retval.setAdtlPaletteOptions(( short ) 0);
  1177. retval.setFillPaletteOptions(( short ) 0x20c0);
  1178. break;
  1179. case 4 :
  1180. retval.setFontIndex(( short ) 2);
  1181. retval.setFormatIndex(( short ) 0);
  1182. retval.setCellOptions(( short ) 0xfffffff5);
  1183. retval.setAlignmentOptions(( short ) 0x20);
  1184. retval.setIndentionOptions(( short ) 0xfffff400);
  1185. retval.setBorderOptions(( short ) 0);
  1186. retval.setPaletteOptions(( short ) 0);
  1187. retval.setAdtlPaletteOptions(( short ) 0);
  1188. retval.setFillPaletteOptions(( short ) 0x20c0);
  1189. break;
  1190. case 5 :
  1191. retval.setFontIndex(( short ) 0);
  1192. retval.setFormatIndex(( short ) 0);
  1193. retval.setCellOptions(( short ) 0xfffffff5);
  1194. retval.setAlignmentOptions(( short ) 0x20);
  1195. retval.setIndentionOptions(( short ) 0xfffff400);
  1196. retval.setBorderOptions(( short ) 0);
  1197. retval.setPaletteOptions(( short ) 0);
  1198. retval.setAdtlPaletteOptions(( short ) 0);
  1199. retval.setFillPaletteOptions(( short ) 0x20c0);
  1200. break;
  1201. case 6 :
  1202. retval.setFontIndex(( short ) 0);
  1203. retval.setFormatIndex(( short ) 0);
  1204. retval.setCellOptions(( short ) 0xfffffff5);
  1205. retval.setAlignmentOptions(( short ) 0x20);
  1206. retval.setIndentionOptions(( short ) 0xfffff400);
  1207. retval.setBorderOptions(( short ) 0);
  1208. retval.setPaletteOptions(( short ) 0);
  1209. retval.setAdtlPaletteOptions(( short ) 0);
  1210. retval.setFillPaletteOptions(( short ) 0x20c0);
  1211. break;
  1212. case 7 :
  1213. retval.setFontIndex(( short ) 0);
  1214. retval.setFormatIndex(( short ) 0);
  1215. retval.setCellOptions(( short ) 0xfffffff5);
  1216. retval.setAlignmentOptions(( short ) 0x20);
  1217. retval.setIndentionOptions(( short ) 0xfffff400);
  1218. retval.setBorderOptions(( short ) 0);
  1219. retval.setPaletteOptions(( short ) 0);
  1220. retval.setAdtlPaletteOptions(( short ) 0);
  1221. retval.setFillPaletteOptions(( short ) 0x20c0);
  1222. break;
  1223. case 8 :
  1224. retval.setFontIndex(( short ) 0);
  1225. retval.setFormatIndex(( short ) 0);
  1226. retval.setCellOptions(( short ) 0xfffffff5);
  1227. retval.setAlignmentOptions(( short ) 0x20);
  1228. retval.setIndentionOptions(( short ) 0xfffff400);
  1229. retval.setBorderOptions(( short ) 0);
  1230. retval.setPaletteOptions(( short ) 0);
  1231. retval.setAdtlPaletteOptions(( short ) 0);
  1232. retval.setFillPaletteOptions(( short ) 0x20c0);
  1233. break;
  1234. case 9 :
  1235. retval.setFontIndex(( short ) 0);
  1236. retval.setFormatIndex(( short ) 0);
  1237. retval.setCellOptions(( short ) 0xfffffff5);
  1238. retval.setAlignmentOptions(( short ) 0x20);
  1239. retval.setIndentionOptions(( short ) 0xfffff400);
  1240. retval.setBorderOptions(( short ) 0);
  1241. retval.setPaletteOptions(( short ) 0);
  1242. retval.setAdtlPaletteOptions(( short ) 0);
  1243. retval.setFillPaletteOptions(( short ) 0x20c0);
  1244. break;
  1245. case 10 :
  1246. retval.setFontIndex(( short ) 0);
  1247. retval.setFormatIndex(( short ) 0);
  1248. retval.setCellOptions(( short ) 0xfffffff5);
  1249. retval.setAlignmentOptions(( short ) 0x20);
  1250. retval.setIndentionOptions(( short ) 0xfffff400);
  1251. retval.setBorderOptions(( short ) 0);
  1252. retval.setPaletteOptions(( short ) 0);
  1253. retval.setAdtlPaletteOptions(( short ) 0);
  1254. retval.setFillPaletteOptions(( short ) 0x20c0);
  1255. break;
  1256. case 11 :
  1257. retval.setFontIndex(( short ) 0);
  1258. retval.setFormatIndex(( short ) 0);
  1259. retval.setCellOptions(( short ) 0xfffffff5);
  1260. retval.setAlignmentOptions(( short ) 0x20);
  1261. retval.setIndentionOptions(( short ) 0xfffff400);
  1262. retval.setBorderOptions(( short ) 0);
  1263. retval.setPaletteOptions(( short ) 0);
  1264. retval.setAdtlPaletteOptions(( short ) 0);
  1265. retval.setFillPaletteOptions(( short ) 0x20c0);
  1266. break;
  1267. case 12 :
  1268. retval.setFontIndex(( short ) 0);
  1269. retval.setFormatIndex(( short ) 0);
  1270. retval.setCellOptions(( short ) 0xfffffff5);
  1271. retval.setAlignmentOptions(( short ) 0x20);
  1272. retval.setIndentionOptions(( short ) 0xfffff400);
  1273. retval.setBorderOptions(( short ) 0);
  1274. retval.setPaletteOptions(( short ) 0);
  1275. retval.setAdtlPaletteOptions(( short ) 0);
  1276. retval.setFillPaletteOptions(( short ) 0x20c0);
  1277. break;
  1278. case 13 :
  1279. retval.setFontIndex(( short ) 0);
  1280. retval.setFormatIndex(( short ) 0);
  1281. retval.setCellOptions(( short ) 0xfffffff5);
  1282. retval.setAlignmentOptions(( short ) 0x20);
  1283. retval.setIndentionOptions(( short ) 0xfffff400);
  1284. retval.setBorderOptions(( short ) 0);
  1285. retval.setPaletteOptions(( short ) 0);
  1286. retval.setAdtlPaletteOptions(( short ) 0);
  1287. retval.setFillPaletteOptions(( short ) 0x20c0);
  1288. break;
  1289. case 14 :
  1290. retval.setFontIndex(( short ) 0);
  1291. retval.setFormatIndex(( short ) 0);
  1292. retval.setCellOptions(( short ) 0xfffffff5);
  1293. retval.setAlignmentOptions(( short ) 0x20);
  1294. retval.setIndentionOptions(( short ) 0xfffff400);
  1295. retval.setBorderOptions(( short ) 0);
  1296. retval.setPaletteOptions(( short ) 0);
  1297. retval.setAdtlPaletteOptions(( short ) 0);
  1298. retval.setFillPaletteOptions(( short ) 0x20c0);
  1299. break;
  1300. // cell records
  1301. case 15 :
  1302. retval.setFontIndex(( short ) 0);
  1303. retval.setFormatIndex(( short ) 0);
  1304. retval.setCellOptions(( short ) 0x1);
  1305. retval.setAlignmentOptions(( short ) 0x20);
  1306. retval.setIndentionOptions(( short ) 0x0);
  1307. retval.setBorderOptions(( short ) 0);
  1308. retval.setPaletteOptions(( short ) 0);
  1309. retval.setAdtlPaletteOptions(( short ) 0);
  1310. retval.setFillPaletteOptions(( short ) 0x20c0);
  1311. break;
  1312. // style
  1313. case 16 :
  1314. retval.setFontIndex(( short ) 1);
  1315. retval.setFormatIndex(( short ) 0x2b);
  1316. retval.setCellOptions(( short ) 0xfffffff5);
  1317. retval.setAlignmentOptions(( short ) 0x20);
  1318. retval.setIndentionOptions(( short ) 0xfffff800);
  1319. retval.setBorderOptions(( short ) 0);
  1320. retval.setPaletteOptions(( short ) 0);
  1321. retval.setAdtlPaletteOptions(( short ) 0);
  1322. retval.setFillPaletteOptions(( short ) 0x20c0);
  1323. break;
  1324. case 17 :
  1325. retval.setFontIndex(( short ) 1);
  1326. retval.setFormatIndex(( short ) 0x29);
  1327. retval.setCellOptions(( short ) 0xfffffff5);
  1328. retval.setAlignmentOptions(( short ) 0x20);
  1329. retval.setIndentionOptions(( short ) 0xfffff800);
  1330. retval.setBorderOptions(( short ) 0);
  1331. retval.setPaletteOptions(( short ) 0);
  1332. retval.setAdtlPaletteOptions(( short ) 0);
  1333. retval.setFillPaletteOptions(( short ) 0x20c0);
  1334. break;
  1335. case 18 :
  1336. retval.setFontIndex(( short ) 1);
  1337. retval.setFormatIndex(( short ) 0x2c);
  1338. retval.setCellOptions(( short ) 0xfffffff5);
  1339. retval.setAlignmentOptions(( short ) 0x20);
  1340. retval.setIndentionOptions(( short ) 0xfffff800);
  1341. retval.setBorderOptions(( short ) 0);
  1342. retval.setPaletteOptions(( short ) 0);
  1343. retval.setAdtlPaletteOptions(( short ) 0);
  1344. retval.setFillPaletteOptions(( short ) 0x20c0);
  1345. break;
  1346. case 19 :
  1347. retval.setFontIndex(( short ) 1);
  1348. retval.setFormatIndex(( short ) 0x2a);
  1349. retval.setCellOptions(( short ) 0xfffffff5);
  1350. retval.setAlignmentOptions(( short ) 0x20);
  1351. retval.setIndentionOptions(( short ) 0xfffff800);
  1352. retval.setBorderOptions(( short ) 0);
  1353. retval.setPaletteOptions(( short ) 0);
  1354. retval.setAdtlPaletteOptions(( short ) 0);
  1355. retval.setFillPaletteOptions(( short ) 0x20c0);
  1356. break;
  1357. case 20 :
  1358. retval.setFontIndex(( short ) 1);
  1359. retval.setFormatIndex(( short ) 0x9);
  1360. retval.setCellOptions(( short ) 0xfffffff5);
  1361. retval.setAlignmentOptions(( short ) 0x20);
  1362. retval.setIndentionOptions(( short ) 0xfffff800);
  1363. retval.setBorderOptions(( short ) 0);
  1364. retval.setPaletteOptions(( short ) 0);
  1365. retval.setAdtlPaletteOptions(( short ) 0);
  1366. retval.setFillPaletteOptions(( short ) 0x20c0);
  1367. break;
  1368. // unused from this point down
  1369. case 21 :
  1370. retval.setFontIndex(( short ) 5);
  1371. retval.setFormatIndex(( short ) 0x0);
  1372. retval.setCellOptions(( short ) 0x1);
  1373. retval.setAlignmentOptions(( short ) 0x20);
  1374. retval.setIndentionOptions(( short ) 0x800);
  1375. retval.setBorderOptions(( short ) 0);
  1376. retval.setPaletteOptions(( short ) 0);
  1377. retval.setAdtlPaletteOptions(( short ) 0);
  1378. retval.setFillPaletteOptions(( short ) 0x20c0);
  1379. break;
  1380. case 22 :
  1381. retval.setFontIndex(( short ) 6);
  1382. retval.setFormatIndex(( short ) 0x0);
  1383. retval.setCellOptions(( short ) 0x1);
  1384. retval.setAlignmentOptions(( short ) 0x20);
  1385. retval.setIndentionOptions(( short ) 0x5c00);
  1386. retval.setBorderOptions(( short ) 0);
  1387. retval.setPaletteOptions(( short ) 0);
  1388. retval.setAdtlPaletteOptions(( short ) 0);
  1389. retval.setFillPaletteOptions(( short ) 0x20c0);
  1390. break;
  1391. case 23 :
  1392. retval.setFontIndex(( short ) 0);
  1393. retval.setFormatIndex(( short ) 0x31);
  1394. retval.setCellOptions(( short ) 0x1);
  1395. retval.setAlignmentOptions(( short ) 0x20);
  1396. retval.setIndentionOptions(( short ) 0x5c00);
  1397. retval.setBorderOptions(( short ) 0);
  1398. retval.setPaletteOptions(( short ) 0);
  1399. retval.setAdtlPaletteOptions(( short ) 0);
  1400. retval.setFillPaletteOptions(( short ) 0x20c0);
  1401. break;
  1402. case 24 :
  1403. retval.setFontIndex(( short ) 0);
  1404. retval.setFormatIndex(( short ) 0x8);
  1405. retval.setCellOptions(( short ) 0x1);
  1406. retval.setAlignmentOptions(( short ) 0x20);
  1407. retval.setIndentionOptions(( short ) 0x5c00);
  1408. retval.setBorderOptions(( short ) 0);
  1409. retval.setPaletteOptions(( short ) 0);
  1410. retval.setAdtlPaletteOptions(( short ) 0);
  1411. retval.setFillPaletteOptions(( short ) 0x20c0);
  1412. break;
  1413. case 25 :
  1414. retval.setFontIndex(( short ) 6);
  1415. retval.setFormatIndex(( short ) 0x8);
  1416. retval.setCellOptions(( short ) 0x1);
  1417. retval.setAlignmentOptions(( short ) 0x20);
  1418. retval.setIndentionOptions(( short ) 0x5c00);
  1419. retval.setBorderOptions(( short ) 0);
  1420. retval.setPaletteOptions(( short ) 0);
  1421. retval.setAdtlPaletteOptions(( short ) 0);
  1422. retval.setFillPaletteOptions(( short ) 0x20c0);
  1423. break;
  1424. }
  1425. return retval;
  1426. }
  1427. /**
  1428. * creates an default cell type ExtendedFormatRecord object.
  1429. * @return ExtendedFormatRecord with intial defaults (cell-type)
  1430. */
  1431. private static ExtendedFormatRecord createExtendedFormat() {
  1432. ExtendedFormatRecord retval = new ExtendedFormatRecord();
  1433. retval.setFontIndex(( short ) 0);
  1434. retval.setFormatIndex(( short ) 0x0);
  1435. retval.setCellOptions(( short ) 0x1);
  1436. retval.setAlignmentOptions(( short ) 0x20);
  1437. retval.setIndentionOptions(( short ) 0);
  1438. retval.setBorderOptions(( short ) 0);
  1439. retval.setPaletteOptions(( short ) 0);
  1440. retval.setAdtlPaletteOptions(( short ) 0);
  1441. retval.setFillPaletteOptions(( short ) 0x20c0);
  1442. retval.setTopBorderPaletteIdx(HSSFColor.BLACK.index);
  1443. retval.setBottomBorderPaletteIdx(HSSFColor.BLACK.index);
  1444. retval.setLeftBorderPaletteIdx(HSSFColor.BLACK.index);
  1445. retval.setRightBorderPaletteIdx(HSSFColor.BLACK.index);
  1446. return retval;
  1447. }
  1448. /**
  1449. * Creates a StyleRecord object
  1450. * @param id the number of the style record to create (meaning its position in
  1451. * a file as MS Excel would create it.
  1452. */
  1453. private static StyleRecord createStyle(int id) { // we'll need multiple editions
  1454. StyleRecord retval = new StyleRecord();
  1455. switch (id) {
  1456. case 0 :
  1457. retval.setXFIndex(0x010);
  1458. retval.setBuiltinStyle(3);
  1459. retval.setOutlineStyleLevel(( byte ) 0xffffffff);
  1460. break;
  1461. case 1 :
  1462. retval.setXFIndex(0x011);
  1463. retval.setBuiltinStyle(6);
  1464. retval.setOutlineStyleLevel(( byte ) 0xffffffff);
  1465. break;
  1466. case 2 :
  1467. retval.setXFIndex(0x012);
  1468. retval.setBuiltinStyle(4);
  1469. retval.setOutlineStyleLevel(( byte ) 0xffffffff);
  1470. break;
  1471. case 3 :
  1472. retval.setXFIndex(0x013);
  1473. retval.setBuiltinStyle(7);
  1474. retval.setOutlineStyleLevel(( byte ) 0xffffffff);
  1475. break;
  1476. case 4 :
  1477. retval.setXFIndex(0x000);
  1478. retval.setBuiltinStyle(0);
  1479. retval.setOutlineStyleLevel(( byte ) 0xffffffff);
  1480. break;
  1481. case 5 :
  1482. retval.setXFIndex(0x014);
  1483. retval.setBuiltinStyle(5);
  1484. retval.setOutlineStyleLevel(( byte ) 0xffffffff);
  1485. break;
  1486. }
  1487. return retval;
  1488. }
  1489. /**
  1490. * Creates a palette record initialized to the default palette
  1491. */
  1492. private static PaletteRecord createPalette() {
  1493. return new PaletteRecord();
  1494. }
  1495. /**
  1496. * @return a new UseSelFS object with the use natural language flag set to 0 (false)
  1497. */
  1498. private static UseSelFSRecord createUseSelFS() {
  1499. return new UseSelFSRecord(false);
  1500. }
  1501. /**
  1502. * create a "bound sheet" or "bundlesheet" (depending who you ask) record
  1503. * Always sets the sheet's bof to 0. You'll need to set that yourself.
  1504. * @param id either sheet 0,1 or 2.
  1505. * @return record containing a BoundSheetRecord
  1506. * @see org.apache.poi.hssf.record.BoundSheetRecord
  1507. * @see org.apache.poi.hssf.record.Record
  1508. */
  1509. private static BoundSheetRecord createBoundSheet(int id) {
  1510. return new BoundSheetRecord("Sheet" + (id+1));
  1511. }
  1512. /**
  1513. * Creates the Country record with the default country set to 1
  1514. * and current country set to 7 in case of russian locale ("ru_RU") and 1 otherwise
  1515. */
  1516. private static CountryRecord createCountry() {
  1517. CountryRecord retval = new CountryRecord();
  1518. retval.setDefaultCountry(( short ) 1);
  1519. // from Russia with love ;)
  1520. if ( Locale.getDefault().toString().equals( "ru_RU" ) ) {
  1521. retval.setCurrentCountry(( short ) 7);
  1522. }
  1523. else {
  1524. retval.setCurrentCountry(( short ) 1);
  1525. }
  1526. return retval;
  1527. }
  1528. /**
  1529. * Creates the ExtendedSST record with numstrings per bucket set to 0x8. HSSF
  1530. * doesn't yet know what to do with this thing, but we create it with nothing in
  1531. * it hardly just to make Excel happy and our sheets look like Excel's
  1532. */
  1533. private static ExtSSTRecord createExtendedSST() {
  1534. ExtSSTRecord retval = new ExtSSTRecord();
  1535. retval.setNumStringsPerBucket(( short ) 0x8);
  1536. return retval;
  1537. }
  1538. /**
  1539. * lazy initialization
  1540. * Note - creating the link table causes creation of 1 EXTERNALBOOK and 1 EXTERNALSHEET record
  1541. */
  1542. private LinkTable getOrCreateLinkTable() {
  1543. if(linkTable == null) {
  1544. linkTable = new LinkTable((short) getNumSheets(), records);
  1545. }
  1546. return linkTable;
  1547. }
  1548. /** finds the sheet name by his extern sheet index
  1549. * @param externSheetIndex extern sheet index
  1550. * @return sheet name.
  1551. */
  1552. public String findSheetNameFromExternSheet(int externSheetIndex){
  1553. int indexToSheet = linkTable.getIndexToInternalSheet(externSheetIndex);
  1554. if (indexToSheet < 0) {
  1555. // TODO - what does '-1' mean here?
  1556. //error check, bail out gracefully!
  1557. return "";
  1558. }
  1559. if (indexToSheet >= boundsheets.size()) {
  1560. // Not sure if this can ever happen (See bug 45798)
  1561. return ""; // Seems to be what excel would do in this case
  1562. }
  1563. return getSheetName(indexToSheet);
  1564. }
  1565. public ExternalSheet getExternalSheet(int externSheetIndex) {
  1566. String[] extNames = linkTable.getExternalBookAndSheetName(externSheetIndex);
  1567. if (extNames == null) {
  1568. return null;
  1569. }
  1570. return new ExternalSheet(extNames[0], extNames[1]);
  1571. }
  1572. public ExternalName getExternalName(int externSheetIndex, int externNameIndex) {
  1573. String nameName = linkTable.resolveNameXText(externSheetIndex, externNameIndex);
  1574. if(nameName == null) {
  1575. return null;
  1576. }
  1577. int ix = linkTable.resolveNameXIx(externSheetIndex, externNameIndex);
  1578. return new ExternalName(nameName, externNameIndex, ix);
  1579. }
  1580. /**
  1581. * Finds the sheet index for a particular external sheet number.
  1582. * @param externSheetNumber The external sheet number to convert
  1583. * @return The index to the sheet found.
  1584. */
  1585. public int getSheetIndexFromExternSheetIndex(int externSheetNumber)
  1586. {
  1587. return linkTable.getSheetIndexFromExternSheetIndex(externSheetNumber);
  1588. }
  1589. /** returns the extern sheet number for specific sheet number ,
  1590. * if this sheet doesn't exist in extern sheet , add it
  1591. * @param sheetNumber sheet number
  1592. * @return index to extern sheet
  1593. */
  1594. public short checkExternSheet(int sheetNumber){
  1595. return (short)getOrCreateLinkTable().checkExternSheet(sheetNumber);
  1596. }
  1597. public int getExternalSheetIndex(String workbookName, String sheetName) {
  1598. return getOrCreateLinkTable().getExternalSheetIndex(workbookName, sheetName);
  1599. }
  1600. /** gets the total number of names
  1601. * @return number of names
  1602. */
  1603. public int getNumNames(){
  1604. if(linkTable == null) {
  1605. return 0;
  1606. }
  1607. return linkTable.getNumNames();
  1608. }
  1609. /** gets the name record
  1610. * @param index name index
  1611. * @return name record
  1612. */
  1613. public NameRecord getNameRecord(int index){
  1614. return linkTable.getNameRecord(index);
  1615. }
  1616. /** gets the name comment record
  1617. * @param nameRecord name record who's comment is required.
  1618. * @return name comment record or <code>null</code> if there isn't one for the given name.
  1619. */
  1620. public NameCommentRecord getNameCommentRecord(final NameRecord nameRecord){
  1621. return commentRecords.get(nameRecord.getNameText());
  1622. }
  1623. /** creates new name
  1624. * @return new name record
  1625. */
  1626. public NameRecord createName(){
  1627. return addName(new NameRecord());
  1628. }
  1629. /** creates new name
  1630. * @return new name record
  1631. */
  1632. public NameRecord addName(NameRecord name)
  1633. {
  1634. LinkTable linkTable = getOrCreateLinkTable();
  1635. linkTable.addName(name);
  1636. return name;
  1637. }
  1638. /**
  1639. * Generates a NameRecord to represent a built-in region
  1640. * @return a new NameRecord
  1641. */
  1642. public NameRecord createBuiltInName(byte builtInName, int sheetNumber) {
  1643. if (sheetNumber < 0 || sheetNumber+1 > Short.MAX_VALUE) {
  1644. throw new IllegalArgumentException("Sheet number ["+sheetNumber+"]is not valid ");
  1645. }
  1646. NameRecord name = new NameRecord(builtInName, sheetNumber);
  1647. if(linkTable.nameAlreadyExists(name)) {
  1648. throw new RuntimeException("Builtin (" + builtInName
  1649. + ") already exists for sheet (" + sheetNumber + ")");
  1650. }
  1651. addName(name);
  1652. return name;
  1653. }
  1654. /** removes the name
  1655. * @param nameIndex name index
  1656. */
  1657. public void removeName(int nameIndex){
  1658. if (linkTable.getNumNames() > nameIndex) {
  1659. int idx = findFirstRecordLocBySid(NameRecord.sid);
  1660. records.remove(idx + nameIndex);
  1661. linkTable.removeName(nameIndex);
  1662. }
  1663. }
  1664. /**
  1665. * If a {@link NameCommentRecord} is added or the name it references
  1666. * is renamed, then this will update the lookup cache for it.
  1667. */
  1668. public void updateNameCommentRecordCache(final NameCommentRecord commentRecord) {
  1669. if(commentRecords.containsValue(commentRecord)) {
  1670. for(Entry<String,NameCommentRecord> entry : commentRecords.entrySet()) {
  1671. if(entry.getValue().equals(commentRecord)) {
  1672. commentRecords.remove(entry.getKey());
  1673. break;
  1674. }
  1675. }
  1676. }
  1677. commentRecords.put(commentRecord.getNameText(), commentRecord);
  1678. }
  1679. /**
  1680. * Returns a format index that matches the passed in format. It does not tie into HSSFDataFormat.
  1681. * @param format the format string
  1682. * @param createIfNotFound creates a new format if format not found
  1683. * @return the format id of a format that matches or -1 if none found and createIfNotFound
  1684. */
  1685. public short getFormat(String format, boolean createIfNotFound) {
  1686. for (FormatRecord r : formats) {
  1687. if (r.getFormatString().equals(format)) {
  1688. return (short)r.getIndexCode();
  1689. }
  1690. }
  1691. if (createIfNotFound) {
  1692. return (short)createFormat(format);
  1693. }
  1694. return -1;
  1695. }
  1696. /**
  1697. * Returns the list of FormatRecords in the workbook.
  1698. * @return ArrayList of FormatRecords in the notebook
  1699. */
  1700. public List<FormatRecord> getFormats() {
  1701. return formats;
  1702. }
  1703. /**
  1704. * Creates a FormatRecord, inserts it, and returns the index code.
  1705. * @param formatString the format string
  1706. * @return the index code of the format record.
  1707. * @see org.apache.poi.hssf.record.FormatRecord
  1708. * @see org.apache.poi.hssf.record.Record
  1709. */
  1710. public int createFormat(String formatString) {
  1711. maxformatid = maxformatid >= 0xa4 ? maxformatid + 1 : 0xa4; //Starting value from M$ empircal study.
  1712. FormatRecord rec = new FormatRecord(maxformatid, formatString);
  1713. int pos = 0;
  1714. while ( pos < records.size() && records.get( pos ).getSid() != FormatRecord.sid )
  1715. pos++;
  1716. pos += formats.size();
  1717. formats.add( rec );
  1718. records.add( pos, rec );
  1719. return maxformatid;
  1720. }
  1721. /**
  1722. * Returns the first occurance of a record matching a particular sid.
  1723. */
  1724. public Record findFirstRecordBySid(short sid) {
  1725. for (Record record : records) {
  1726. if (record.getSid() == sid) {
  1727. return record;
  1728. }
  1729. }
  1730. return null;
  1731. }
  1732. /**
  1733. * Returns the index of a record matching a particular sid.
  1734. * @param sid The sid of the record to match
  1735. * @return The index of -1 if no match made.
  1736. */
  1737. public int findFirstRecordLocBySid(short sid) {
  1738. int index = 0;
  1739. for (Record record : records) {
  1740. if (record.getSid() == sid) {
  1741. return index;
  1742. }
  1743. index ++;
  1744. }
  1745. return -1;
  1746. }
  1747. /**
  1748. * Returns the next occurance of a record matching a particular sid.
  1749. */
  1750. public Record findNextRecordBySid(short sid, int pos) {
  1751. int matches = 0;
  1752. for (Record record : records) {
  1753. if (record.getSid() == sid) {
  1754. if (matches++ == pos)
  1755. return record;
  1756. }
  1757. }
  1758. return null;
  1759. }
  1760. public List<HyperlinkRecord> getHyperlinks()
  1761. {
  1762. return hyperlinks;
  1763. }
  1764. public List<Record> getRecords() {
  1765. return records.getRecords();
  1766. }
  1767. /**
  1768. * Whether date windowing is based on 1/2/1904 or 1/1/1900.
  1769. * Some versions of Excel (Mac) can save workbooks using 1904 date windowing.
  1770. *
  1771. * @return true if using 1904 date windowing
  1772. */
  1773. public boolean isUsing1904DateWindowing() {
  1774. return uses1904datewindowing;
  1775. }
  1776. /**
  1777. * Returns the custom palette in use for this workbook; if a custom palette record
  1778. * does not exist, then it is created.
  1779. */
  1780. public PaletteRecord getCustomPalette()
  1781. {
  1782. PaletteRecord palette;
  1783. int palettePos = records.getPalettepos();
  1784. if (palettePos != -1) {
  1785. Record rec = records.get(palettePos);
  1786. if (rec instanceof PaletteRecord) {
  1787. palette = (PaletteRecord) rec;
  1788. } else throw new RuntimeException("InternalError: Expected PaletteRecord but got a '"+rec+"'");
  1789. }
  1790. else
  1791. {
  1792. palette = createPalette();
  1793. //Add the palette record after the bof which is always the first record
  1794. records.add(1, palette);
  1795. records.setPalettepos(1);
  1796. }
  1797. return palette;
  1798. }
  1799. /**
  1800. * Finds the primary drawing group, if one already exists
  1801. */
  1802. public DrawingManager2 findDrawingGroup() {
  1803. if(drawingManager != null) {
  1804. // We already have it!
  1805. return drawingManager;
  1806. }
  1807. // Need to find a DrawingGroupRecord that
  1808. // contains a EscherDggRecord
  1809. for(Record r : records) {
  1810. if(r instanceof DrawingGroupRecord) {
  1811. DrawingGroupRecord dg = (DrawingGroupRecord)r;
  1812. dg.processChildRecords();
  1813. EscherContainerRecord cr =
  1814. dg.getEscherContainer();
  1815. if(cr == null) {
  1816. continue;
  1817. }
  1818. EscherDggRecord dgg = null;
  1819. EscherContainerRecord bStore = null;
  1820. for(Iterator<EscherRecord> it = cr.getChildIterator(); it.hasNext();) {
  1821. EscherRecord er = it.next();
  1822. if(er instanceof EscherDggRecord) {
  1823. dgg = (EscherDggRecord)er;
  1824. } else if (er.getRecordId() == EscherContainerRecord.BSTORE_CONTAINER) {
  1825. bStore = (EscherContainerRecord) er;
  1826. }
  1827. }
  1828. if(dgg != null) {
  1829. drawingManager = new DrawingManager2(dgg);
  1830. if(bStore != null){
  1831. for(EscherRecord bs : bStore.getChildRecords()){
  1832. if(bs instanceof EscherBSERecord) escherBSERecords.add((EscherBSERecord)bs);
  1833. }
  1834. }
  1835. return drawingManager;
  1836. }
  1837. }
  1838. }
  1839. // Look for the DrawingGroup record
  1840. int dgLoc = findFirstRecordLocBySid(DrawingGroupRecord.sid);
  1841. // If there is one, does it have a EscherDggRecord?
  1842. if(dgLoc != -1) {
  1843. DrawingGroupRecord dg = (DrawingGroupRecord)records.get(dgLoc);
  1844. EscherDggRecord dgg = null;
  1845. EscherContainerRecord bStore = null;
  1846. for(EscherRecord er : dg.getEscherRecords()) {
  1847. if (er instanceof EscherDggRecord) {
  1848. dgg = (EscherDggRecord) er;
  1849. } else if (er.getRecordId() == EscherContainerRecord.BSTORE_CONTAINER) {
  1850. bStore = (EscherContainerRecord) er;
  1851. }
  1852. }
  1853. if(dgg != null) {
  1854. drawingManager = new DrawingManager2(dgg);
  1855. if(bStore != null){
  1856. for(EscherRecord bs : bStore.getChildRecords()){
  1857. if(bs instanceof EscherBSERecord) escherBSERecords.add((EscherBSERecord)bs);
  1858. }
  1859. }
  1860. }
  1861. }
  1862. return drawingManager;
  1863. }
  1864. /**
  1865. * Creates a primary drawing group record. If it already
  1866. * exists then it's modified.
  1867. */
  1868. public void createDrawingGroup() {
  1869. if (drawingManager == null) {
  1870. EscherContainerRecord dggContainer = new EscherContainerRecord();
  1871. EscherDggRecord dgg = new EscherDggRecord();
  1872. EscherOptRecord opt = new EscherOptRecord();
  1873. EscherSplitMenuColorsRecord splitMenuColors = new EscherSplitMenuColorsRecord();
  1874. dggContainer.setRecordId((short) 0xF000);
  1875. dggContainer.setOptions((short) 0x000F);
  1876. dgg.setRecordId(EscherDggRecord.RECORD_ID);
  1877. dgg.setOptions((short)0x0000);
  1878. dgg.setShapeIdMax(1024);
  1879. dgg.setNumShapesSaved(0);
  1880. dgg.setDrawingsSaved(0);
  1881. dgg.setFileIdClusters(new EscherDggRecord.FileIdCluster[] {} );
  1882. drawingManager = new DrawingManager2(dgg);
  1883. EscherContainerRecord bstoreContainer = null;
  1884. if (escherBSERecords.size() > 0)
  1885. {
  1886. bstoreContainer = new EscherContainerRecord();
  1887. bstoreContainer.setRecordId( EscherContainerRecord.BSTORE_CONTAINER );
  1888. bstoreContainer.setOptions( (short) ( (escherBSERecords.size() << 4) | 0xF ) );
  1889. for (EscherRecord escherRecord : escherBSERecords) {
  1890. bstoreContainer.addChildRecord( escherRecord );
  1891. }
  1892. }
  1893. opt.setRecordId((short) 0xF00B);
  1894. opt.setOptions((short) 0x0033);
  1895. opt.addEscherProperty( new EscherBoolProperty(EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 524296) );
  1896. opt.addEscherProperty( new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, 0x08000041) );
  1897. opt.addEscherProperty( new EscherRGBProperty(EscherProperties.LINESTYLE__COLOR, 134217792) );
  1898. splitMenuColors.setRecordId((short) 0xF11E);
  1899. splitMenuColors.setOptions((short) 0x0040);
  1900. splitMenuColors.setColor1(0x0800000D);
  1901. splitMenuColors.setColor2(0x0800000C);
  1902. splitMenuColors.setColor3(0x08000017);
  1903. splitMenuColors.setColor4(0x100000F7);
  1904. dggContainer.addChildRecord(dgg);
  1905. if (bstoreContainer != null)
  1906. dggContainer.addChildRecord( bstoreContainer );
  1907. dggContainer.addChildRecord(opt);
  1908. dggContainer.addChildRecord(splitMenuColors);
  1909. int dgLoc = findFirstRecordLocBySid(DrawingGroupRecord.sid);
  1910. if (dgLoc == -1) {
  1911. DrawingGroupRecord drawingGroup = new DrawingGroupRecord();
  1912. drawingGroup.addEscherRecord(dggContainer);
  1913. int loc = findFirstRecordLocBySid(CountryRecord.sid);
  1914. getRecords().add(loc+1, drawingGroup);
  1915. } else {
  1916. DrawingGroupRecord drawingGroup = new DrawingGroupRecord();
  1917. drawingGroup.addEscherRecord(dggContainer);
  1918. getRecords().set(dgLoc, drawingGroup);
  1919. }
  1920. }
  1921. }
  1922. public WindowOneRecord getWindowOne() {
  1923. return windowOne;
  1924. }
  1925. public EscherBSERecord getBSERecord(int pictureIndex) {
  1926. return escherBSERecords.get(pictureIndex-1);
  1927. }
  1928. public int addBSERecord(EscherBSERecord e) {
  1929. createDrawingGroup();
  1930. // maybe we don't need that as an instance variable anymore
  1931. escherBSERecords.add( e );
  1932. int dgLoc = findFirstRecordLocBySid(DrawingGroupRecord.sid);
  1933. DrawingGroupRecord drawingGroup = (DrawingGroupRecord) getRecords().get( dgLoc );
  1934. EscherContainerRecord dggContainer = (EscherContainerRecord) drawingGroup.getEscherRecord( 0 );
  1935. EscherContainerRecord bstoreContainer;
  1936. if (dggContainer.getChild( 1 ).getRecordId() == EscherContainerRecord.BSTORE_CONTAINER )
  1937. {
  1938. bstoreContainer = (EscherContainerRecord) dggContainer.getChild( 1 );
  1939. }
  1940. else
  1941. {
  1942. bstoreContainer = new EscherContainerRecord();
  1943. bstoreContainer.setRecordId( EscherContainerRecord.BSTORE_CONTAINER );
  1944. List<EscherRecord> childRecords = dggContainer.getChildRecords();
  1945. childRecords.add(1, bstoreContainer);
  1946. dggContainer.setChildRecords(childRecords);
  1947. }
  1948. bstoreContainer.setOptions( (short) ( (escherBSERecords.size() << 4) | 0xF ) );
  1949. bstoreContainer.addChildRecord( e );
  1950. return escherBSERecords.size();
  1951. }
  1952. public DrawingManager2 getDrawingManager()
  1953. {
  1954. return drawingManager;
  1955. }
  1956. public WriteProtectRecord getWriteProtect() {
  1957. if (writeProtect == null) {
  1958. writeProtect = new WriteProtectRecord();
  1959. int i = 0;
  1960. for (i = 0;
  1961. i < records.size() && !(records.get(i) instanceof BOFRecord);
  1962. i++) {
  1963. }
  1964. records.add(i+1, writeProtect);
  1965. }
  1966. return this.writeProtect;
  1967. }
  1968. public WriteAccessRecord getWriteAccess() {
  1969. if (writeAccess == null) {
  1970. writeAccess = createWriteAccess();
  1971. int i = 0;
  1972. for (i = 0;
  1973. i < records.size() && !(records.get(i) instanceof InterfaceEndRecord);
  1974. i++) {
  1975. }
  1976. records.add(i+1, writeAccess);
  1977. }
  1978. return writeAccess;
  1979. }
  1980. public FileSharingRecord getFileSharing() {
  1981. if (fileShare == null) {
  1982. fileShare = new FileSharingRecord();
  1983. int i = 0;
  1984. for (i = 0;
  1985. i < records.size() && !(records.get(i) instanceof WriteAccessRecord);
  1986. i++) {
  1987. }
  1988. records.add(i+1, fileShare);
  1989. }
  1990. return fileShare;
  1991. }
  1992. /**
  1993. * is the workbook protected with a password (not encrypted)?
  1994. */
  1995. public boolean isWriteProtected() {
  1996. if (fileShare == null) {
  1997. return false;
  1998. }
  1999. FileSharingRecord frec = getFileSharing();
  2000. return frec.getReadOnly() == 1;
  2001. }
  2002. /**
  2003. * protect a workbook with a password (not encypted, just sets writeprotect
  2004. * flags and the password.
  2005. * @param password to set
  2006. */
  2007. public void writeProtectWorkbook( String password, String username ) {
  2008. FileSharingRecord frec = getFileSharing();
  2009. WriteAccessRecord waccess = getWriteAccess();
  2010. /* WriteProtectRecord wprotect =*/ getWriteProtect();
  2011. frec.setReadOnly((short)1);
  2012. frec.setPassword(FileSharingRecord.hashPassword(password));
  2013. frec.setUsername(username);
  2014. waccess.setUsername(username);
  2015. }
  2016. /**
  2017. * removes the write protect flag
  2018. */
  2019. public void unwriteProtectWorkbook() {
  2020. records.remove(fileShare);
  2021. records.remove(writeProtect);
  2022. fileShare = null;
  2023. writeProtect = null;
  2024. }
  2025. /**
  2026. * @param refIndex Index to REF entry in EXTERNSHEET record in the Link Table
  2027. * @param definedNameIndex zero-based to DEFINEDNAME or EXTERNALNAME record
  2028. * @return the string representation of the defined or external name
  2029. */
  2030. public String resolveNameXText(int refIndex, int definedNameIndex) {
  2031. return linkTable.resolveNameXText(refIndex, definedNameIndex);
  2032. }
  2033. /**
  2034. *
  2035. * @param name the name of an external function, typically a name of a UDF
  2036. * @param udf locator of user-defiend functions to resolve names of VBA and Add-In functions
  2037. * @return the external name or null
  2038. */
  2039. public NameXPtg getNameXPtg(String name, UDFFinder udf) {
  2040. LinkTable lnk = getOrCreateLinkTable();
  2041. NameXPtg xptg = lnk.getNameXPtg(name);
  2042. if(xptg == null && udf.findFunction(name) != null) {
  2043. // the name was not found in the list of external names
  2044. // check if the Workbook's UDFFinder is aware about it and register the name if it is
  2045. xptg = lnk.addNameXPtg(name);
  2046. }
  2047. return xptg;
  2048. }
  2049. /**
  2050. * Check if the cloned sheet has drawings. If yes, then allocate a new drawing group ID and
  2051. * re-generate shape IDs
  2052. *
  2053. * @param sheet the cloned sheet
  2054. */
  2055. public void cloneDrawings(InternalSheet sheet){
  2056. findDrawingGroup();
  2057. if(drawingManager == null) {
  2058. //this workbook does not have drawings
  2059. return;
  2060. }
  2061. //check if the cloned sheet has drawings
  2062. int aggLoc = sheet.aggregateDrawingRecords(drawingManager, false);
  2063. if(aggLoc != -1) {
  2064. EscherAggregate agg = (EscherAggregate) sheet.findFirstRecordBySid(EscherAggregate.sid);
  2065. EscherContainerRecord escherContainer = agg.getEscherContainer();
  2066. if (escherContainer == null) {
  2067. return;
  2068. }
  2069. EscherDggRecord dgg = drawingManager.getDgg();
  2070. //register a new drawing group for the cloned sheet
  2071. int dgId = drawingManager.findNewDrawingGroupId();
  2072. dgg.addCluster( dgId, 0 );
  2073. dgg.setDrawingsSaved(dgg.getDrawingsSaved() + 1);
  2074. EscherDgRecord dg = null;
  2075. for(Iterator<EscherRecord> it = escherContainer.getChildIterator(); it.hasNext();) {
  2076. EscherRecord er = it.next();
  2077. if(er instanceof EscherDgRecord) {
  2078. dg = (EscherDgRecord)er;
  2079. //update id of the drawing in the cloned sheet
  2080. dg.setOptions( (short) ( dgId << 4 ) );
  2081. } else if (er instanceof EscherContainerRecord){
  2082. // iterate over shapes and re-generate shapeId
  2083. EscherContainerRecord cp = (EscherContainerRecord)er;
  2084. for(Iterator<EscherRecord> spIt = cp.getChildRecords().iterator(); spIt.hasNext();) {
  2085. EscherContainerRecord shapeContainer = (EscherContainerRecord)spIt.next();
  2086. for(EscherRecord shapeChildRecord : shapeContainer.getChildRecords()) {
  2087. int recordId = shapeChildRecord.getRecordId();
  2088. if (recordId == EscherSpRecord.RECORD_ID){
  2089. EscherSpRecord sp = (EscherSpRecord)shapeChildRecord;
  2090. int shapeId = drawingManager.allocateShapeId((short)dgId, dg);
  2091. //allocateShapeId increments the number of shapes. roll back to the previous value
  2092. dg.setNumShapes(dg.getNumShapes()-1);
  2093. sp.setShapeId(shapeId);
  2094. } else if (recordId == EscherOptRecord.RECORD_ID){
  2095. EscherOptRecord opt = (EscherOptRecord)shapeChildRecord;
  2096. EscherSimpleProperty prop = (EscherSimpleProperty)opt.lookup(
  2097. EscherProperties.BLIP__BLIPTODISPLAY );
  2098. if (prop != null){
  2099. int pictureIndex = prop.getPropertyValue();
  2100. // increment reference count for pictures
  2101. EscherBSERecord bse = getBSERecord(pictureIndex);
  2102. bse.setRef(bse.getRef() + 1);
  2103. }
  2104. }
  2105. }
  2106. }
  2107. }
  2108. }
  2109. }
  2110. }
  2111. public NameRecord cloneFilter(int filterDbNameIndex, int newSheetIndex){
  2112. NameRecord origNameRecord = getNameRecord(filterDbNameIndex);
  2113. // copy original formula but adjust 3D refs to the new external sheet index
  2114. int newExtSheetIx = checkExternSheet(newSheetIndex);
  2115. Ptg[] ptgs = origNameRecord.getNameDefinition();
  2116. for (int i=0; i< ptgs.length; i++) {
  2117. Ptg ptg = ptgs[i];
  2118. if (ptg instanceof Area3DPtg) {
  2119. Area3DPtg a3p = (Area3DPtg) ((OperandPtg) ptg).copy();
  2120. a3p.setExternSheetIndex(newExtSheetIx);
  2121. ptgs[i] = a3p;
  2122. } else if (ptg instanceof Ref3DPtg) {
  2123. Ref3DPtg r3p = (Ref3DPtg) ((OperandPtg) ptg).copy();
  2124. r3p.setExternSheetIndex(newExtSheetIx);
  2125. ptgs[i] = r3p;
  2126. }
  2127. }
  2128. NameRecord newNameRecord = createBuiltInName(NameRecord.BUILTIN_FILTER_DB, newSheetIndex+1);
  2129. newNameRecord.setNameDefinition(ptgs);
  2130. newNameRecord.setHidden(true);
  2131. return newNameRecord;
  2132. }
  2133. /**
  2134. * Updates named ranges due to moving of cells
  2135. */
  2136. public void updateNamesAfterCellShift(FormulaShifter shifter) {
  2137. for (int i = 0 ; i < getNumNames() ; ++i){
  2138. NameRecord nr = getNameRecord(i);
  2139. Ptg[] ptgs = nr.getNameDefinition();
  2140. if (shifter.adjustFormula(ptgs, nr.getSheetNumber())) {
  2141. nr.setNameDefinition(ptgs);
  2142. }
  2143. }
  2144. }
  2145. /**
  2146. * Get or create RecalcIdRecord
  2147. *
  2148. * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#setForceFormulaRecalculation(boolean)
  2149. */
  2150. public RecalcIdRecord getRecalcId(){
  2151. RecalcIdRecord record = (RecalcIdRecord)findFirstRecordBySid(RecalcIdRecord.sid);
  2152. if(record == null){
  2153. record = new RecalcIdRecord();
  2154. // typically goes after the Country record
  2155. int pos = findFirstRecordLocBySid(CountryRecord.sid);
  2156. records.add(pos + 1, record);
  2157. }
  2158. return record;
  2159. }
  2160. /**
  2161. * Changes an external referenced file to another file.
  2162. * A formular in Excel which refers a cell in another file is saved in two parts:
  2163. * The referenced file is stored in an reference table. the row/cell information is saved separate.
  2164. * This method invokation will only change the reference in the lookup-table itself.
  2165. * @param oldUrl The old URL to search for and which is to be replaced
  2166. * @param newUrl The URL replacement
  2167. * @return true if the oldUrl was found and replaced with newUrl. Otherwise false
  2168. */
  2169. public boolean changeExternalReference(String oldUrl, String newUrl) {
  2170. return linkTable.changeExternalReference(oldUrl, newUrl);
  2171. }
  2172. }