Java Web利用POI导出Excel简单例子

时间:2023-12-16 08:48:32
采用Spring mvc架构: 
Controller层代码如下
  1. @Controller
  2. public class StudentExportController{
  3. @Autowired
  4. private StudentExportService studentExportService;
  5. @RequestMapping(value = "/excel/export")
  6. public void exportExcel(HttpServletRequest request, HttpServletResponse response)
  7. throws Exception {
  8. List<Student> list = new ArrayList<Student>();
  9. list.add(new Student(1000,"zhangsan","20"));
  10. list.add(new Student(1001,"lisi","23"));
  11. list.add(new Student(1002,"wangwu","25"));
  12. HSSFWorkbook wb = studentExportService.export(list);
  13. response.setContentType("application/vnd.ms-excel");
  14. response.setHeader("Content-disposition", "attachment;filename=student.xls");
  15. OutputStream ouputStream = response.getOutputStream();
  16. wb.write(ouputStream);
  17. ouputStream.flush();
  18. ouputStream.close();
  19. }
  20. }

Service层代码如下:

  1. @Service
  2. public class StudentExportService {
  3. String[] excelHeader = { "Sno", "Name", "Age"};
  4. public HSSFWorkbook export(List<Student> list) {
  5. HSSFWorkbook wb = new HSSFWorkbook();
  6. HSSFSheet sheet = wb.createSheet("Student");
  7. HSSFRow row = sheet.createRow((int) 0);
  8. HSSFCellStyle style = wb.createCellStyle();
  9. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  10. for (int i = 0; i < excelHeader.length; i++) {
  11. HSSFCell cell = row.createCell(i);
  12. cell.setCellValue(excelHeader[i]);
  13. cell.setCellStyle(style);
  14. sheet.autoSizeColumn(i);
  15. // sheet.SetColumnWidth(i, 100 * 256);
  16. }
  17. for (int i = 0; i < list.size(); i++) {
  18. row = sheet.createRow(i + 1);
  19. Student student = list.get(i);
  20. row.createCell(0).setCellValue(student.getSno());
  21. row.createCell(1).setCellValue(student.getName());
  22. row.createCell(2).setCellValue(student.getAge());
  23. }
  24. return wb;
  25. }
  26. }

前台的js代码如下:

  1. <script>
  2. function exportExcel(){
  3. location.href="excel/export";
  4. <!--这里不能用ajax请求,ajax请求无法弹出下载保存对话框-->
  5. }
  6. </script>