解决方案:
引入pom文件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
示例代码:
@GetMapping("/N042")
public CommonResult N042(HttpServletResponse response, @RequestParam("qs") Date qs,
@RequestParam("zs") Date zs) {
try (Connection conn = DriverManager.getConnection(url, username, password);
CallableStatement cs = conn.prepareCall("{call PRO_N042(?,?)}");) {
// 设置输入参数的值
cs.setDate(1, qs);
cs.setDate(2, zs);
// 调用存储过程
cs.execute();
ResultSet resultSet = cs.executeQuery();
// 创建CSV文件
File csvFile = new File("N042.csv");
FileWriter writer = new FileWriter(csvFile);
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
// 获取ResultSet的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// 将列名写入CSV文件
for (int i = 1; i <= columnCount; i++) {
csvPrinter.print(metaData.getColumnName(i));
}
csvPrinter.println();
// 将数据写入CSV文件
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
csvPrinter.print(resultSet.getString(i));
}
csvPrinter.println();
}
csvPrinter.close();
writer.close();
// 设置响应头信息
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"" + csvFile.getName() + "\"");
// 将CSV文件写入响应流中
FileInputStream fileInputStream = new FileInputStream(csvFile);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
fileInputStream.close();
// 删除临时CSV文件
csvFile.delete();
} catch (SQLException | IOException e) {
return CommonResult.error(e.getMessage());
}
return CommonResult.success();
}
这段代码使用了CSVPrinter和CSVFormat来创建和写入CSV文件。在将文件写入响应流之后,会删除临时的CSV文件。