1.整理需要导出的实体类
public void exportCSV(Trip driftTripDetail) throws Exception {
List<List<String>> contents = new ArrayList<>();
List<String> result = new ArrayList<>();
result.add(people.getName());
result.add(String.valueOf(people.getAge()));
contents.add(result);
CsvExportUtil.doExport("people",contents,"姓名","年龄");
}
2.导出csv工具类
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
public class CsvExportUtil {
public static void doExport(String tablename, List<List<String>> contents,String... header) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream("D:\\data\\data_export\\"+tablename+".csv");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "GBK");
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(header);
CSVPrinter csvPrinter = new CSVPrinter(outputStreamWriter, csvFormat);
for (List<String> content : contents) {
csvPrinter.printRecord(content);
}
csvPrinter.flush();
csvPrinter.close();
}
}