通过easypoi导出Excel

需求说明

之前说了用freemarker来导出word,这次来简单的说一下通过easypoi导出Excel。

具体实现

1.目标数据

如图:
在这里插入图片描述

2.引入easypoi依赖包

可以直接从maven仓库下载

		<!-- 引入easypoi -->
		<dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.0.3</version>
        </dependency>

3.给需要导出的字段添加注解

这边只处理了3个字段

@Setter
@Getter
public class User {
	private Integer id;				// 用户id
	@Excel(name = "账号", width=20)
	private String userName;		// 用户账号
	@Excel(name = "暱称", width=20)
	private String nickName;		// 用户暱称
	@Excel(name = "密码", width=20)
	private String password;		// 用户密码
	private String salt;			// 加密密码的盐
	private Integer status;			// 用户状态,0:创建未认证(比如没有激活,没有输入验证码等) --等待验证的用户,1:正常状态,2:用户被锁定 								
	private String age;				// 用户年龄
	private String sex;				// 用户性别
	private String mail;         	// 用户邮箱
	private String photo;			// 用户头像
}

注意:
@Excel中有不少属性,这边只用了到了name和width,默认情况下导出的宽度太挤了,所以调大了些。
如果想要了解更多的属性,可以参考EasyPoi教程:http://easypoi.mydoc.io/#text_197838

4.代码调用

/**  
     * Description: 通过easypoi导出Excel
     *
     * @param request
     * @param response  
     *
     */  
    @RequestMapping(value = "/exportUserByExcel", method=RequestMethod.GET)
	public void exportUserByExcel(HttpServletRequest request, HttpServletResponse response) {
    	List<User> users = userService.findByList();
    	Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), User.class, users);
		try {
			String name = "用户数据.xls";
			String fileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
	                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                        workbook.write(response.getOutputStream());
			response.flushBuffer();
			logger.info("用户数据导出成功");
		} catch (IOException e) {
			logger.error("用户数据导出失败,原因:", e);
		} finally {
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }

5.调用结果

如图:
在这里插入图片描述

6.说明

虽然只是简单的尝试的用了一下,不过感觉还真是好用!

参考资料:
http://easypoi.mydoc.io/#text_197838

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章