使用jxls生成excel并导出

首先需要pom文件

    
      org.apache.poi
      poi
      3.15-beta2
    
    
      org.apache.poi
      poi-ooxml
      3.15-beta2
    
    
      net.sf.jxls
      jxls-core
      1.0-RC-1
    

实体类

    public class User implements Serializable{
        private static final long serialVersionUID = -7588727575833992276L;
        private String username;
        private String password;
        private Date birthday;
        
        //~~
    }

模板文件

使用jxls生成excel并导出_第1张图片
文件存放地址
使用jxls生成excel并导出_第2张图片
模板文件内容
  • 如果想要日期格式的内容正常显示需要修改下图位置的单元格格式


    使用jxls生成excel并导出_第3张图片
    修改日期的单元格格式
使用jxls生成excel并导出_第4张图片
修改单元格格式

代码部分

    @RequestMapping("/downData.do")
    public void downData(HttpServletResponse response) throws IOException, InvalidFormatException {
        User user1 = new User("zhangsan", "123", new Date());
        User user2 = new User("lisi", "9999", new Date());
        User user3 = new User("wagnwu", "44444", new Date());
        List userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        String fileName = "学生信息";
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setContentType("application/x-download");
        Resource resource = new ClassPathResource("template/a.xlsx");
        InputStream is = resource.getInputStream();
        Workbook workbook = getWorkBook(userList);
        workbook.write(response.getOutputStream());
    }

    private Workbook getWorkBook(List userList) throws IOException, InvalidFormatException {
        Map> beans = new HashMap<>();
        beans.put("userList", userList);
        XLSTransformer transformer = new XLSTransformer();
        Resource resource = new ClassPathResource("template/a.xlsx");
        InputStream is = resource.getInputStream();
        return transformer.transformXLS(is, beans);
    }

你可能感兴趣的:(使用jxls生成excel并导出)