Как экспортировать данные в файл CSV - Java
ФайлComma-Separated Values (CSV) - это просто обычный текстовый файл, в котором данные хранятся по столбцу за столбцом и разделены разделителями (запятыми).
Note
Запись файла CSV аналогична написанию обычного текстового файла, только остерегайтесь проблемы «двойных кавычек», о которой я упоминал в моих предыдущихCSV parsing
example.
В этом руководстве мы покажем вам простой классCVSUtils
для простой записи данных или объектов в файл CVS.
1. Пример написания CSV
1.1 Review the following CVSUtils
class, it supports custom separator, custom enclose quote (default is empty), escaped the double-quotes with another double quote (RFC4180)
CSVUtils.java
package com.example.utils; import java.io.IOException; import java.io.Writer; import java.util.List; public class CSVUtils { private static final char DEFAULT_SEPARATOR = ','; public static void writeLine(Writer w, Listvalues) throws IOException { writeLine(w, values, DEFAULT_SEPARATOR, ' '); } public static void writeLine(Writer w, List values, char separators) throws IOException { writeLine(w, values, separators, ' '); } //https://tools.ietf.org/html/rfc4180 private static String followCVSformat(String value) { String result = value; if (result.contains("\"")) { result = result.replace("\"", "\"\""); } return result; } public static void writeLine(Writer w, List values, char separators, char customQuote) throws IOException { boolean first = true; //default customQuote is empty if (separators == ' ') { separators = DEFAULT_SEPARATOR; } StringBuilder sb = new StringBuilder(); for (String value : values) { if (!first) { sb.append(separators); } if (customQuote == ' ') { sb.append(followCVSformat(value)); } else { sb.append(customQuote).append(followCVSformat(value)).append(customQuote); } first = false; } sb.append("\n"); w.append(sb.toString()); } }
1.2 Example to show the CSVUtils
usage.
CSVUtils.java
package com.example.utils; import java.io.FileWriter; import java.util.Arrays; public class CVSUtilExample { public static void main(String[] args) throws Exception { String csvFile = "/Users/example/csv/abc.csv"; FileWriter writer = new FileWriter(csvFile); CSVUtils.writeLine(writer, Arrays.asList("a", "b", "c", "d")); //custom separator + quote CSVUtils.writeLine(writer, Arrays.asList("aaa", "bb,b", "cc,c"), ',', '"'); //custom separator + quote CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc,c"), '|', '\''); //double-quotes CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc\"c")); writer.flush(); writer.close(); } }
Выход
/Users/example/csv/abc.csv
a,b,c,d "aaa","bb,b","cc,c" 'aaa'|'bbb'|'cc,c' aaa,bbb,cc""c
2. Больше примеров
Давайте рассмотрим другой пример, он создает список объектов и записывает его в файл CSV.
2.1 A Developer class.
Developer.java
package com.example.csv; import java.math.BigDecimal; public class Developer { private String name; private BigDecimal salary; private int age; public Developer(String name, BigDecimal salary, int age) { this.name = name; this.salary = salary; this.age = age; } //... }
2.2 Example.
CVSUtilExample.java
package com.example.utils; import com.example.java8.Developer; import java.io.FileWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CVSUtilExample { public static void main(String[] args) throws Exception { String csvFile = "/Users/example/csv/developer.csv"; FileWriter writer = new FileWriter(csvFile); Listdevelopers = Arrays.asList( new Developer("example", new BigDecimal(120500), 32), new Developer("zilap", new BigDecimal(150099), 5), new Developer("ultraman", new BigDecimal(99999), 99) ); //for header CSVUtils.writeLine(writer, Arrays.asList("Name", "Salary", "Age")); for (Developer d : developers) { List list = new ArrayList<>(); list.add(d.getName()); list.add(d.getSalary().toString()); list.add(String.valueOf(d.getAge())); CSVUtils.writeLine(writer, list); //try custom separator and quote. //CSVUtils.writeLine(writer, list, '|', '\"'); } writer.flush(); writer.close(); } }
Выход
/Users/example/csv/developer.csv
Name,Salary,Age example,120500,32 zilap,150099,5 ultraman,99999,99
Note
Если вам все еще неудобно реализовать себя, попробуйте эту стороннюю библиотеку CSV -OpenCSV.
Готово.