今天公司要做导出功能,所以就在SSM下研究了下 发现还挺简单的做了个工具类以便自己以后使用
- 使用的第三方架包是POI,使用的框架是SSM
- 第三方架包下载地址: POI官网
- 如果是使用的maven创建的项目,直接导入依赖就好
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
正式工具代码如下
首先是获得SXSSFWorkbook类的工具类
工具类代码如下
public SXSSFWorkbook export_Flight (List<Flight> flights) {
SXSSFWorkbook workbook = new SXSSFWorkbook(100);//内存中保留100条数据,以免内存溢出
Sheet sheet = workbook.createSheet();//获取改工作区间的第一个sheet
int flightsSize = flights.size();
Row row = sheet.createRow(0);//标题行
Cell title1 = row.createCell(0);
Cell title2 = row.createCell(1);
Cell title3 = row.createCell(2);
Cell title4 = row.createCell(3);
Cell title5 = row.createCell(4);
Cell title6 = row.createCell(5);
title1.setCellValue("航空编号");
title2.setCellValue("航空公司");
title3.setCellValue("起飞日期");
title4.setCellValue("起飞时间");
title5.setCellValue("起飞城市");
title6.setCellValue("到达城市");
for (int i = 0; i < flightsSize; i++) {
Flight flight = flights.get(i);
Row row1 = sheet.createRow(i + 1);
Cell cell1 = row1.createCell(0);
Cell cell2 = row1.createCell(1);
Cell cell3 = row1.createCell(2);
Cell cell4 = row1.createCell(3);
Cell cell5 = row1.createCell(4);
Cell cell6 = row1.createCell(5);
cell1.setCellValue(flight.getFlightid());
cell2.setCellValue(flight.getFlighname());
cell3.setCellValue(flight.getStartDate());
cell4.setCellValue(flight.getArrivalTime());
cell5.setCellValue(flight.getStartCity());
cell6.setCellValue(flight.getArrivalCity());
}
return workbook;
}
我这里是导出一个飞机类的实例,所以命名是这么命名的
然后在控制层写这么一个方法就可以了,代码如下
//导出航班信息
@RequestMapping("/export")
public void export(HttpServletResponse response) {
// 创建新的Excel工作簿
SXSSFWorkbook workbook = null;
UtilPoi export = new UtilPoi();
try {
String excelName = "flight";
OutputStream out = response.getOutputStream();
excelName = new String(excelName.getBytes("GBK"), "ISO8859_1");
response.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xlsx");
//这里flightService.selectFlightPage(1) 只是得到一个flight的集合 不用太关心
workbook = export.export_Flight(flightService.selectFlightPage(1));
workbook.write(out);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
然后我们看效果:
至此导出完成了,因为第一次写导出所以写的比价简单,如果大家想要更详细的介绍这里推荐一篇博客感觉写的听详细的,有导入和导出
比较详细的导入发出博客推荐