基于springMVC+POI 实现最简单的excel-xlsx导出下载功能

基于springMVC+POI 实现最简单的excel-xlsx导出下载功能

@Controller
@RequestMapping("/meteo/test")
public class TestController {

    @Autowired
    private WaterPointService waterPointService;

    @RequestMapping(value = "/downLoadExcel", method = RequestMethod.GET)
    public String downLoadExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
        List meteoMonitors = waterPointService.getMeteoMonitorList();
        if (meteoMonitors != null && meteoMonitors.size() > 0) {
            String fileName = "test.xlsx";
            response.setHeader("Content-disposition", "attachment;filename="
                    + new String(fileName.getBytes("gb2312"), "ISO8859-1"));//设置文件头编码格式
            response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");//设置类型
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头

            XSSFWorkbook workbook = new XSSFWorkbook();

            XSSFSheet sheet = workbook.createSheet();
            CellStyle cellStyle = workbook.createCellStyle();

            cellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

            int rowNum = 0;
            for (MeteoMonitor meteoMonitor:meteoMonitors) {
                Row row = sheet.createRow(rowNum);

                Cell cell = row.createCell(0);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(meteoMonitor.getTime());

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(meteoMonitor.getBaseStation());

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(meteoMonitor.getPrecipitation());

                Cell cell3 = row.createCell(3);
                cell3.setCellValue(meteoMonitor.getPressure());

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(meteoMonitor.getWind());

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(meteoMonitor.getTemperature());

                Cell cell6 = row.createCell(6);
                cell6.setCellValue(meteoMonitor.getHumidity());

                rowNum++;
            }

            workbook.write(response.getOutputStream());

            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
        return null;
    }
}
里面获取的实体类列表请换成你们实际需要的,其它源码我就不给出了。
然后在浏览器输入localhost:8080/meteo/test/downLoadExcel,js里面可以用window.location跳转

结果:
基于springMVC+POI 实现最简单的excel-xlsx导出下载功能_第1张图片
基于springMVC+POI 实现最简单的excel-xlsx导出下载功能_第2张图片

你可能感兴趣的:(poi-excel)