0
如何使用仅一列将Java中的字符串导出为具有此格式的csv文件。将Java中的字符串导出为CSV
这就是我期待:
Column 1
Row 1: string1,string2,string3
Row 2: string4, string5, string6
在此先感谢
如何使用仅一列将Java中的字符串导出为具有此格式的csv文件。将Java中的字符串导出为CSV
这就是我期待:
Column 1
Row 1: string1,string2,string3
Row 2: string4, string5, string6
在此先感谢
在下面的代码,你提供的元素列表。每个元素都包含csv文件的一行信息。 StringBuilder用于为一行创建字符串,然后一次输出到文件。
public void writeCsvFile(List elements, String fileName) throws IOException {
BufferedWriter csvFile = null;
String delim = ",";
try {
csvFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), StandardCharsets.UTF_8));
for (int i = 0; i < objects.size(); i++) {
StringBuilder buf = new StringBuilder();
Elements elem = elements.get(i);
buf.append(elem.info1).append(delim);
buf.append(elem.info2).append(delim);
buf.append(elem.info3);
csvFile.write(buf.toString());
csvFile.newLine();
}
} finally {
try {
if (csvFile != null) {
csvFile.close();
}
} catch (IOException e) {
// empty
}
}
}
您必须“转义”逗号,以便CSV阅读器不会将它们解释为列分隔符。
如果在引号,则逗号应该被忽略,因为定界符换你行值
这会给你3列
Value1,Value2,Value3
这应该给你用整个字符串作为一个单一的1列值
"Value1,Value2,Value3"
你试过了什么?您是否尝试过使用谷歌浏览器访问序列化为CSV的第三方库? – jgitter
它是如何单列的。由于列以逗号分隔,所以我在每行看到三列。 – SacJn
打开outputstream并写入它。 – ergonaut