csv文件 内容转义,如何转义逗号和双引号同时为CSV文件?

I am writing a Java app to export data from Oracle to csv file

Unfortunately the content of data may quite tricky. Still comma is the deliminator, but some data on a row could be like this:

ID FN LN AGE COMMENT

123, John, Smith, 39, I said "Hey, I am 5'10"."

so this is one of the string on the comment column:

I said "Hey, I am 5'10"."

No kidding, I need to show above comment without compromise in excel or open office from a CSV file generated by Java, and of course cannot mess up other regular escaping situation(i.e. regular double quotes, and regular comma within a tuple). I know regular expression is powerful but how can we achieve the goal with such complicated situation?

解决方案

There are several libraries. Here are two examples:

Apache Commons Lang includes a special class to escape or unescape strings (CSV, EcmaScript, HTML, Java, Json, XML): org.apache.commons.lang3.StringEscapeUtils.

Escape to CSV

String escaped = StringEscapeUtils

.escapeCsv("I said \"Hey, I am 5'10\".\""); // I said "Hey, I am 5'10"."

System.out.println(escaped); // "I said ""Hey, I am 5'10""."""

Unescape from CSV

String unescaped = StringEscapeUtils

.unescapeCsv("\"I said \"\"Hey, I am 5'10\"\".\"\"\""); // "I said ""Hey, I am 5'10""."""

System.out.println(unescaped); // I said "Hey, I am 5'10"."

* You can download it from here.

If you use OpenCSV, you will not need to worry about escape or unescape, only for write or read the content.

Writing file:

FileOutputStream fos = new FileOutputStream("awesomefile.csv");

OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");

CSVWriter writer = new CSVWriter(osw);

...

String[] row = {

"123",

"John",

"Smith",

"39",

"I said \"Hey, I am 5'10\".\""

};

writer.writeNext(row);

...

writer.close();

osw.close();

os.close();

Reading file:

FileInputStream fis = new FileInputStream("awesomefile.csv");

InputStreamReader isr = new InputStreamReader(fis, "UTF-8");

CSVReader reader = new CSVReader(isr);

for (String[] row; (row = reader.readNext()) != null;) {

System.out.println(Arrays.toString(row));

}

reader.close();

isr.close();

fis.close();

* You can download it from here.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值