1.添加依赖 <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv --> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.9.0</version> </dependency>
2.控制层代码 dataList类型List<String[]> CSVWriter writer = null; try { response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(vName, "UTF-8") + ".csv"); OutputStream out = response.getOutputStream(); //防止中文乱码问题 out.write(new byte []{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}); writer = new CSVWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8.name())); writer.writeAll(dataList); } catch (IOException e) { e.printStackTrace(); } finally { if (null != writer) { try { writer.flush(); writer.close(); } catch (IOException e) { System.out.println("关闭文件输出流出错:" + e); } } }