1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
|
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.formula.EvaluationName;
import org.apache.poi.ss.formula.EvaluationWorkbook;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaParsingWorkbook;
import org.apache.poi.ss.formula.FormulaRenderingWorkbook;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.SheetIdentifier;
import org.apache.poi.ss.formula.functions.FreeRefFunction;
import org.apache.poi.ss.formula.ptg.Area3DPxg;
import org.apache.poi.ss.formula.ptg.NamePtg;
import org.apache.poi.ss.formula.ptg.NameXPtg;
import org.apache.poi.ss.formula.ptg.NameXPxg;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.ptg.Ref3DPxg;
import org.apache.poi.ss.formula.udf.IndexedUDFFinder;
import org.apache.poi.ss.formula.udf.UDFFinder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.NotImplemented;
import org.apache.poi.util.Internal;
import org.apache.poi.xssf.model.ExternalLinksTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
/**
* Internal POI use only - parent of XSSF and SXSSF evaluation workbooks
*/
@Internal
public abstract class BaseXSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook {
protected final XSSFWorkbook _uBook;
// lazily populated. This should only be accessed through getTableCache
// keys are lower-case to make this a quasi-case-insensitive map
private Map<String, XSSFTable> _tableCache;
protected BaseXSSFEvaluationWorkbook(XSSFWorkbook book) {
_uBook = book;
}
/* (non-JavaDoc), inherit JavaDoc from EvaluationWorkbook
* @since POI 3.15 beta 3
*/
@Override
public void clearAllCachedResultValues() {
_tableCache = null;
}
private int convertFromExternalSheetIndex(int externSheetIndex) {
return externSheetIndex;
}
/**
* XSSF doesn't use external sheet indexes, so when asked treat
* it just as a local index
*/
@Override
public int convertFromExternSheetIndex(int externSheetIndex) {
return externSheetIndex;
}
/**
* @return the external sheet index of the sheet with the given internal
* index. Used by some of the more obscure formula and named range things.
* Fairly easy on XSSF (we think...) since the internal and external
* indices are the same
*/
private int convertToExternalSheetIndex(int sheetIndex) {
return sheetIndex;
}
@Override
public int getExternalSheetIndex(String sheetName) {
int sheetIndex = _uBook.getSheetIndex(sheetName);
return convertToExternalSheetIndex(sheetIndex);
}
private int resolveBookIndex(String bookName) {
// Strip the [] wrapper, if still present
if (bookName.startsWith("[") && bookName.endsWith("]")) {
bookName = bookName.substring(1, bookName.length()-2);
}
// Is it already in numeric form?
try {
return Integer.parseInt(bookName);
} catch (NumberFormatException e) {}
// Look up an External Link Table for this name
List<ExternalLinksTable> tables = _uBook.getExternalLinksTable();
int index = findExternalLinkIndex(bookName, tables);
if (index != -1) return index;
// Is it an absolute file reference?
if (bookName.startsWith("'file:///") && bookName.endsWith("'")) {
String relBookName = bookName.substring(bookName.lastIndexOf('/')+1);
relBookName = relBookName.substring(0, relBookName.length()-1); // Trailing '
// Try with this name
index = findExternalLinkIndex(relBookName, tables);
if (index != -1) return index;
// If we get here, it's got no associated proper links yet
// So, add the missing reference and return
// Note - this is really rather nasty...
ExternalLinksTable fakeLinkTable = new FakeExternalLinksTable(relBookName);
tables.add(fakeLinkTable);
return tables.size(); // 1 based results, 0 = current workbook
}
// Not properly referenced
throw new IllegalStateException("Book not linked for filename " + bookName);
}
/* This is case-sensitive. Is that correct? */
private int findExternalLinkIndex(String bookName, List<ExternalLinksTable> tables) {
int i = 0;
for (ExternalLinksTable table : tables) {
if (table.getLinkedFileName().equals(bookName)) {
return i+1; // 1 based results, 0 = current workbook
}
i++;
}
return -1;
}
private static class FakeExternalLinksTable extends ExternalLinksTable {
private final String fileName;
private FakeExternalLinksTable(String fileName) {
this.fileName = fileName;
}
@Override
public String getLinkedFileName() {
return fileName;
}
}
/**
* Return EvaluationName wrapper around the matching XSSFName (named range)
* @param name case-aware but case-insensitive named range in workbook
* @param sheetIndex index of sheet if named range scope is limited to one sheet
* if named range scope is global to the workbook, sheetIndex is -1.
* @return If name is a named range in the workbook, returns
* EvaluationName corresponding to that named range
* Returns null if there is no named range with the same name and scope in the workbook
*/
@Override
public EvaluationName getName(String name, int sheetIndex) {
for (int i = 0; i < _uBook.getNumberOfNames(); i++) {
XSSFName nm = _uBook.getNameAt(i);
String nameText = nm.getNameName();
int nameSheetindex = nm.getSheetIndex();
if (name.equalsIgnoreCase(nameText) &&
(nameSheetindex == -1 || nameSheetindex == sheetIndex)) {
return new Name(nm, i, this);
}
}
return sheetIndex == -1 ? null : getName(name, -1);
}
@Override
public String getSheetName(int sheetIndex) {
return _uBook.getSheetName(sheetIndex);
}
@Override
public ExternalName getExternalName(int externSheetIndex, int externNameIndex) {
throw new IllegalStateException("HSSF-style external references are not supported for XSSF");
}
@Override
public ExternalName getExternalName(String nameName, String sheetName, int externalWorkbookNumber) {
if (externalWorkbookNumber > 0) {
// External reference - reference is 1 based, link table is 0 based
int linkNumber = externalWorkbookNumber - 1;
ExternalLinksTable linkTable = _uBook.getExternalLinksTable().get(linkNumber);
for (org.apache.poi.ss.usermodel.Name name : linkTable.getDefinedNames()) {
if (name.getNameName().equals(nameName)) {
// HSSF returns one sheet higher than normal, and various bits
// of the code assume that. So, make us match that behaviour!
int nameSheetIndex = name.getSheetIndex() + 1;
// TODO Return a more specialised form of this, see bug #56752
// Should include the cached values, for in case that book isn't available
// Should support XSSF stuff lookups
return new ExternalName(nameName, -1, nameSheetIndex);
}
}
throw new IllegalArgumentException("Name '"+nameName+"' not found in " +
"reference to " + linkTable.getLinkedFileName());
} else {
// Internal reference
int nameIdx = _uBook.getNameIndex(nameName);
return new ExternalName(nameName, nameIdx, 0); // TODO Is this right?
}
}
/**
* Return an external name (named range, function, user-defined function) Pxg
*/
@Override
public NameXPxg getNameXPtg(String name, SheetIdentifier sheet) {
// First, try to find it as a User Defined Function
IndexedUDFFinder udfFinder = (IndexedUDFFinder)getUDFFinder();
FreeRefFunction func = udfFinder.findFunction(name);
if (func != null) {
return new NameXPxg(null, name);
}
// Otherwise, try it as a named range
if (sheet == null) {
if (!_uBook.getNames(name).isEmpty()) {
return new NameXPxg(null, name);
}
return null;
}
if (sheet.getSheetIdentifier() == null) {
// Workbook + Named Range only
int bookIndex = resolveBookIndex(sheet.getBookName());
return new NameXPxg(bookIndex, null, name);
}
// Use the sheetname and process
String sheetName = sheet.getSheetIdentifier().getName();
if (sheet.getBookName() != null) {
int bookIndex = resolveBookIndex(sheet.getBookName());
return new NameXPxg(bookIndex, sheetName, name);
} else {
return new NameXPxg(sheetName, name);
}
}
@Override
public Ptg get3DReferencePtg(CellReference cell, SheetIdentifier sheet) {
if (sheet.getBookName() != null) {
int bookIndex = resolveBookIndex(sheet.getBookName());
return new Ref3DPxg(bookIndex, sheet, cell);
} else {
return new Ref3DPxg(sheet, cell);
}
}
@Override
public Ptg get3DReferencePtg(AreaReference area, SheetIdentifier sheet) {
if (sheet.getBookName() != null) {
int bookIndex = resolveBookIndex(sheet.getBookName());
return new Area3DPxg(bookIndex, sheet, area);
} else {
return new Area3DPxg(sheet, area);
}
}
@Override
public String resolveNameXText(NameXPtg n) {
int idx = n.getNameIndex();
String name = null;
// First, try to find it as a User Defined Function
IndexedUDFFinder udfFinder = (IndexedUDFFinder)getUDFFinder();
name = udfFinder.getFunctionName(idx);
if (name != null) return name;
// Otherwise, try it as a named range
XSSFName xname = _uBook.getNameAt(idx);
if (xname != null) {
name = xname.getNameName();
}
return name;
}
@Override
public ExternalSheet getExternalSheet(int externSheetIndex) {
throw new IllegalStateException("HSSF-style external references are not supported for XSSF");
}
@Override
public ExternalSheet getExternalSheet(String firstSheetName, String lastSheetName, int externalWorkbookNumber) {
String workbookName;
if (externalWorkbookNumber > 0) {
// External reference - reference is 1 based, link table is 0 based
int linkNumber = externalWorkbookNumber - 1;
ExternalLinksTable linkTable = _uBook.getExternalLinksTable().get(linkNumber);
workbookName = linkTable.getLinkedFileName();
} else {
// Internal reference
workbookName = null;
}
if (lastSheetName == null || firstSheetName.equals(lastSheetName)) {
return new ExternalSheet(workbookName, firstSheetName);
} else {
return new ExternalSheetRange(workbookName, firstSheetName, lastSheetName);
}
}
@Override
@NotImplemented
public int getExternalSheetIndex(String workbookName, String sheetName) {
throw new IllegalStateException("not implemented yet");
}
@Override
public int getSheetIndex(String sheetName) {
return _uBook.getSheetIndex(sheetName);
}
@Override
public String getSheetFirstNameByExternSheet(int externSheetIndex) {
int sheetIndex = convertFromExternalSheetIndex(externSheetIndex);
return _uBook.getSheetName(sheetIndex);
}
@Override
public String getSheetLastNameByExternSheet(int externSheetIndex) {
// XSSF does multi-sheet references differently, so this is the same as the first
return getSheetFirstNameByExternSheet(externSheetIndex);
}
@Override
public String getNameText(NamePtg namePtg) {
return _uBook.getNameAt(namePtg.getIndex()).getNameName();
}
@Override
public EvaluationName getName(NamePtg namePtg) {
int ix = namePtg.getIndex();
return new Name(_uBook.getNameAt(ix), ix, this);
}
@Override
public XSSFName createName() {
return _uBook.createName();
}
/*
* TODO: data tables are stored at the workbook level in XSSF, but are bound to a single sheet.
* The current code structure has them hanging off XSSFSheet, but formulas reference them
* only by name (names are global, and case insensitive).
* This map stores names as lower case for case-insensitive lookups.
*
* FIXME: Caching tables by name here for fast formula lookup means the map is out of date if
* a table is renamed or added/removed to a sheet after the map is created.
*
* Perhaps tables can be managed similar to PivotTable references above?
*/
private Map<String, XSSFTable> getTableCache() {
if ( _tableCache != null ) {
return _tableCache;
}
_tableCache = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER);
for (Sheet sheet : _uBook) {
for (XSSFTable tbl : ((XSSFSheet)sheet).getTables()) {
_tableCache.put(tbl.getName(), tbl);
}
}
return _tableCache;
}
/**
* Returns the data table with the given name (case insensitive).
* Tables are cached for performance (formula evaluation looks them up by name repeatedly).
* After the first table lookup, adding or removing a table from the document structure will cause trouble.
* This is meant to be used on documents whose structure is essentially static at the point formulas are evaluated.
*
* @param name the data table name (case-insensitive)
* @return The Data table in the workbook named {@code name}, or {@code null} if no table is named {@code name}.
* @since 3.15 beta 2
*/
@Override
public XSSFTable getTable(String name) {
if (name == null) return null;
return getTableCache().get(name);
}
@Override
public UDFFinder getUDFFinder(){
return _uBook.getUDFFinder();
}
@Override
public SpreadsheetVersion getSpreadsheetVersion(){
return SpreadsheetVersion.EXCEL2007;
}
private static final class Name implements EvaluationName {
private final XSSFName _nameRecord;
private final int _index;
private final FormulaParsingWorkbook _fpBook;
public Name(XSSFName name, int index, FormulaParsingWorkbook fpBook) {
_nameRecord = name;
_index = index;
_fpBook = fpBook;
}
@Override
public Ptg[] getNameDefinition() {
return FormulaParser.parse(_nameRecord.getRefersToFormula(), _fpBook, FormulaType.NAMEDRANGE, _nameRecord.getSheetIndex());
}
@Override
public String getNameText() {
return _nameRecord.getNameName();
}
@Override
public boolean hasFormula() {
// TODO - no idea if this is right
CTDefinedName ctn = _nameRecord.getCTName();
String strVal = ctn.getStringValue();
return !ctn.getFunction() && strVal != null && !strVal.isEmpty();
}
@Override
public boolean isFunctionName() {
return _nameRecord.isFunctionName();
}
@Override
public boolean isRange() {
return hasFormula(); // TODO - is this right?
}
@Override
public NamePtg createPtg() {
return new NamePtg(_index);
}
}
}
|