Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

InternalWorkbook.java 79KB

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