-
Notifications
You must be signed in to change notification settings - Fork 145
/
ExcelRelation.scala
198 lines (174 loc) · 6.67 KB
/
ExcelRelation.scala
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
/*
* Copyright 2022 Martin Mauch (@nightscape)
*
* 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 com.crealytics.spark.excel
import java.sql.Timestamp
import java.text.SimpleDateFormat
import org.apache.poi.ss.usermodel.{Cell, CellType, DataFormatter, DateUtil, Row => _}
import org.apache.spark.rdd.RDD
import org.apache.spark.sql._
import org.apache.spark.sql.sources._
import org.apache.spark.sql.types._
import scala.util.Try
case class ExcelRelation(
dataLocator: DataLocator,
header: Boolean,
treatEmptyValuesAsNulls: Boolean,
usePlainNumberFormat: Boolean,
inferSheetSchema: Boolean,
setErrorCellsToFallbackValues: Boolean,
addColorColumns: Boolean = true,
userSchema: Option[StructType] = None,
timestampFormat: Option[String] = None,
excerptSize: Int = 10,
workbookReader: WorkbookReader
)(@transient val sqlContext: SQLContext)
extends BaseRelation
with TableScan
with PrunedScan {
type SheetRow = Seq[Cell]
lazy val excerpt: List[SheetRow] = workbookReader.withWorkbook(dataLocator.readFrom(_).take(excerptSize).toList)
lazy val headerColumnForName = headerColumns.map(c => c.name -> c).toMap
override val schema: StructType = inferSchema
val dataFormatter = new DataFormatter()
override def buildScan(): RDD[Row] = buildScan(schema.map(_.name).toArray)
private val timestampParser: String => Timestamp =
timestampFormat
.map { fmt =>
val parser = new SimpleDateFormat(fmt)
(stringValue: String) => new Timestamp(parser.parse(stringValue).getTime)
}
.getOrElse((stringValue: String) => Timestamp.valueOf(stringValue))
val columnNameRegex = s"(?s)^(.*?)(_color)?$$".r.unanchored
private def columnExtractor(column: String): SheetRow => Any = {
val columnNameRegex(columnName, isColor) = column
val headerColumn = headerColumnForName(columnName)
val cellExtractor: PartialFunction[Seq[Cell], Any] = if (isColor == null) {
headerColumn
} else new ColorDataColumn(headerColumn.name, headerColumn.columnIndex)
cellExtractor.applyOrElse(_, (_: Seq[Cell]) => null)
}
override def buildScan(requiredColumns: Array[String]): RDD[Row] = {
val lookups = requiredColumns.map(columnExtractor).toSeq
workbookReader.withWorkbook { workbook =>
val allDataIterator = dataLocator.readFrom(workbook)
val iter = if (header) allDataIterator.drop(1) else allDataIterator
val rows: Iterator[Seq[Any]] = iter
.flatMap(row =>
Try {
val values = lookups.map(l => l(row))
Some(values)
}.recover { case _ =>
// e.printStackTrace()
None
}.get
)
val result = rows.toVector
parallelize(result.map(Row.fromSeq))
}
}
private def getSparkType(cell: Cell): DataType = {
cell.getCellType match {
case CellType.FORMULA =>
cell.getCachedFormulaResultType match {
case CellType.STRING => StringType
case CellType.NUMERIC => DoubleType
case _ => NullType
}
case CellType.STRING if cell.getStringCellValue == "" => NullType
case CellType.STRING => StringType
case CellType.BOOLEAN => BooleanType
case CellType.NUMERIC => if (DateUtil.isCellDateFormatted(cell)) TimestampType else DoubleType
case CellType.BLANK => NullType
case CellType.ERROR => NullType
case CellType._NONE => NullType
}
}
private def parallelize[T : scala.reflect.ClassTag](seq: Seq[T]): RDD[T] = sqlContext.sparkContext.parallelize(seq)
/** Generates a header from the given row which is null-safe and duplicate-safe.
*/
lazy val headerColumns: Seq[HeaderDataColumn] = {
val firstRow = excerpt.head
val nonHeaderRows = if (header) excerpt.tail else excerpt
val fields = userSchema.getOrElse {
val dataTypes = if (this.inferSheetSchema) {
val headerIndices = firstRow.map(_.getColumnIndex)
val cellTypes: Seq[Seq[DataType]] = nonHeaderRows
.map { r =>
headerIndices.map(i => r.find(_.getColumnIndex == i).map(getSparkType).getOrElse(DataTypes.NullType))
}
InferSchema(parallelize(cellTypes))
} else {
// By default fields are assumed to be StringType
excerpt.map(_.size).reduceOption(math.max) match {
case None => Array()
case Some(maxCellsPerRow) => {
(0 until maxCellsPerRow).map(_ => StringType: DataType).toArray
}
}
}
def colName(cell: Cell) = cell.getStringCellValue
val colNames = if (header) {
val headerNames = firstRow.map(colName)
val duplicates = {
val nonNullHeaderNames = headerNames.filter(_ != null)
nonNullHeaderNames.groupBy(identity).filter(_._2.size > 1).keySet
}
firstRow.zipWithIndex.map { case (cell, index) =>
val value = colName(cell)
if (value == null || value.isEmpty) {
// When there are empty strings or the, put the index as the suffix.
s"_c$index"
} else if (duplicates.contains(value)) {
// When there are duplicates, put the index as the suffix.
s"$value$index"
} else {
value
}
}
} else {
firstRow.zipWithIndex.map { case (_, index) =>
// Uses default column names, "_c#" where # is its position of fields
// when header option is disabled.
s"_c$index"
}
}
colNames.zip(dataTypes).map { case (colName, dataType) =>
StructField(name = colName, dataType = dataType, nullable = true)
}
}
firstRow.zip(fields).map { case (cell, field) =>
new HeaderDataColumn(
field,
cell.getColumnIndex,
treatEmptyValuesAsNulls,
usePlainNumberFormat,
timestampParser,
setErrorCellsToFallbackValues
)
}
}
private def inferSchema: StructType =
this.userSchema.getOrElse {
val baseSchema = StructType(headerColumns.map(_.field))
if (addColorColumns) {
headerColumns.foldLeft(baseSchema) { (schema, header) =>
schema.add(s"${header.name}_color", StringType, nullable = true)
}
} else {
baseSchema
}
}
}