Skip to content

Instantly share code, notes, and snippets.

@aeg
Created September 19, 2012 17:28
Show Gist options
  • Save aeg/3750951 to your computer and use it in GitHub Desktop.
Save aeg/3750951 to your computer and use it in GitHub Desktop.
リスト要素をCSV出力する。
// Case #1
// 各要素が文字列であるListからCSV出力する。
def listA = ['A', 'B"', 'C', 4, 3.14]
println listA.join(',')
// 結果
// A,B",C,4,3.14
// Case #2
// 各要素が文字列であるListからCSV出力する。
// 各要素について、文字列に変換した後、ダブルクォーテーションで囲う。
// ただし、数値として解釈できる場合にはダブルクォーテーションを付けない。
// 文字列の中にダブルクォーテーションが含まれていれば2個重ねてエスケープする。
def escapeString(obj) {
String str = obj.toString()
if (str.isNumber()) {
str
} else {
'"' + str.replaceAll(/"/,'""') + '"'
}
}
println listA.collect{escapeString(it)}.join(',')
// 結果
// "A","B""","C",4,3.14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment