So exportieren Sie Daten in eine CSV-Datei - Java
Die DateiComma-Separated Values (CSV)ist nur eine normale Nur-Text-Datei. Sie speichert Daten spaltenweise und teilt sie durch Trennzeichen (Kommas) auf.
Note
Das Schreiben einer CSV-Datei ist wie das Schreiben einer normalen Textdatei. Achten Sie jedoch auf das Problem der doppelten Anführungszeichen, das in meinen vorherigenCSV parsing
example erwähnt wurde.
In diesem Tutorial zeigen wir Ihnen eine einfacheCVSUtils
-Klasse, mit der Sie Daten oder Objekte einfach in eine CVS-Datei schreiben können.
1. CSV-Schreibbeispiel
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(); } }
Ausgabe
/Users/example/csv/abc.csv
a,b,c,d "aaa","bb,b","cc,c" 'aaa'|'bbb'|'cc,c' aaa,bbb,cc""c
2. Mehr Beispiele
Sehen wir uns ein anderes Beispiel an, es erstellt eine Liste von Objekten und schreibt sie in eine CSV-Datei.
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(); } }
Ausgabe
/Users/example/csv/developer.csv
Name,Salary,Age example,120500,32 zilap,150099,5 ultraman,99999,99
Note
Wenn Sie sich immer noch nicht gut implementieren können, probieren Sie diese CSV-Bibliothek eines Drittanbieters aus -OpenCSV.
Erledigt.