springmvc使用easypoi导出导入Excel表(2):导入Excel表
在pom.xml引入easypoi的依赖包:
cn.afterturn
easypoi-base
3.0.3
cn.afterturn
easypoi-web
3.0.3
cn.afterturn
easypoi-annotation
3.0.3
前端页面:
【导出】
controller层:
/**
* 导出车位信息
* @param response
* @param page
*/
@RequestMapping("/exceportExcel")
public void exceportExcel(HttpServletResponse response,Pagepage) {
if(page==null) {
page=new Page();
}
try {
Listlist=customSpaceService.resultSet(page);
Workbook workbook=ExcelExportUtil.exportExcel(new ExportParams("车位信息","车位租赁信息"), CustomSpaceVo.class,list);
String fileName="cars.xls";
//设置返回响应头
response.setContentType("application/xls;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
service层:
// 获取租赁车位列表(分页)
List resultSet(Page page);
serviceImpl:
@Override
public List resultSet(Page page) {
return customSpaceMapper.resultSet(page);
}
mapper.xml:(如果你只是单表查询的,是要导出整个表的所有数据到Excel表的,那就直接select * from table)
注意点:就是实体类要加注解:在要导出属性上加 @Excel(name="数据库字段的意思或自己随意命名")
model层:
(我要导出的实体类是vo类,vo类就是用来展示给用户需要看到的信息,但并不仅仅是对应一张表的信息,简单说就是查询多张表,把一些重要的字段返回给用户看)
package com.st.eleventh.model;
import java.io.Serializable;
import java.util.Date;
import cn.afterturn.easypoi.excel.annotation.Excel;
public class CustomSpace implements Serializable {
private Integer cs_id;
@Excel(name = "车主")
private String csname;
@Excel(name = "联系电话")
private String phone;
private String carid;
private String park;
@Excel(name = "车位编号")
private String parknum;
private Integer w_id;
@Excel(name = "租用类型")
private Integer renttype;
@Excel(name = "租用时间")
private Integer renttime;
@Excel(name = "开始时间")
private Date starttime;
@Excel(name = "到期时间")
private Date endtime;
private Integer cs_state;
//自己加setter,getter方法
}
package com.st.eleventh.paramVo;
import com.st.eleventh.model.CustomSpace;
import cn.afterturn.easypoi.excel.annotation.Excel;
public class CustomSpaceVo extends CustomSpace {
@Excel(name = "停车场")
private String cg_name;
@Excel(name = "月费")
private Float mz_cost;
@Excel(name = "年费")
private Float yz_cost;
@Excel(name = "工作人员")
private String w_name;
//自己加setter,getter方法
}
好了,导出Excel表就是这么简单。
思路就是:前端发送一个导出请求到controller,controller直接调用service层拿到想要导出的数据,然后直接把该数据放到已经ExcelExportUtil工具类中就好了,因为一切easypoi已经封装好了。唯一注意的就是:你要那个类负责封装要导出的数据,那个类的属性就要加上注解:
@Excel(name = "停车场")
private String cg_name;
效果图: