您的位置:首页 > 数据库

数据库中数据如何导出生成Excel?

2017-11-27 16:26 441 查看

本文目的:

  将数据库中的数据导出并生成Excel。

如果想要让Excel中的数据导入数据库可以参考我的另外一篇: Excel怎么导入到数据库?

准备工作:

导包:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>


主要使用到该包下的这两个类:其中HSSFWorkbook是Excel中的xls版本,XSSFWorkbook是Excel中的xlsx版本。本文使用的是XSSFWorkbook这个类

下面代码是将数据库中的数据导出生成Excel表格。

详细代码

实现层:

List<CinemaReport> cinemaReportList = cinemaReportRepository.findAll();
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("CinemaReport"); //创建一张表
Row titleRow = sheet.createRow(0);//创建第一行,起始为0
titleRow.createCell(0).setCellValue("序号");//第一列
titleRow.createCell(1).setCellValue("省份");
titleRow.createCell(2).setCellValue("影院名称");
titleRow.createCell(3).setCellValue("天数");
int cell = 1;
for(CinemaReport cinema : cinemaReportList) {
Row row  = sheet.createRow(cell);//从第二行开始保存数据
row.createCell(0).setCellValue(cell);
row.createCell(1).setCellValue(cinema.getProvince());
row.createCell(2).setCellValue(cinema.getCinemaName());
row.createCell(3).setCellValue(cinema.getTotalDays());
cell++;
}
return wb;
}


控制层:

@RequestMapping(value = "/export/cinemaReport",method = RequestMethod.GET)
public void importCinemaReport(HttpServletResponse response) {
XSSFWorkbook wb = fileImportServiceImpl.exportCinemaReport();
String fileName = "电影报表.xlsx";
OutputStream out = null;
try {
fileName = URLEncoder.encode(fileName,"UTF-8");
//设置ContentType请求信息格式
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}


测试:

然后在浏览器地址栏输入:localhost:8080/file/export/cinemaReport如果成功就会自动提醒你是否保存该文件了

ELEVEN:

个人转载无须申请版权许可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: