-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathExcelLoader.java
More file actions
1401 lines (1225 loc) · 49.7 KB
/
ExcelLoader.java
File metadata and controls
1401 lines (1225 loc) · 49.7 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2009-2019 LabKey Corporation
*
* Licensed 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.labkey.api.reader;
import org.apache.commons.collections4.iterators.ArrayIterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.apache.poi.UnsupportedFileFormatException;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.formula.eval.NotImplementedException;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import org.junit.Test;
import org.labkey.api.data.Container;
import org.labkey.api.exp.PropertyType;
import org.labkey.api.iterator.CloseableIterator;
import org.labkey.api.util.DateUtil;
import org.labkey.api.util.FileType;
import org.labkey.api.util.FileUtil;
import org.labkey.api.util.JunitUtil;
import org.labkey.api.util.StringUtilsLabKey;
import org.labkey.api.util.XmlBeansUtil;
import org.labkey.vfs.FileLike;
import org.labkey.vfs.FileSystemLike;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Data loader for Excel files -- can infer columns and return rows of data
*/
public class ExcelLoader extends DataLoader
{
public static FileType FILE_TYPE = new FileType(Arrays.asList(".xlsx", ".xls"), ".xlsx",
Arrays.asList("application/" + ExcelFactory.SUB_TYPE_BIFF8, "application/" + ExcelFactory.SUB_TYPE_XSSF, "application/" + ExcelFactory.SUB_TYPE_BIFF5));
private Boolean _isStartDate1904 = null;
static {
FILE_TYPE.setExtensionsMutuallyExclusive(false);
}
private static final Pattern EXCEL_TIME_PATTERN = Pattern.compile("^[\\[\\]hHmMsS :]+0*[ampAMP/]*(;@)?$");
public static class Factory extends AbstractDataLoaderFactory
{
@NotNull @Override
public DataLoader createLoader(File file, boolean hasColumnHeaders, Container mvIndicatorContainer) throws IOException
{
return new ExcelLoader(file, hasColumnHeaders, mvIndicatorContainer);
}
@NotNull @Override
public DataLoader createLoader(InputStream is, boolean hasColumnHeaders, Container mvIndicatorContainer) throws IOException
{
return new ExcelLoader(is, hasColumnHeaders, mvIndicatorContainer);
}
@NotNull @Override
public FileType getFileType() { return FILE_TYPE; }
}
public static boolean isExcel(final FileLike dataFile)
{
try
{
try (InputStream inputStream = new BufferedInputStream(dataFile.openInputStream()))
{
return ExcelLoader.FILE_TYPE.isType(dataFile.toNioPathForRead(), null, FileUtil.readHeader(inputStream, 8 * 1024));
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public static boolean isExcel(final File dataFile)
{
try
{
return ExcelLoader.FILE_TYPE.isType(dataFile, null, FileUtil.readHeader(dataFile, 8 * 1024));
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
private Workbook _workbook = null;
private ExcelFactory.WorkbookMetadata _workbookMetadata = null;
private String sheetName;
private Integer sheetIndex;
// For Excel sheets that don't have column headers as the first line, the column types can all be seen as Strings.
// In that case, the cell contents in readFields() might not get the expected values for numeric columns.
private boolean useColumnFormats = true;
// keep track if we created a temp file
private boolean shouldDeleteFile = false;
private ExcelLoader() {}
public static ExcelLoader create(Path path, boolean hasColumnHeaders, Container mvIndicatorContainer) throws IOException
{
if (path.getFileSystem() == FileSystems.getDefault())
return new ExcelLoader(path.toFile(), hasColumnHeaders, mvIndicatorContainer);
return new ExcelLoader(Files.newInputStream(path), hasColumnHeaders, mvIndicatorContainer);
}
public ExcelLoader(File file) throws IOException
{
this(file, false);
}
public ExcelLoader(File file, boolean hasColumnHeaders) throws IOException
{
this(file, hasColumnHeaders, null);
}
public ExcelLoader(InputStream is, boolean hasColumnHeaders, Container mvIndicatorContainer) throws IOException
{
super(mvIndicatorContainer);
setHasColumnHeaders(hasColumnHeaders);
setScrollable(false);
// NOTE: If we don't create a temp file, ExcelFactory will.
// Create here so we can call getMetadata() and then stream sheets in loadSheetFromXLSX().
_file = FileUtil.createTempFile("excel", "tmp", true);
shouldDeleteFile = true;
try
{
FileUtil.copyData(is, _file);
}
catch (IOException x)
{
FileUtil.deleteTempFile(_file);
_file = null;
throw x;
}
}
public ExcelLoader(File file, boolean hasColumnHeaders, Container mvIndicatorContainer) throws IOException
{
super(mvIndicatorContainer);
setHasColumnHeaders(hasColumnHeaders);
setSource(file);
setScrollable(true);
}
public ExcelLoader(File file, ExcelFactory.WorkbookMetadata md, boolean hasColumnHeaders, Container mvIndicatorContainer)
{
super(mvIndicatorContainer);
setHasColumnHeaders(hasColumnHeaders);
_file = file;
_workbookMetadata = md;
_workbook = md.getWorkbook();
setScrollable(true);
}
// Issue 42244: From the Excel documentation:
// "Excel supports two date systems. Each date system uses a unique starting date from which all other workbook
// dates are calculated. Excel 2008 for Mac and earlier Excel for Mac versions calculate dates based on the 1904
// date system. Excel for Mac 2011 uses the 1900 date system, which guarantees date compatibility with Excel for
// Windows. All versions of Excel for Windows calculate dates based on the 1900 date system."
//
// When using the SAXParser, we need to know whether this current workbook/sheet is 1904-base or 1900-based.
// We are not using getDateCellValue in that case, which knows how to determine which date system is in use, so
// we hack up our own way to detect this. This is derived from this posting:
// https://alandix.com/code2/apache-poi-detect-1904-date-option/
void computeIsStartDate1904()
{
try
{
Boolean isStart1904 = getWorkbookMetadata(null).isStart1904();
if (null == isStart1904)
{
Sheet sheet = getSheet();
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
Cell cell = row.createCell(0);
cell.setCellValue(0.0);
Date date = cell.getDateCellValue();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
long year1900 = cal.get(Calendar.YEAR)-1900;
isStart1904 = year1900 > 0;
sheet.removeRow(row);
}
_isStartDate1904 = isStart1904;
}
catch (IOException x)
{
_isStartDate1904 = false;
}
}
private boolean getIsStartDate1904()
{
if (_isStartDate1904 == null)
computeIsStartDate1904();
return _isStartDate1904;
}
public ExcelFactory.WorkbookMetadata getWorkbookMetadata(@Nullable OPCPackage opc) throws IOException
{
try
{
if (null == _workbookMetadata && null == _workbook && (null != _file || null != opc))
{
// if we already have an OPCPackage we can reuse it
if (null != opc)
_workbookMetadata = ExcelFactory.getMetadata(opc);
else
_workbookMetadata = ExcelFactory.getMetadata(_file);
if (null != _workbookMetadata.getWorkbook())
_workbook = _workbookMetadata.getWorkbook();
}
if (null == _workbookMetadata)
_workbookMetadata = ExcelFactory.getMetadata(getWorkbook());
return _workbookMetadata;
}
catch (InvalidFormatException e)
{
throw new ExcelFormatException(e);
}
}
private Workbook getWorkbook() throws IOException
{
if (null == _workbook)
{
try
{
_workbook = ExcelFactory.create(_file);
}
catch (InvalidFormatException e)
{
throw new ExcelFormatException(e);
}
}
return _workbook;
}
public List<String> getSheetNames() throws IOException
{
return getWorkbookMetadata(null).getSheetNames();
}
public void setSheetName(String sheetName)
{
this.sheetName = sheetName;
this.sheetIndex = null;
}
public void setSheetIndex(int index)
{
this.sheetName = null;
this.sheetIndex = index;
}
public void setUseColumnFormats(boolean useColumnFormats)
{
this.useColumnFormats = useColumnFormats;
}
public Sheet getSheet() throws IOException
{
try
{
Workbook workbook = getWorkbook();
if (sheetName != null)
return workbook.getSheet(sheetName);
else
return workbook.getSheetAt(Objects.requireNonNullElse(sheetIndex, 0));
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new IOException("Invalid Excel file");
}
}
public boolean sheetMatches(int index, String name)
{
if (sheetName != null)
return Strings.CS.equals(sheetName, name);
else if (sheetIndex != null)
return sheetIndex == index;
else
return index == 0;
}
@Override
public String[][] getFirstNLines(int n) throws IOException
{
if (null != _file)
{
try
{
return getFirstNLinesXLSX(n);
}
catch (InvalidFormatException x)
{
/* fall through */
}
}
try
{
return getFirstNLinesXLS(n);
}
catch (NotImplementedException e)
{
throw new IOException("Unable to open Excel file: " + (e.getMessage() == null ? "No specific error information available" : e.getMessage()), e);
}
}
@NotNull
private String[][] getFirstNLinesXLSX(int n) throws IOException, InvalidFormatException
{
int row = -1;
List<Object[]> grid = new ArrayList<>();
try (AsyncXlsxIterator iter = new AsyncXlsxIterator())
{
while (row < n && iter.hasNext())
{
grid.add(iter.next().toArray());
}
}
List<String[]> cells = new ArrayList<>();
for (int i = 0; cells.size() < n && i<grid.size() ; i++)
{
Object[] currentRow = grid.get(i);
List<String> rowData = new ArrayList<>(currentRow.length);
boolean foundData = false;
for (Object v : currentRow)
{
String data = StringUtilsLabKey.fullTrimToEmpty(v);
if (!StringUtils.isEmpty(data))
foundData = true;
rowData.add(data);
}
if (foundData)
cells.add(rowData.toArray(new String[0]));
}
return cells.toArray(new String[0][]);
}
public String[][] getFirstNLinesXLS(int n) throws IOException
{
Sheet sheet = getSheet();
List<String[]> cells = new ArrayList<>();
for (Row currentRow : sheet)
{
List<String> rowData = new ArrayList<>();
// Excel can report back more rows than exist. If we find no data at all, we should not add a row.
boolean foundData = false;
if (currentRow.getPhysicalNumberOfCells() != 0)
{
for (int column = 0; column < currentRow.getLastCellNum(); column++)
{
Cell cell = currentRow.getCell(column);
if (cell != null)
{
Object value = PropertyType.getFromExcelCell(cell);
String data;
// Use ISO format instead of Date.toString(), Issue 21232
if (value instanceof Date)
data = DateUtil.formatIsoDateShortTime((Date)value);
else
data = String.valueOf(value);
data = StringUtilsLabKey.fullTrimToEmpty(data);
if (!data.isEmpty())
foundData = true;
rowData.add(data);
}
else
rowData.add("");
}
if (foundData)
cells.add(rowData.toArray(new String[0]));
}
if (--n == 0)
break;
}
return cells.toArray(new String[cells.size()][]);
}
@Override
protected DataLoader.DataLoaderIterator _iterator(boolean includeRowHash)
{
try
{
var md = getWorkbookMetadata(null);
if (md.isSpreadSheetML())
return new XlsxIterator();
else
return new ExcelIterator();
}
catch (InvalidFormatException | IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public void close()
{
if (_workbook != null)
{
try
{
_workbook.close();
}
catch (IOException ignore)
{
}
}
if (shouldDeleteFile && null != _file)
FileUtil.deleteTempFile(_file);
}
private static class StopLoadingRows extends RuntimeException
{}
private class AsyncXlsxIterator implements CloseableIterator<List<Object>>
{
public static final String THREAD_NAME_PREFIX = "Async XLSX parser: ";
private final BlockingQueue<List<Object>> _queue;
private final Thread _asyncThread;
private OPCPackage _xlsxPackage;
private volatile RuntimeException _exception;
private volatile boolean _complete = false;
private List<Object> _nextRow;
public AsyncXlsxIterator() throws IOException, InvalidFormatException
{
_queue = new ArrayBlockingQueue<>(4);
_asyncThread = startAsyncParsing();
}
private Thread startAsyncParsing() throws IOException, InvalidFormatException
{
try
{
_xlsxPackage = OPCPackage.open(_file.getPath(), PackageAccess.READ);
ExcelFactory.WorkbookMetadata md = getWorkbookMetadata(_xlsxPackage);
String[] strings = md.getSharedStrings();
XSSFReader xssfReader = new XSSFReader(_xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
Runnable runnable = () -> {
int sheetIndex = -1;
while (iter.hasNext())
{
InputStream stream = iter.next();
sheetIndex++;
// DO NOT CALL getSheet() for XLSX since it loads all rows into memory!
if (sheetMatches(sheetIndex, iter.getSheetName()))
{
InputSource sheetSource = new InputSource(stream);
SAXParserFactory saxFactory = XmlBeansUtil.SAX_PARSER_FACTORY;
try
{
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader sheetParser = saxParser.getXMLReader();
SheetHandler handler = new SheetHandler(styles, strings, _queue, getIsStartDate1904());
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
}
catch (StopLoadingRows slr)
{
/* no problem */
}
catch (Exception x)
{
_exception = new RuntimeException(x);
}
break;
}
}
_complete = true;
synchronized (_queue)
{
_queue.notify();
}
};
Thread parsingThread = new Thread(runnable, THREAD_NAME_PREFIX + _file.getName());
parsingThread.start();
return parsingThread;
}
catch (POIXMLException x)
{
throw new InvalidFormatException("File is not a valid xlsx file: " + _file.getName() + (x.getMessage() == null ? "" : x.getMessage()));
}
catch (InvalidOperationException | UnsupportedFileFormatException x)
{
throw new InvalidFormatException("File is not an xlsx file: " + _file.getPath());
}
catch (InvalidFormatException | IOException x)
{
throw x;
}
catch (Exception x)
{
throw new IOException(x);
}
}
@Override
public void close()
{
if (_xlsxPackage != null)
{
_xlsxPackage.revert();
}
_asyncThread.interrupt();
try
{
_asyncThread.join(TimeUnit.SECONDS.toMillis(5));
}
catch (InterruptedException ignored) {}
if (_asyncThread.isAlive())
{
throw new IllegalStateException("Async thread still alive");
}
}
@Override
public boolean hasNext()
{
if (_nextRow != null)
{
return true;
}
do
{
try
{
_nextRow = _queue.poll(1, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ignored)
{
}
}
while (!_complete && _nextRow == null && _exception == null);
if (_exception != null)
{
throw _exception;
}
return _nextRow != null;
}
@Override
public List<Object> next()
{
if (_nextRow == null)
{
throw new NoSuchElementException();
}
var result = _nextRow;
_nextRow = null;
return result;
}
}
private class XlsxIterator extends AbstractDataLoaderIterator
{
private final AsyncXlsxIterator _asyncIter;
XlsxIterator() throws IOException, InvalidFormatException
{
super(_skipLines == -1 ? 1 : _skipLines);
_asyncIter = new AsyncXlsxIterator();
int skipLines = _skipLines == -1 ? 1 : _skipLines;
for (int i = 0; i < skipLines && _asyncIter.hasNext(); i++)
{
_asyncIter.next();
}
}
@Override
public void close() throws IOException
{
super.close();
_asyncIter.close();
}
@Override
protected Object[] readFields() throws IOException
{
if (!_asyncIter.hasNext())
{
return null;
}
ColumnDescriptor[] allColumns = getColumns();
List<Object> row = _asyncIter.next();
Object[] fields = new Object[_activeColumns.length];
for (int columnIndex = 0, fieldIndex = 0; columnIndex < row.size() && columnIndex < allColumns.length; columnIndex++)
{
// UNDONE: it seems to me that DataLoader should handle .load==false
ColumnDescriptor cd = allColumns[columnIndex];
if (!cd.load)
continue;
Object value = row.get(columnIndex);
if (value instanceof String s)
value = StringUtilsLabKey.fullTrimToEmpty(s);
fields[fieldIndex++] = value;
}
return fields;
}
}
private class ExcelIterator extends AbstractDataLoaderIterator
{
private final Sheet sheet;
private final int numRows;
ExcelIterator() throws IOException
{
super(_skipLines == -1 ? 1 : _skipLines);
sheet = getSheet();
numRows = sheet.getLastRowNum() + 1;
}
@Override
protected Object[] readFields() throws IOException
{
if (lineNum() >= numRows)
return null;
ColumnDescriptor[] allColumns = getColumns();
Iterator<ColumnDescriptor> columnIter = new ArrayIterator<>(allColumns);
Object[] fields = new Object[_activeColumns.length];
Row row = sheet.getRow(lineNum());
if (row != null)
{
int numCols = row.getLastCellNum();
for (int columnIndex = 0, fieldIndex = 0; columnIndex < allColumns.length; columnIndex++)
{
boolean loadThisColumn = ((columnIter.hasNext() && columnIter.next().load));
if (loadThisColumn)
{
ColumnDescriptor column = _activeColumns[fieldIndex];
Object contents;
if (columnIndex < numCols) // We can get asked for more data than we contain, as extra columns can exist
{
Cell cell = row.getCell(columnIndex);
if (cell == null)
{
contents = "";
}
else if (useColumnFormats && column.clazz.equals(String.class))
{
contents = StringUtilsLabKey.fullTrimToEmpty(ExcelFactory.getCellStringValue(cell));
}
else
{
contents = PropertyType.getFromExcelCell(cell);
if (contents instanceof String s)
contents = StringUtilsLabKey.fullTrimToEmpty(s);
}
}
else
{
contents = "";
}
fields[fieldIndex++] = contents;
}
}
}
return fields;
}
}
/**
* The main point of this routine is to return a full-fidelity string version of the passed in value.
* However, when copying a numeric value in a spreadsheet to a string column in the database, it would
* be nice to use a decent default format.
*
* If the caller REALLY cares about the format, it should probably set useFormats==true
* @param value object to convert
* @return string representation
*/
String _toString(Object value, boolean isNumberFormat)
{
if (null == value)
return "";
String toStringValue = value.toString();
if (!isNumberFormat || !StringUtils.contains(toStringValue,'.'))
return toStringValue;
try
{
// try to convert to double and reformat without trailing ...00000001 or ...99999999.
double d = Double.parseDouble(toStringValue);
double pos = Math.abs(d);
if (pos == 0.0)
return "0";
if (Double.isFinite(d) && pos <= 9_007_199_254_740_992L && Math.log10(pos)>=-6)
{
String formatValue = df.format(d);
if (d == Double.parseDouble(formatValue))
return formatValue;
}
}
catch (NumberFormatException x)
{
/* pass */
}
return toStringValue;
}
DecimalFormat df = new DecimalFormat("###0.#####################");
public static class ExcelLoaderTestCase extends Assert
{
String[] line0 = new String[] { "date", "scan", "time", "mz", "accurateMZ", "mass", "intensity", "charge", "chargeStates", "kl", "background", "median", "peaks", "scan\nFirst", "scanLast", "scanCount", "totalIntensity", "description" };
String[] line1Xlsx = new String[] { "2006-01-02 00:00:00", "96", "1543.3400999999999", "858.32460000000003", "false", "1714.6346000000001", "2029.6295", "2", "1", "0.19630893999999999", "26.471083", "12.982442000000001", "4", "92", "100", "9", "20248.761999999999", "description" };
String[] line1Xls = new String[] { "2006-01-02 00:00", "96.0", "1543.3401", "858.3246", "false", "1714.6346", "2029.6295", "2.0", "1.0", "0.19630894", "26.471083", "12.982442", "4.0", "92.0", "100.0", "9.0", "20248.762", "description" };
String[] line7Xlsx = new String[] { "2006-01-02 00:00:00", "249", "1724.5541000000001", "773.42174999999997", "false", "1544.829", "5.9057474000000001", "2", "1", "0.51059710000000003", "0.67020833000000002", "1.4744527000000001", "2", "246", "250", "5", "29.369174999999998" };
String[] line7Xls = new String[] { "2006-01-02 00:00", "249.0", "1724.5541", "773.42175", "false", "1544.829", "5.9057474", "2.0", "1.0", "0.5105971", "0.67020833", "1.4744527", "2.0", "246.0", "250.0", "5.0", "29.369175" };
@Test
public void detect() throws Exception
{
File excelSamplesRoot = JunitUtil.getSampleData(null, "dataLoading/excel");
assertTrue(isExcel(FileUtil.appendName(excelSamplesRoot, "ExcelLoaderTest.xls")));
assertTrue(isExcel(FileUtil.appendName(excelSamplesRoot, "SimpleExcelFile.xls")));
assertTrue(isExcel(FileUtil.appendName(excelSamplesRoot, "SimpleExcelFile.xlsx")));
assertTrue(isExcel(FileUtil.appendName(excelSamplesRoot, "fruits.xls")));
assertTrue(isExcel(FileUtil.appendName(excelSamplesRoot, "DatesWithSeconds.xlsx")));
// Issue 22153: detect xls file without extension
assertTrue(isExcel(JunitUtil.getSampleData(null, "Nab/seaman/MS010407")));
// NOTE: DataLoaderService only available when running junit tests with running server
DataLoaderService svc = DataLoaderService.get();
if (svc != null)
{
DataLoaderFactory factory = svc.findFactory(FileSystemLike.wrapFile(JunitUtil.getSampleData(null, "Nab/seaman/MS010407")), null);
assertTrue(factory instanceof ExcelLoader.Factory);
}
assertFalse(isExcel(FileUtil.appendName(excelSamplesRoot, "notreallyexcel.xls")));
assertFalse(isExcel(FileUtil.appendName(excelSamplesRoot, "notreallyexcel.xlsx")));
assertFalse(isExcel(FileUtil.appendName(excelSamplesRoot, "fruits.tsv")));
}
@Test
public void testColumnTypes() throws Exception
{
try (ExcelLoader loader = getExcelLoader("ExcelLoaderTest.xls"))
{
checkColumnMetadata(loader);
checkData(loader);
}
}
@Test
public void testColumnTypesXlsx() throws Exception
{
try (ExcelLoader loader = getExcelLoader("ExcelLoaderTest.xlsx"))
{
checkColumnMetadata(loader);
checkData(loader);
}
ensureAsyncThreads(0);
}
@Test
public void testBogusXlsx() throws Exception
{
try
{
try (ExcelLoader loader = getExcelLoader("notreallyexcel.xlsx"))
{
loader.iterator();
}
fail();
}
catch (RuntimeException ignored)
{
}
ensureAsyncThreads(0);
}
@Test
public void testExtraHasNext() throws Exception
{
for (String file : Arrays.asList("ExcelLoaderTest.xlsx", "ExcelLoaderTest.xls"))
{
try (ExcelLoader loader = getExcelLoader(file))
{
try (var iter = loader.iterator())
{
int rowCount = 0;
while (iter.hasNext())
{
//noinspection ConstantValue
assertTrue(iter.hasNext());
iter.next();
rowCount++;
}
assertEquals("Wrong row count for " + file, 7, rowCount);
}
}
ensureAsyncThreads(0);
}
}
@Test
public void testPartialXlsxParsing() throws Exception
{
try (ExcelLoader loader = getExcelLoader("ExcelLoaderTest.xlsx"))
{
try (var iter = loader.iterator())
{
assertTrue(iter.hasNext());
ensureAsyncThreads(1);
Map<String, Object> row = iter.next();
checkFirstRow(row);
}
}
ensureAsyncThreads(0);
}
@Test
public void testFirstNLinesXlsx() throws Exception
{
try (ExcelLoader loader = getExcelLoader("ExcelLoaderTest.xlsx"))
{
verifyLines(loader, line1Xlsx, line7Xlsx);
}
ensureAsyncThreads(0);
}
private void ensureAsyncThreads(int expected)
{
int actual = 0;
for (Map.Entry<Thread, StackTraceElement[]> threadEntry : Thread.getAllStackTraces().entrySet())
{
Thread t = threadEntry.getKey();
if (t.isAlive() && t.getName().startsWith(AsyncXlsxIterator.THREAD_NAME_PREFIX))
{
actual++;
}
}
assertEquals("Unexpected number of async parsing threads", expected, actual);
}
@Test
public void testFirstNLinesXls() throws Exception
{
try (ExcelLoader loader = getExcelLoader("ExcelLoaderTest.xls"))
{
verifyLines(loader, line1Xls, line7Xls);
}
}
private void verifyLines(ExcelLoader loader, String[] expectedLine1, String[] expectedLine7) throws IOException
{
String[][] lines = loader.getFirstNLines(5);
assertEquals(5, lines.length);
assertArrayEquals(line0, lines[0]);
assertArrayEquals(expectedLine1, lines[1]);
lines = loader.getFirstNLines(20);
assertEquals(8, lines.length);
assertArrayEquals(line0, lines[0]);
assertArrayEquals(expectedLine1, lines[1]);
assertArrayEquals(expectedLine7, lines[7]);
}
private ExcelLoader getExcelLoader(String filename) throws IOException
{
File excelSamplesRoot = JunitUtil.getSampleData(null, "dataLoading/excel");
if (!excelSamplesRoot.canRead())
throw new IOException("Could not read excel samples in: " + excelSamplesRoot);
File excelFile = FileUtil.appendName(excelSamplesRoot, filename);
return new ExcelLoader(excelFile, true);
}
private static void checkColumnMetadata(ExcelLoader loader) throws IOException
{
ColumnDescriptor[] columns = loader.getColumns();
assertEquals(18, columns.length);
assertEquals(Date.class, columns[0].clazz);
assertEquals(Integer.class, columns[1].clazz);
assertEquals(Double.class, columns[2].clazz);
assertEquals(Boolean.class, columns[4].clazz);
assertEquals(String.class, columns[17].clazz);
}
private static void checkData(ExcelLoader loader)