Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

LinkTable.java 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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.util.ArrayList;
  17. import java.util.Iterator;
  18. import java.util.List;
  19. import java.util.Map;
  20. import org.apache.poi.hssf.record.CRNCountRecord;
  21. import org.apache.poi.hssf.record.CRNRecord;
  22. import org.apache.poi.hssf.record.CountryRecord;
  23. import org.apache.poi.hssf.record.ExternSheetRecord;
  24. import org.apache.poi.hssf.record.ExternalNameRecord;
  25. import org.apache.poi.hssf.record.NameCommentRecord;
  26. import org.apache.poi.hssf.record.NameRecord;
  27. import org.apache.poi.hssf.record.Record;
  28. import org.apache.poi.hssf.record.SupBookRecord;
  29. import org.apache.poi.ss.formula.SheetNameFormatter;
  30. import org.apache.poi.ss.formula.ptg.Area3DPtg;
  31. import org.apache.poi.ss.formula.ptg.ErrPtg;
  32. import org.apache.poi.ss.formula.ptg.NameXPtg;
  33. import org.apache.poi.ss.formula.ptg.Ptg;
  34. import org.apache.poi.ss.formula.ptg.Ref3DPtg;
  35. import org.apache.poi.ss.usermodel.Workbook;
  36. /**
  37. * Link Table (OOO pdf reference: 4.10.3 ) <p/>
  38. *
  39. * The main data of all types of references is stored in the Link Table inside the Workbook Globals
  40. * Substream (4.2.5). The Link Table itself is optional and occurs only if there are any
  41. * references in the document.
  42. * <p/>
  43. *
  44. * In BIFF8 the Link Table consists of
  45. * <ul>
  46. * <li>zero or more EXTERNALBOOK Blocks<p/>
  47. * each consisting of
  48. * <ul>
  49. * <li>exactly one EXTERNALBOOK (0x01AE) record</li>
  50. * <li>zero or more EXTERNALNAME (0x0023) records</li>
  51. * <li>zero or more CRN Blocks<p/>
  52. * each consisting of
  53. * <ul>
  54. * <li>exactly one XCT (0x0059)record</li>
  55. * <li>zero or more CRN (0x005A) records (documentation says one or more)</li>
  56. * </ul>
  57. * </li>
  58. * </ul>
  59. * </li>
  60. * <li>zero or one EXTERNSHEET (0x0017) record</li>
  61. * <li>zero or more DEFINEDNAME (0x0018) records</li>
  62. * </ul>
  63. */
  64. final class LinkTable {
  65. // TODO make this class into a record aggregate
  66. private static final class CRNBlock {
  67. private final CRNCountRecord _countRecord;
  68. private final CRNRecord[] _crns;
  69. public CRNBlock(RecordStream rs) {
  70. _countRecord = (CRNCountRecord) rs.getNext();
  71. int nCRNs = _countRecord.getNumberOfCRNs();
  72. CRNRecord[] crns = new CRNRecord[nCRNs];
  73. for (int i = 0; i < crns.length; i++) {
  74. crns[i] = (CRNRecord) rs.getNext();
  75. }
  76. _crns = crns;
  77. }
  78. public CRNRecord[] getCrns() {
  79. return _crns.clone();
  80. }
  81. }
  82. private static final class ExternalBookBlock {
  83. private final SupBookRecord _externalBookRecord;
  84. private ExternalNameRecord[] _externalNameRecords;
  85. private final CRNBlock[] _crnBlocks;
  86. public ExternalBookBlock(RecordStream rs) {
  87. _externalBookRecord = (SupBookRecord) rs.getNext();
  88. List<Object> temp = new ArrayList<Object>();
  89. while(rs.peekNextClass() == ExternalNameRecord.class) {
  90. temp.add(rs.getNext());
  91. }
  92. _externalNameRecords = new ExternalNameRecord[temp.size()];
  93. temp.toArray(_externalNameRecords);
  94. temp.clear();
  95. while(rs.peekNextClass() == CRNCountRecord.class) {
  96. temp.add(new CRNBlock(rs));
  97. }
  98. _crnBlocks = new CRNBlock[temp.size()];
  99. temp.toArray(_crnBlocks);
  100. }
  101. /**
  102. * Create a new block for external references.
  103. */
  104. public ExternalBookBlock(String url, String[] sheetNames) {
  105. _externalBookRecord = SupBookRecord.createExternalReferences(url, sheetNames);
  106. _crnBlocks = new CRNBlock[0];
  107. }
  108. /**
  109. * Create a new block for internal references. It is called when constructing a new LinkTable.
  110. *
  111. * @see org.apache.poi.hssf.model.LinkTable#LinkTable(int, WorkbookRecordList)
  112. */
  113. public ExternalBookBlock(int numberOfSheets) {
  114. _externalBookRecord = SupBookRecord.createInternalReferences((short)numberOfSheets);
  115. _externalNameRecords = new ExternalNameRecord[0];
  116. _crnBlocks = new CRNBlock[0];
  117. }
  118. /**
  119. * Create a new block for registering add-in functions
  120. *
  121. * @see org.apache.poi.hssf.model.LinkTable#addNameXPtg(String)
  122. */
  123. public ExternalBookBlock() {
  124. _externalBookRecord = SupBookRecord.createAddInFunctions();
  125. _externalNameRecords = new ExternalNameRecord[0];
  126. _crnBlocks = new CRNBlock[0];
  127. }
  128. public SupBookRecord getExternalBookRecord() {
  129. return _externalBookRecord;
  130. }
  131. public String getNameText(int definedNameIndex) {
  132. return _externalNameRecords[definedNameIndex].getText();
  133. }
  134. public int getNameIx(int definedNameIndex) {
  135. return _externalNameRecords[definedNameIndex].getIx();
  136. }
  137. /**
  138. * Performs case-insensitive search
  139. * @return -1 if not found
  140. */
  141. public int getIndexOfName(String name) {
  142. for (int i = 0; i < _externalNameRecords.length; i++) {
  143. if(_externalNameRecords[i].getText().equalsIgnoreCase(name)) {
  144. return i;
  145. }
  146. }
  147. return -1;
  148. }
  149. public int getNumberOfNames() {
  150. return _externalNameRecords.length;
  151. }
  152. public int addExternalName(ExternalNameRecord rec){
  153. ExternalNameRecord[] tmp = new ExternalNameRecord[_externalNameRecords.length + 1];
  154. System.arraycopy(_externalNameRecords, 0, tmp, 0, _externalNameRecords.length);
  155. tmp[tmp.length - 1] = rec;
  156. _externalNameRecords = tmp;
  157. return _externalNameRecords.length - 1;
  158. }
  159. }
  160. private ExternalBookBlock[] _externalBookBlocks;
  161. private final ExternSheetRecord _externSheetRecord;
  162. private final List<NameRecord> _definedNames;
  163. private final int _recordCount;
  164. private final WorkbookRecordList _workbookRecordList; // TODO - would be nice to remove this
  165. public LinkTable(List<Record> inputList, int startIndex, WorkbookRecordList workbookRecordList, Map<String, NameCommentRecord> commentRecords) {
  166. _workbookRecordList = workbookRecordList;
  167. RecordStream rs = new RecordStream(inputList, startIndex);
  168. List<ExternalBookBlock> temp = new ArrayList<ExternalBookBlock>();
  169. while(rs.peekNextClass() == SupBookRecord.class) {
  170. temp.add(new ExternalBookBlock(rs));
  171. }
  172. _externalBookBlocks = new ExternalBookBlock[temp.size()];
  173. temp.toArray(_externalBookBlocks);
  174. temp.clear();
  175. if (_externalBookBlocks.length > 0) {
  176. // If any ExternalBookBlock present, there is always 1 of ExternSheetRecord
  177. if (rs.peekNextClass() != ExternSheetRecord.class) {
  178. // not quite - if written by google docs
  179. _externSheetRecord = null;
  180. } else {
  181. _externSheetRecord = readExtSheetRecord(rs);
  182. }
  183. } else {
  184. _externSheetRecord = null;
  185. }
  186. _definedNames = new ArrayList<NameRecord>();
  187. // collect zero or more DEFINEDNAMEs id=0x18,
  188. // with their comments if present
  189. while(true) {
  190. Class<? extends Record> nextClass = rs.peekNextClass();
  191. if (nextClass == NameRecord.class) {
  192. NameRecord nr = (NameRecord)rs.getNext();
  193. _definedNames.add(nr);
  194. }
  195. else if (nextClass == NameCommentRecord.class) {
  196. NameCommentRecord ncr = (NameCommentRecord)rs.getNext();
  197. commentRecords.put(ncr.getNameText(), ncr);
  198. }
  199. else {
  200. break;
  201. }
  202. }
  203. _recordCount = rs.getCountRead();
  204. _workbookRecordList.getRecords().addAll(inputList.subList(startIndex, startIndex + _recordCount));
  205. }
  206. private static ExternSheetRecord readExtSheetRecord(RecordStream rs) {
  207. List<ExternSheetRecord> temp = new ArrayList<ExternSheetRecord>(2);
  208. while(rs.peekNextClass() == ExternSheetRecord.class) {
  209. temp.add((ExternSheetRecord) rs.getNext());
  210. }
  211. int nItems = temp.size();
  212. if (nItems < 1) {
  213. throw new RuntimeException("Expected an EXTERNSHEET record but got ("
  214. + rs.peekNextClass().getName() + ")");
  215. }
  216. if (nItems == 1) {
  217. // this is the normal case. There should be just one ExternSheetRecord
  218. return temp.get(0);
  219. }
  220. // Some apps generate multiple ExternSheetRecords (see bug 45698).
  221. // It seems like the best thing to do might be to combine these into one
  222. ExternSheetRecord[] esrs = new ExternSheetRecord[nItems];
  223. temp.toArray(esrs);
  224. return ExternSheetRecord.combine(esrs);
  225. }
  226. public LinkTable(int numberOfSheets, WorkbookRecordList workbookRecordList) {
  227. _workbookRecordList = workbookRecordList;
  228. _definedNames = new ArrayList<NameRecord>();
  229. _externalBookBlocks = new ExternalBookBlock[] {
  230. new ExternalBookBlock(numberOfSheets),
  231. };
  232. _externSheetRecord = new ExternSheetRecord();
  233. _recordCount = 2;
  234. // tell _workbookRecordList about the 2 new records
  235. SupBookRecord supbook = _externalBookBlocks[0].getExternalBookRecord();
  236. int idx = findFirstRecordLocBySid(CountryRecord.sid);
  237. if(idx < 0) {
  238. throw new RuntimeException("CountryRecord not found");
  239. }
  240. _workbookRecordList.add(idx+1, _externSheetRecord);
  241. _workbookRecordList.add(idx+1, supbook);
  242. }
  243. /**
  244. * TODO - would not be required if calling code used RecordStream or similar
  245. */
  246. public int getRecordCount() {
  247. return _recordCount;
  248. }
  249. /**
  250. * @param builtInCode a BUILTIN_~ constant from {@link NameRecord}
  251. * @param sheetNumber 1-based sheet number
  252. */
  253. public NameRecord getSpecificBuiltinRecord(byte builtInCode, int sheetNumber) {
  254. Iterator<NameRecord> iterator = _definedNames.iterator();
  255. while (iterator.hasNext()) {
  256. NameRecord record = iterator.next();
  257. //print areas are one based
  258. if (record.getBuiltInName() == builtInCode && record.getSheetNumber() == sheetNumber) {
  259. return record;
  260. }
  261. }
  262. return null;
  263. }
  264. public void removeBuiltinRecord(byte name, int sheetIndex) {
  265. //the name array is smaller so searching through it should be faster than
  266. //using the findFirstXXXX methods
  267. NameRecord record = getSpecificBuiltinRecord(name, sheetIndex);
  268. if (record != null) {
  269. _definedNames.remove(record);
  270. }
  271. // TODO - do we need "Workbook.records.remove(...);" similar to that in Workbook.removeName(int namenum) {}?
  272. }
  273. public int getNumNames() {
  274. return _definedNames.size();
  275. }
  276. public NameRecord getNameRecord(int index) {
  277. return _definedNames.get(index);
  278. }
  279. public void addName(NameRecord name) {
  280. _definedNames.add(name);
  281. // TODO - this is messy
  282. // Not the most efficient way but the other way was causing too many bugs
  283. int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
  284. if (idx == -1) idx = findFirstRecordLocBySid(SupBookRecord.sid);
  285. if (idx == -1) idx = findFirstRecordLocBySid(CountryRecord.sid);
  286. int countNames = _definedNames.size();
  287. _workbookRecordList.add(idx+countNames, name);
  288. }
  289. public void removeName(int namenum) {
  290. _definedNames.remove(namenum);
  291. }
  292. /**
  293. * checks if the given name is already included in the linkTable
  294. */
  295. public boolean nameAlreadyExists(NameRecord name)
  296. {
  297. // Check to ensure no other names have the same case-insensitive name
  298. for ( int i = getNumNames()-1; i >=0; i-- ) {
  299. NameRecord rec = getNameRecord(i);
  300. if (rec != name) {
  301. if (isDuplicatedNames(name, rec))
  302. return true;
  303. }
  304. }
  305. return false;
  306. }
  307. private static boolean isDuplicatedNames(NameRecord firstName, NameRecord lastName) {
  308. return lastName.getNameText().equalsIgnoreCase(firstName.getNameText())
  309. && isSameSheetNames(firstName, lastName);
  310. }
  311. private static boolean isSameSheetNames(NameRecord firstName, NameRecord lastName) {
  312. return lastName.getSheetNumber() == firstName.getSheetNumber();
  313. }
  314. public String[] getExternalBookAndSheetName(int extRefIndex) {
  315. int ebIx = _externSheetRecord.getExtbookIndexFromRefIndex(extRefIndex);
  316. SupBookRecord ebr = _externalBookBlocks[ebIx].getExternalBookRecord();
  317. if (!ebr.isExternalReferences()) {
  318. return null;
  319. }
  320. // Sheet name only applies if not a global reference
  321. int shIx1 = _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
  322. int shIx2 = _externSheetRecord.getLastSheetIndexFromRefIndex(extRefIndex);
  323. String firstSheetName = null;
  324. String lastSheetName = null;
  325. if(shIx1 >= 0) {
  326. firstSheetName = ebr.getSheetNames()[shIx1];
  327. }
  328. if (shIx2 >= 0) {
  329. lastSheetName = ebr.getSheetNames()[shIx2];
  330. }
  331. if (shIx1 == shIx2) {
  332. return new String[] {
  333. ebr.getURL(),
  334. firstSheetName
  335. };
  336. } else {
  337. return new String[] {
  338. ebr.getURL(),
  339. firstSheetName,
  340. lastSheetName
  341. };
  342. }
  343. }
  344. private int getExternalWorkbookIndex(String workbookName) {
  345. for (int i=0; i<_externalBookBlocks.length; i++) {
  346. SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
  347. if (!ebr.isExternalReferences()) {
  348. continue;
  349. }
  350. if (workbookName.equals(ebr.getURL())) { // not sure if 'equals()' works when url has a directory
  351. return i;
  352. }
  353. }
  354. return -1;
  355. }
  356. public int linkExternalWorkbook(String name, Workbook externalWorkbook) {
  357. int extBookIndex = getExternalWorkbookIndex(name);
  358. if (extBookIndex != -1) {
  359. // Already linked!
  360. return extBookIndex;
  361. }
  362. // Create a new SupBookRecord
  363. String[] sheetNames = new String[externalWorkbook.getNumberOfSheets()];
  364. for (int sn=0; sn<sheetNames.length; sn++) {
  365. sheetNames[sn] = externalWorkbook.getSheetName(sn);
  366. }
  367. String url = "\000" + name;
  368. ExternalBookBlock block = new ExternalBookBlock(url, sheetNames);
  369. // Add it into the list + records
  370. extBookIndex = extendExternalBookBlocks(block);
  371. // add the created SupBookRecord before ExternSheetRecord
  372. int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
  373. if (idx == -1) {
  374. idx = _workbookRecordList.size();
  375. }
  376. _workbookRecordList.add(idx, block.getExternalBookRecord());
  377. // Setup links for the sheets
  378. for (int sn=0; sn<sheetNames.length; sn++) {
  379. _externSheetRecord.addRef(extBookIndex, sn, sn);
  380. }
  381. // Report where it went
  382. return extBookIndex;
  383. }
  384. public int getExternalSheetIndex(String workbookName, String firstSheetName, String lastSheetName) {
  385. int externalBookIndex = getExternalWorkbookIndex(workbookName);
  386. if (externalBookIndex == -1) {
  387. throw new RuntimeException("No external workbook with name '" + workbookName + "'");
  388. }
  389. SupBookRecord ebrTarget = _externalBookBlocks[externalBookIndex].getExternalBookRecord();
  390. int firstSheetIndex = getSheetIndex(ebrTarget.getSheetNames(), firstSheetName);
  391. int lastSheetIndex = getSheetIndex(ebrTarget.getSheetNames(), lastSheetName);
  392. // Find or add the external sheet record definition for this
  393. int result = _externSheetRecord.getRefIxForSheet(externalBookIndex, firstSheetIndex, lastSheetIndex);
  394. if (result < 0) {
  395. result = _externSheetRecord.addRef(externalBookIndex, firstSheetIndex, lastSheetIndex);
  396. }
  397. return result;
  398. }
  399. private static int getSheetIndex(String[] sheetNames, String sheetName) {
  400. for (int i = 0; i < sheetNames.length; i++) {
  401. if (sheetNames[i].equals(sheetName)) {
  402. return i;
  403. }
  404. }
  405. throw new RuntimeException("External workbook does not contain sheet '" + sheetName + "'");
  406. }
  407. /**
  408. * @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
  409. * @return -1 if the reference is to an external book
  410. */
  411. public int getFirstInternalSheetIndexForExtIndex(int extRefIndex) {
  412. if (extRefIndex >= _externSheetRecord.getNumOfRefs() || extRefIndex < 0) {
  413. return -1;
  414. }
  415. return _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
  416. }
  417. /**
  418. * @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
  419. * @return -1 if the reference is to an external book
  420. */
  421. public int getLastInternalSheetIndexForExtIndex(int extRefIndex) {
  422. if (extRefIndex >= _externSheetRecord.getNumOfRefs() || extRefIndex < 0) {
  423. return -1;
  424. }
  425. return _externSheetRecord.getLastSheetIndexFromRefIndex(extRefIndex);
  426. }
  427. public void removeSheet(int sheetIdx) {
  428. _externSheetRecord.removeSheet(sheetIdx);
  429. }
  430. public int checkExternSheet(int sheetIndex) {
  431. return checkExternSheet(sheetIndex, sheetIndex);
  432. }
  433. public int checkExternSheet(int firstSheetIndex, int lastSheetIndex) {
  434. int thisWbIndex = -1; // this is probably always zero
  435. for (int i=0; i<_externalBookBlocks.length; i++) {
  436. SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
  437. if (ebr.isInternalReferences()) {
  438. thisWbIndex = i;
  439. break;
  440. }
  441. }
  442. if (thisWbIndex < 0) {
  443. throw new RuntimeException("Could not find 'internal references' EXTERNALBOOK");
  444. }
  445. //Trying to find reference to this sheet
  446. int i = _externSheetRecord.getRefIxForSheet(thisWbIndex, firstSheetIndex, lastSheetIndex);
  447. if (i>=0) {
  448. return i;
  449. }
  450. //We haven't found reference to this sheet
  451. return _externSheetRecord.addRef(thisWbIndex, firstSheetIndex, lastSheetIndex);
  452. }
  453. /**
  454. * copied from Workbook
  455. */
  456. private int findFirstRecordLocBySid(short sid) {
  457. int index = 0;
  458. for (Iterator<Record> iterator = _workbookRecordList.iterator(); iterator.hasNext(); ) {
  459. Record record = iterator.next();
  460. if (record.getSid() == sid) {
  461. return index;
  462. }
  463. index ++;
  464. }
  465. return -1;
  466. }
  467. public String resolveNameXText(int refIndex, int definedNameIndex, InternalWorkbook workbook) {
  468. int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
  469. int firstTabIndex = _externSheetRecord.getFirstSheetIndexFromRefIndex(refIndex);
  470. if (firstTabIndex == -1) {
  471. // The referenced sheet could not be found
  472. throw new RuntimeException("Referenced sheet could not be found");
  473. }
  474. // Does it exist via the external book block?
  475. ExternalBookBlock externalBook = _externalBookBlocks[extBookIndex];
  476. if (externalBook._externalNameRecords.length > definedNameIndex) {
  477. return _externalBookBlocks[extBookIndex].getNameText(definedNameIndex);
  478. } else if (firstTabIndex == -2) {
  479. // Workbook scoped name, not actually external after all
  480. NameRecord nr = getNameRecord(definedNameIndex);
  481. int sheetNumber = nr.getSheetNumber();
  482. StringBuffer text = new StringBuffer();
  483. if (sheetNumber > 0) {
  484. String sheetName = workbook.getSheetName(sheetNumber-1);
  485. SheetNameFormatter.appendFormat(text, sheetName);
  486. text.append("!");
  487. }
  488. text.append(nr.getNameText());
  489. return text.toString();
  490. } else {
  491. throw new ArrayIndexOutOfBoundsException(
  492. "Ext Book Index relative but beyond the supported length, was " +
  493. extBookIndex + " but maximum is " + _externalBookBlocks.length
  494. );
  495. }
  496. }
  497. public int resolveNameXIx(int refIndex, int definedNameIndex) {
  498. int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
  499. return _externalBookBlocks[extBookIndex].getNameIx(definedNameIndex);
  500. }
  501. /**
  502. * Finds the external name definition for the given name,
  503. * optionally restricted by externsheet index, and returns
  504. * (if found) as a NameXPtg.
  505. * @param sheetRefIndex The Extern Sheet Index to look for, or -1 if any
  506. */
  507. public NameXPtg getNameXPtg(String name, int sheetRefIndex) {
  508. // first find any external book block that contains the name:
  509. for (int i = 0; i < _externalBookBlocks.length; i++) {
  510. int definedNameIndex = _externalBookBlocks[i].getIndexOfName(name);
  511. if (definedNameIndex < 0) {
  512. continue;
  513. }
  514. // Found one
  515. int thisSheetRefIndex = findRefIndexFromExtBookIndex(i);
  516. if (thisSheetRefIndex >= 0) {
  517. // Check for the sheet index match, if requested
  518. if (sheetRefIndex == -1 || thisSheetRefIndex == sheetRefIndex) {
  519. return new NameXPtg(thisSheetRefIndex, definedNameIndex);
  520. }
  521. }
  522. }
  523. return null;
  524. }
  525. /**
  526. * Register an external name in this workbook
  527. *
  528. * @param name the name to register
  529. * @return a NameXPtg describing this name
  530. */
  531. public NameXPtg addNameXPtg(String name) {
  532. int extBlockIndex = -1;
  533. ExternalBookBlock extBlock = null;
  534. // find ExternalBlock for Add-In functions and remember its index
  535. for (int i = 0; i < _externalBookBlocks.length; i++) {
  536. SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
  537. if (ebr.isAddInFunctions()) {
  538. extBlock = _externalBookBlocks[i];
  539. extBlockIndex = i;
  540. break;
  541. }
  542. }
  543. // An ExternalBlock for Add-In functions was not found. Create a new one.
  544. if (extBlock == null) {
  545. extBlock = new ExternalBookBlock();
  546. extBlockIndex = extendExternalBookBlocks(extBlock);
  547. // add the created SupBookRecord before ExternSheetRecord
  548. int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
  549. _workbookRecordList.add(idx, extBlock.getExternalBookRecord());
  550. // register the SupBookRecord in the ExternSheetRecord
  551. // -2 means that the scope of this name is Workbook and the reference applies to the entire workbook.
  552. _externSheetRecord.addRef(_externalBookBlocks.length - 1, -2, -2);
  553. }
  554. // create a ExternalNameRecord that will describe this name
  555. ExternalNameRecord extNameRecord = new ExternalNameRecord();
  556. extNameRecord.setText(name);
  557. // The docs don't explain why Excel set the formula to #REF!
  558. extNameRecord.setParsedExpression(new Ptg[]{ErrPtg.REF_INVALID});
  559. int nameIndex = extBlock.addExternalName(extNameRecord);
  560. int supLinkIndex = 0;
  561. // find the posistion of the Add-In SupBookRecord in the workbook stream,
  562. // the created ExternalNameRecord will be appended to it
  563. for (Iterator<Record> iterator = _workbookRecordList.iterator(); iterator.hasNext(); supLinkIndex++) {
  564. Record record = iterator.next();
  565. if (record instanceof SupBookRecord) {
  566. if (((SupBookRecord) record).isAddInFunctions()) break;
  567. }
  568. }
  569. int numberOfNames = extBlock.getNumberOfNames();
  570. // a new name is inserted in the end of the SupBookRecord, after the last name
  571. _workbookRecordList.add(supLinkIndex + numberOfNames, extNameRecord);
  572. int fakeSheetIdx = -2; /* the scope is workbook*/
  573. int ix = _externSheetRecord.getRefIxForSheet(extBlockIndex, fakeSheetIdx, fakeSheetIdx);
  574. return new NameXPtg(ix, nameIndex);
  575. }
  576. private int extendExternalBookBlocks(ExternalBookBlock newBlock) {
  577. ExternalBookBlock[] tmp = new ExternalBookBlock[_externalBookBlocks.length + 1];
  578. System.arraycopy(_externalBookBlocks, 0, tmp, 0, _externalBookBlocks.length);
  579. tmp[tmp.length - 1] = newBlock;
  580. _externalBookBlocks = tmp;
  581. return (_externalBookBlocks.length - 1);
  582. }
  583. private int findRefIndexFromExtBookIndex(int extBookIndex) {
  584. return _externSheetRecord.findRefIndexFromExtBookIndex(extBookIndex);
  585. }
  586. /**
  587. * Changes an external referenced file to another file.
  588. * A formular in Excel which refers a cell in another file is saved in two parts:
  589. * The referenced file is stored in an reference table. the row/cell information is saved separate.
  590. * This method invokation will only change the reference in the lookup-table itself.
  591. * @param oldUrl The old URL to search for and which is to be replaced
  592. * @param newUrl The URL replacement
  593. * @return true if the oldUrl was found and replaced with newUrl. Otherwise false
  594. */
  595. public boolean changeExternalReference(String oldUrl, String newUrl) {
  596. for(ExternalBookBlock ex : _externalBookBlocks) {
  597. SupBookRecord externalRecord = ex.getExternalBookRecord();
  598. if (externalRecord.isExternalReferences()
  599. && externalRecord.getURL().equals(oldUrl)) {
  600. externalRecord.setURL(newUrl);
  601. return true;
  602. }
  603. }
  604. return false;
  605. }
  606. }