-
Notifications
You must be signed in to change notification settings - Fork 19
/
CSVGenerator.kt
28 lines (22 loc) · 1016 Bytes
/
CSVGenerator.kt
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
package klite.csv
import java.io.OutputStream
import java.sql.ResultSet
const val bomUTF8 = "\uFEFF"
private val needsQuotes = "[\\s\"';,]".toRegex()
open class CSVGenerator(val out: OutputStream, val separator: String = ",", bom: String = bomUTF8) {
init { out.write(bom.toByteArray()) }
fun row(vararg values: Any?) = this.apply {
out.write(values.joinToString(separator, postfix = "\n", transform = ::transform).toByteArray())
}
protected open fun transform(o: Any?): String = when(o) {
null -> ""
is Number -> if (separator == ";") o.toString().replace(".", ",") else o.toString()
is String -> if (o.contains(needsQuotes)) "\"${o.replace("\"", "\"\"")}\"" else o
else -> transform(o.toString())
}
private fun sqlHeader(rs: ResultSet) = row(*(1..rs.metaData.columnCount).map { rs.metaData.getColumnName(it) }.toTypedArray())
fun sqlDump(rs: ResultSet) {
if (rs.isFirst) sqlHeader(rs)
row(*(1..rs.metaData.columnCount).map { rs.getObject(it) }.toTypedArray())
}
}