以Java导出为CSV / Excel [英] Exporting to CSV/Excel in Java
问题描述
我想通过Java导出数据到CSV文件,我有一些代码,但它似乎没有输出CSV文件。有人能告诉我什么问题吗?我想要做的不是将文件保存在某个地方,我希望它直接导出给用户。
I'm trying to export data into a CSV file through Java and I've got some code to do it but it doesn't seem to be outputting the CSV file. Could someone tell me what's wrong? What I would like to do is rather than saving the file somewhere, I would like it to be directly exported to the user.
编辑:为了防止不清楚,我不希望文件被保存在任何地方,但希望它被自动输出到用户,即他们单击导出并获得运行/保存results.csv窗口,他们打开文件。目前文件正在保存,所以我知道方法似乎工作,只是在我想要的相反的方式。
Just in case it's not clear, I don't want the file to be saved anywhere but would like it to be outputted automatically to the user i.e. they click export and get the "Run/Save results.csv" window and they open the file. Currently the file is getting saved so I know that the method seems to work, just in the opposite way that I want it to.
public static void writeToCSV(List<Map> objectList) {
String CSV_SEPARATOR = ",";
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("results.csv"), "UTF-8"));
for (Map objectDetails : objectList) {
StringBuffer oneLine = new StringBuffer();
Iterator it = objectDetails.values().iterator();
while (it.hasNext()) {
Object value = it.next();
if(value !=null){
oneLine.append(value.toString());
}
if (it.hasNext()) {
oneLine.append(CSV_SEPARATOR);
}
}
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
推荐答案
我建议使用opencsv 。它也逃避和引用你。
I would recommend using a framework like opencsv for that. It also does escaping and quoting for you.
这篇关于以Java导出为CSV / Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!