1.首先pom.xml引入依赖
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.10</version>
</dependency>
2.要输出的实体T字段加上注解
@CsvBindByName(column = "标题名")
3.实现方法,dataList要输出的数据,finalPath输出路径包括文件名如: xxx/xxx/xxx.csv
public static void writeCSV(List<T> dataList, String finalPath) { try { Writer writer = new FileWriter(finalPath); writer.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF })); StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withEscapechar(‘\\‘).build(); beanToCsv.write(dataList); writer.close(); } catch (IOException e) { log.error("IOException:" + e.toString()); } catch (CsvDataTypeMismatchException e) { log.error("CsvDataTypeMismatchException:" + e.toString()); } catch (CsvRequiredFieldEmptyException e) { log.error("CsvRequiredFieldEmptyException:" + e.toString()); }}
原文地址:https://www.cnblogs.com/me168/p/10207143.html
时间: 2024-11-06 01:37:50