您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

LinkTable.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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.hssf.record.formula.Area3DPtg;
  30. import org.apache.poi.hssf.record.formula.NameXPtg;
  31. import org.apache.poi.hssf.record.formula.Ref3DPtg;
  32. /**
  33. * Link Table (OOO pdf reference: 4.10.3 ) <p/>
  34. *
  35. * The main data of all types of references is stored in the Link Table inside the Workbook Globals
  36. * Substream (4.2.5). The Link Table itself is optional and occurs only, if there are any
  37. * references in the document.
  38. * <p/>
  39. *
  40. * In BIFF8 the Link Table consists of
  41. * <ul>
  42. * <li>zero or more EXTERNALBOOK Blocks<p/>
  43. * each consisting of
  44. * <ul>
  45. * <li>exactly one EXTERNALBOOK (0x01AE) record</li>
  46. * <li>zero or more EXTERNALNAME (0x0023) records</li>
  47. * <li>zero or more CRN Blocks<p/>
  48. * each consisting of
  49. * <ul>
  50. * <li>exactly one XCT (0x0059)record</li>
  51. * <li>zero or more CRN (0x005A) records (documentation says one or more)</li>
  52. * </ul>
  53. * </li>
  54. * </ul>
  55. * </li>
  56. * <li>zero or one EXTERNSHEET (0x0017) record</li>
  57. * <li>zero or more DEFINEDNAME (0x0018) records</li>
  58. * </ul>
  59. *
  60. *
  61. * @author Josh Micich
  62. */
  63. final class LinkTable {
  64. // TODO make this class into a record aggregate
  65. private static final class CRNBlock {
  66. private final CRNCountRecord _countRecord;
  67. private final CRNRecord[] _crns;
  68. public CRNBlock(RecordStream rs) {
  69. _countRecord = (CRNCountRecord) rs.getNext();
  70. int nCRNs = _countRecord.getNumberOfCRNs();
  71. CRNRecord[] crns = new CRNRecord[nCRNs];
  72. for (int i = 0; i < crns.length; i++) {
  73. crns[i] = (CRNRecord) rs.getNext();
  74. }
  75. _crns = crns;
  76. }
  77. public CRNRecord[] getCrns() {
  78. return _crns.clone();
  79. }
  80. }
  81. private static final class ExternalBookBlock {
  82. private final SupBookRecord _externalBookRecord;
  83. private final ExternalNameRecord[] _externalNameRecords;
  84. private final CRNBlock[] _crnBlocks;
  85. public ExternalBookBlock(RecordStream rs) {
  86. _externalBookRecord = (SupBookRecord) rs.getNext();
  87. List<Object> temp = new ArrayList<Object>();
  88. while(rs.peekNextClass() == ExternalNameRecord.class) {
  89. temp.add(rs.getNext());
  90. }
  91. _externalNameRecords = new ExternalNameRecord[temp.size()];
  92. temp.toArray(_externalNameRecords);
  93. temp.clear();
  94. while(rs.peekNextClass() == CRNCountRecord.class) {
  95. temp.add(new CRNBlock(rs));
  96. }
  97. _crnBlocks = new CRNBlock[temp.size()];
  98. temp.toArray(_crnBlocks);
  99. }
  100. public ExternalBookBlock(int numberOfSheets) {
  101. _externalBookRecord = SupBookRecord.createInternalReferences((short)numberOfSheets);
  102. _externalNameRecords = new ExternalNameRecord[0];
  103. _crnBlocks = new CRNBlock[0];
  104. }
  105. public SupBookRecord getExternalBookRecord() {
  106. return _externalBookRecord;
  107. }
  108. public String getNameText(int definedNameIndex) {
  109. return _externalNameRecords[definedNameIndex].getText();
  110. }
  111. public int getNameIx(int definedNameIndex) {
  112. return _externalNameRecords[definedNameIndex].getIx();
  113. }
  114. /**
  115. * Performs case-insensitive search
  116. * @return -1 if not found
  117. */
  118. public int getIndexOfName(String name) {
  119. for (int i = 0; i < _externalNameRecords.length; i++) {
  120. if(_externalNameRecords[i].getText().equalsIgnoreCase(name)) {
  121. return i;
  122. }
  123. }
  124. return -1;
  125. }
  126. }
  127. private final ExternalBookBlock[] _externalBookBlocks;
  128. private final ExternSheetRecord _externSheetRecord;
  129. private final List<NameRecord> _definedNames;
  130. private final int _recordCount;
  131. private final WorkbookRecordList _workbookRecordList; // TODO - would be nice to remove this
  132. public LinkTable(List inputList, int startIndex, WorkbookRecordList workbookRecordList, Map<String, NameCommentRecord> commentRecords) {
  133. _workbookRecordList = workbookRecordList;
  134. RecordStream rs = new RecordStream(inputList, startIndex);
  135. List<ExternalBookBlock> temp = new ArrayList<ExternalBookBlock>();
  136. while(rs.peekNextClass() == SupBookRecord.class) {
  137. temp.add(new ExternalBookBlock(rs));
  138. }
  139. _externalBookBlocks = new ExternalBookBlock[temp.size()];
  140. temp.toArray(_externalBookBlocks);
  141. temp.clear();
  142. if (_externalBookBlocks.length > 0) {
  143. // If any ExternalBookBlock present, there is always 1 of ExternSheetRecord
  144. if (rs.peekNextClass() != ExternSheetRecord.class) {
  145. // not quite - if written by google docs
  146. _externSheetRecord = null;
  147. } else {
  148. _externSheetRecord = readExtSheetRecord(rs);
  149. }
  150. } else {
  151. _externSheetRecord = null;
  152. }
  153. _definedNames = new ArrayList<NameRecord>();
  154. // collect zero or more DEFINEDNAMEs id=0x18,
  155. // with their comments if present
  156. while(true) {
  157. Class nextClass = rs.peekNextClass();
  158. if (nextClass == NameRecord.class) {
  159. NameRecord nr = (NameRecord)rs.getNext();
  160. _definedNames.add(nr);
  161. }
  162. else if (nextClass == NameCommentRecord.class) {
  163. NameCommentRecord ncr = (NameCommentRecord)rs.getNext();
  164. commentRecords.put(ncr.getNameText(), ncr);
  165. }
  166. else {
  167. break;
  168. }
  169. }
  170. _recordCount = rs.getCountRead();
  171. _workbookRecordList.getRecords().addAll(inputList.subList(startIndex, startIndex + _recordCount));
  172. }
  173. private static ExternSheetRecord readExtSheetRecord(RecordStream rs) {
  174. List<ExternSheetRecord> temp = new ArrayList<ExternSheetRecord>(2);
  175. while(rs.peekNextClass() == ExternSheetRecord.class) {
  176. temp.add((ExternSheetRecord) rs.getNext());
  177. }
  178. int nItems = temp.size();
  179. if (nItems < 1) {
  180. throw new RuntimeException("Expected an EXTERNSHEET record but got ("
  181. + rs.peekNextClass().getName() + ")");
  182. }
  183. if (nItems == 1) {
  184. // this is the normal case. There should be just one ExternSheetRecord
  185. return temp.get(0);
  186. }
  187. // Some apps generate multiple ExternSheetRecords (see bug 45698).
  188. // It seems like the best thing to do might be to combine these into one
  189. ExternSheetRecord[] esrs = new ExternSheetRecord[nItems];
  190. temp.toArray(esrs);
  191. return ExternSheetRecord.combine(esrs);
  192. }
  193. public LinkTable(int numberOfSheets, WorkbookRecordList workbookRecordList) {
  194. _workbookRecordList = workbookRecordList;
  195. _definedNames = new ArrayList<NameRecord>();
  196. _externalBookBlocks = new ExternalBookBlock[] {
  197. new ExternalBookBlock(numberOfSheets),
  198. };
  199. _externSheetRecord = new ExternSheetRecord();
  200. _recordCount = 2;
  201. // tell _workbookRecordList about the 2 new records
  202. SupBookRecord supbook = _externalBookBlocks[0].getExternalBookRecord();
  203. int idx = findFirstRecordLocBySid(CountryRecord.sid);
  204. if(idx < 0) {
  205. throw new RuntimeException("CountryRecord not found");
  206. }
  207. _workbookRecordList.add(idx+1, _externSheetRecord);
  208. _workbookRecordList.add(idx+1, supbook);
  209. }
  210. /**
  211. * TODO - would not be required if calling code used RecordStream or similar
  212. */
  213. public int getRecordCount() {
  214. return _recordCount;
  215. }
  216. /**
  217. * @param builtInCode a BUILTIN_~ constant from {@link NameRecord}
  218. * @param sheetNumber 1-based sheet number
  219. */
  220. public NameRecord getSpecificBuiltinRecord(byte builtInCode, int sheetNumber) {
  221. Iterator iterator = _definedNames.iterator();
  222. while (iterator.hasNext()) {
  223. NameRecord record = ( NameRecord ) iterator.next();
  224. //print areas are one based
  225. if (record.getBuiltInName() == builtInCode && record.getSheetNumber() == sheetNumber) {
  226. return record;
  227. }
  228. }
  229. return null;
  230. }
  231. public void removeBuiltinRecord(byte name, int sheetIndex) {
  232. //the name array is smaller so searching through it should be faster than
  233. //using the findFirstXXXX methods
  234. NameRecord record = getSpecificBuiltinRecord(name, sheetIndex);
  235. if (record != null) {
  236. _definedNames.remove(record);
  237. }
  238. // TODO - do we need "Workbook.records.remove(...);" similar to that in Workbook.removeName(int namenum) {}?
  239. }
  240. public int getNumNames() {
  241. return _definedNames.size();
  242. }
  243. public NameRecord getNameRecord(int index) {
  244. return _definedNames.get(index);
  245. }
  246. public void addName(NameRecord name) {
  247. _definedNames.add(name);
  248. // TODO - this is messy
  249. // Not the most efficient way but the other way was causing too many bugs
  250. int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
  251. if (idx == -1) idx = findFirstRecordLocBySid(SupBookRecord.sid);
  252. if (idx == -1) idx = findFirstRecordLocBySid(CountryRecord.sid);
  253. int countNames = _definedNames.size();
  254. _workbookRecordList.add(idx+countNames, name);
  255. }
  256. public void removeName(int namenum) {
  257. _definedNames.remove(namenum);
  258. }
  259. /**
  260. * checks if the given name is already included in the linkTable
  261. */
  262. public boolean nameAlreadyExists(NameRecord name)
  263. {
  264. // Check to ensure no other names have the same case-insensitive name
  265. for ( int i = getNumNames()-1; i >=0; i-- ) {
  266. NameRecord rec = getNameRecord(i);
  267. if (rec != name) {
  268. if (isDuplicatedNames(name, rec))
  269. return true;
  270. }
  271. }
  272. return false;
  273. }
  274. private static boolean isDuplicatedNames(NameRecord firstName, NameRecord lastName) {
  275. return lastName.getNameText().equalsIgnoreCase(firstName.getNameText())
  276. && isSameSheetNames(firstName, lastName);
  277. }
  278. private static boolean isSameSheetNames(NameRecord firstName, NameRecord lastName) {
  279. return lastName.getSheetNumber() == firstName.getSheetNumber();
  280. }
  281. public String[] getExternalBookAndSheetName(int extRefIndex) {
  282. int ebIx = _externSheetRecord.getExtbookIndexFromRefIndex(extRefIndex);
  283. SupBookRecord ebr = _externalBookBlocks[ebIx].getExternalBookRecord();
  284. if (!ebr.isExternalReferences()) {
  285. return null;
  286. }
  287. // Sheet name only applies if not a global reference
  288. int shIx = _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
  289. String usSheetName = null;
  290. if(shIx >= 0) {
  291. usSheetName = ebr.getSheetNames()[shIx];
  292. }
  293. return new String[] {
  294. ebr.getURL(),
  295. usSheetName,
  296. };
  297. }
  298. public int getExternalSheetIndex(String workbookName, String sheetName) {
  299. SupBookRecord ebrTarget = null;
  300. int externalBookIndex = -1;
  301. for (int i=0; i<_externalBookBlocks.length; i++) {
  302. SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
  303. if (!ebr.isExternalReferences()) {
  304. continue;
  305. }
  306. if (workbookName.equals(ebr.getURL())) { // not sure if 'equals()' works when url has a directory
  307. ebrTarget = ebr;
  308. externalBookIndex = i;
  309. break;
  310. }
  311. }
  312. if (ebrTarget == null) {
  313. throw new RuntimeException("No external workbook with name '" + workbookName + "'");
  314. }
  315. int sheetIndex = getSheetIndex(ebrTarget.getSheetNames(), sheetName);
  316. int result = _externSheetRecord.getRefIxForSheet(externalBookIndex, sheetIndex);
  317. if (result < 0) {
  318. throw new RuntimeException("ExternSheetRecord does not contain combination ("
  319. + externalBookIndex + ", " + sheetIndex + ")");
  320. }
  321. return result;
  322. }
  323. private static int getSheetIndex(String[] sheetNames, String sheetName) {
  324. for (int i = 0; i < sheetNames.length; i++) {
  325. if (sheetNames[i].equals(sheetName)) {
  326. return i;
  327. }
  328. }
  329. throw new RuntimeException("External workbook does not contain sheet '" + sheetName + "'");
  330. }
  331. /**
  332. * @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
  333. * @return -1 if the reference is to an external book
  334. */
  335. public int getIndexToInternalSheet(int extRefIndex) {
  336. return _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
  337. }
  338. public int getSheetIndexFromExternSheetIndex(int extRefIndex) {
  339. if (extRefIndex >= _externSheetRecord.getNumOfRefs()) {
  340. return -1;
  341. }
  342. return _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
  343. }
  344. public int checkExternSheet(int sheetIndex) {
  345. int thisWbIndex = -1; // this is probably always zero
  346. for (int i=0; i<_externalBookBlocks.length; i++) {
  347. SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
  348. if (ebr.isInternalReferences()) {
  349. thisWbIndex = i;
  350. break;
  351. }
  352. }
  353. if (thisWbIndex < 0) {
  354. throw new RuntimeException("Could not find 'internal references' EXTERNALBOOK");
  355. }
  356. //Trying to find reference to this sheet
  357. int i = _externSheetRecord.getRefIxForSheet(thisWbIndex, sheetIndex);
  358. if (i>=0) {
  359. return i;
  360. }
  361. //We haven't found reference to this sheet
  362. return _externSheetRecord.addRef(thisWbIndex, sheetIndex, sheetIndex);
  363. }
  364. /**
  365. * copied from Workbook
  366. */
  367. private int findFirstRecordLocBySid(short sid) {
  368. int index = 0;
  369. for (Iterator iterator = _workbookRecordList.iterator(); iterator.hasNext(); ) {
  370. Record record = ( Record ) iterator.next();
  371. if (record.getSid() == sid) {
  372. return index;
  373. }
  374. index ++;
  375. }
  376. return -1;
  377. }
  378. public String resolveNameXText(int refIndex, int definedNameIndex) {
  379. int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
  380. return _externalBookBlocks[extBookIndex].getNameText(definedNameIndex);
  381. }
  382. public int resolveNameXIx(int refIndex, int definedNameIndex) {
  383. int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
  384. return _externalBookBlocks[extBookIndex].getNameIx(definedNameIndex);
  385. }
  386. public NameXPtg getNameXPtg(String name) {
  387. // first find any external book block that contains the name:
  388. for (int i = 0; i < _externalBookBlocks.length; i++) {
  389. int definedNameIndex = _externalBookBlocks[i].getIndexOfName(name);
  390. if (definedNameIndex < 0) {
  391. continue;
  392. }
  393. // found it.
  394. int sheetRefIndex = findRefIndexFromExtBookIndex(i);
  395. if (sheetRefIndex >= 0) {
  396. return new NameXPtg(sheetRefIndex, definedNameIndex);
  397. }
  398. }
  399. return null;
  400. }
  401. private int findRefIndexFromExtBookIndex(int extBookIndex) {
  402. return _externSheetRecord.findRefIndexFromExtBookIndex(extBookIndex);
  403. }
  404. }