You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LinkTable.java 27KB

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