Skip to content

Commit cdf5f60

Browse files
committed
Create ExcelReader.groovy
1 parent be5071e commit cdf5f60

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

ExcelReader.groovy

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
@Grab('org.apache.poi:poi:3.9')
2+
@Grab('org.apache.poi:poi-ooxml:3.9')
3+
4+
import org.apache.poi.ss.usermodel.WorkbookFactory
5+
import org.apache.poi.ss.usermodel.Cell
6+
import org.apache.poi.ss.usermodel.Row
7+
import org.apache.poi.ss.usermodel.DataFormatter
8+
9+
/**
10+
* Groovy parser for Microsoft Excel spreadsheets.
11+
* Based on @author Goran Ehrsson's post: http://www.technipelago.se/content/technipelago/blog/44
12+
* Updated to handle xlsx document types, and modified to just return the string formatted value of each cell (ignore types)
13+
*/
14+
class ExcelReader {
15+
16+
def workbook
17+
def labels
18+
def row
19+
20+
ExcelReader(String fileName) {
21+
DataFormatter dataFormatter = new DataFormatter()
22+
23+
Row.metaClass.getAt = { int idx ->
24+
Cell cell = delegate.getCell(idx)
25+
26+
if (!cell) {
27+
return null
28+
}
29+
30+
return dataFormatter.formatCellValue(cell)
31+
}
32+
33+
workbook = WorkbookFactory.create(new File(fileName))
34+
}
35+
36+
def getSheet(idx) {
37+
def sheet
38+
if (!idx) idx = 0
39+
if (idx instanceof Number) {
40+
sheet = workbook.getSheetAt(idx)
41+
} else if (idx ==~ /^\d+$/) {
42+
sheet = workbook.getSheetAt(Integer.valueOf(idx))
43+
} else {
44+
sheet = workbook.getSheet(idx)
45+
}
46+
return sheet
47+
}
48+
49+
def cell(idx) {
50+
if (labels && (idx instanceof String)) {
51+
idx = labels.indexOf(idx.toLowerCase())
52+
}
53+
return row[idx]
54+
}
55+
56+
def propertyMissing(String name) {
57+
cell(name)
58+
}
59+
60+
def eachLine(Map params = [:], Closure closure) {
61+
def offset = params.offset ?: 0
62+
def max = params.max ?: 9999999
63+
def sheet = getSheet(params.sheet)
64+
def rowIterator = sheet.rowIterator()
65+
def linesRead = 0
66+
67+
if (params.labels) {
68+
labels = rowIterator.next().collect { it.toString().toLowerCase() }
69+
}
70+
offset.times { rowIterator.next() }
71+
72+
closure.setDelegate(this)
73+
74+
while (rowIterator.hasNext() && linesRead++ < max) {
75+
row = rowIterator.next()
76+
closure.call(row)
77+
}
78+
}
79+
}

0 commit comments

Comments
 (0)