Created
September 19, 2012 17:28
-
-
Save aeg/3750951 to your computer and use it in GitHub Desktop.
リスト要素をCSV出力する。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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