对于批量数据的操作,在项目中引进Excel的导入和导出功能是个不错的选择。对于Excel表的结构,简单理解可以把它分成三部分(Sheet,Cell,Row),这三部分可以理解为excel表中的页,列,行。因此,我们想要获取到某一个单元的内容,可以通过获取该单元所在的页数、对应所在的行和对应的列数从而定位到该单位,继而便可执行操作从而获取其中的内容。本文在SSM环境下基于Java的POI实现对excel的导入导出功能也是相似的思路。
准备工作:
导入POI对应的Jar包
org.apache.poi
poi-ooxml
3.14-beta1
org.apache.poi
poi-ooxml-schemas
3.14-beta1
org.apache.poi
poi
3.14-beta1
org.apache.httpcomponents
httpclient
4.5.2
创建一个ExcelBean实现对数据的封装
public class ExcelBean implements java.io.Serializable{
private String headTextName; //列头(标题)名
private String propertyName; //对应字段名
private Integer cols; //合并单元格数
private XSSFCellStyle cellStyle;
public ExcelBean(){
}
public ExcelBean(String headTextName, String propertyName){
this.headTextName = headTextName;
this.propertyName = propertyName;
}
public ExcelBean(String headTextName, String propertyName, Integer cols) {
super();
this.headTextName = headTextName;
this.propertyName = propertyName;
this.cols = cols;
}
/* 省略了get和set方法 */
}
创建一个Excel导入导出工具类ExcelUtil
public class ExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* Excel导入
*/
public static List> getBankListByExcel(InputStream in, String fileName) throws Exception{
List> list = null;
//创建Excel工作薄
Workbook work = getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
//包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
//读取一行
row = sheet.getRow(j);
//去掉空行和表头
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List
导入:
Excel表导入控制器层实现
@RequestMapping("/import")
public String impotr(HttpServletRequest request, Model model) throws Exception {
int adminId = 1;
//获取上传的文件
MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
MultipartFile file = multipart.getFile("upfile");
String month = request.getParameter("month");
InputStream in = file.getInputStream();
//数据导入
salaryService.importExcelInfo(in,file,month,adminId);
in.close();
return "redirect:/salary/index.html";
}
Service层,这里是接口importExcellnfo的实现方法,调用了ExcelUtil里的方法
public void importExcelInfo(InputStream in, MultipartFile file, String salaryDate,Integer adminId) throws Exception{
List> listob = ExcelUtil.getBankListByExcel(in,file.getOriginalFilename());
List salaryList = new ArrayList();
//遍历listob数据,把数据放到List中
for (int i = 0; i < listob.size(); i++) {
List ob = listob.get(i);
Salarymanage salarymanage = new Salarymanage();
//设置编号
salarymanage.setSerial(SerialUtil.salarySerial());
//通过遍历实现把每一列封装成一个model中,再把所有的model用List集合装载
salarymanage.setAdminId(adminId);
salarymanage.setCompany(String.valueOf(ob.get(1)));
salarymanage.setNumber(String.valueOf(ob.get(2)));
salarymanage.setName(String.valueOf(ob.get(3)));
salarymanage.setSex(String.valueOf(ob.get(4)));
salarymanage.setCardName(String.valueOf(ob.get(5)));
salarymanage.setBankCard(String.valueOf(ob.get(6)));
salarymanage.setBank(String.valueOf(ob.get(7)));
//object类型转Double类型
salarymanage.setMoney(Double.parseDouble(ob.get(8).toString()));
salarymanage.setRemark(String.valueOf(ob.get(9)));
salarymanage.setSalaryDate(salaryDate);
salaryList.add(salarymanage);
}
//批量插入
salarymanageDao.insertInfoBatch(salaryList);
}
接着是mapper.xml,用
insert into salarymanage (admin_id, serial,company, number, name,sex, card_name, bank_card,
bank, money, remark,salary_date)
values
(#{item.adminId}, #{item.serial}, #{item.company},#{item.number}, #{item.name},
#{item.sex}, #{item.cardName},#{item.bankCard}, #{item.bank},
#{item.money}, #{item.remark}, #{item.salaryDate})
到这里,excel表的导入功能便完成了。这里补充一下mybatis里
导出:
Excel导出Controller端实现
@RequestMapping("/export")
public @ResponseBody void export(HttpServletRequest request, HttpServletResponse response) throwsClassNotFoundException, IntrospectionException, IllegalAccessException, ParseException, InvocationTargetException {
String salaryDate = request.getParameter("salaryDate");
if(salaryDate!=""){
response.reset(); //清除buffer缓存
Map map=new HashMap();
// 指定下载的文件名,浏览器都会使用本地编码,即GBK,浏览器收到这个文件名后,用ISO-8859-1来解码,然后用GBK来显示
// 所以我们用GBK解码,ISO-8859-1来编码,在浏览器那边会反过来执行。
response.setHeader("Content-Disposition", "attachment;filename=" + new String(salaryDate.getBytes("GBK"),"ISO-8859-1"));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
XSSFWorkbook workbook=null;
//导出Excel对象
workbook = salaryService.exportExcelInfo(salaryDate);
OutputStream output;
try {
output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
bufferedOutPut.flush();
workbook.write(bufferedOutPut);
bufferedOutPut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Service层,这里是exportExcelInfo的实现方法
public XSSFWorkbook exportExcelInfo(String salaryDate) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException {
//根据条件查询数据,把数据装载到一个list中
List list = salarymanageDao.selectApartInfo(salaryDate);
for(int i=0;i excel=new ArrayList<>();
Map> map=new LinkedHashMap<>();
XSSFWorkbook xssfWorkbook=null;
//设置标题栏
excel.add(new ExcelBean("序号","id",0));
excel.add(new ExcelBean("厂名","company",0));
excel.add(new ExcelBean("工号","number",0));
excel.add(new ExcelBean("姓名","name",0));
excel.add(new ExcelBean("性别","sex",0));
excel.add(new ExcelBean("开户名","cardName",0));
excel.add(new ExcelBean("银行卡号","bankCard",0));
excel.add(new ExcelBean("开户行","bank",0));
excel.add(new ExcelBean("金额","money",0));
excel.add(new ExcelBean("备注","remark",0));
map.put(0, excel);
String sheetName = salaryDate + "月份收入";
//调用ExcelUtil的方法
xssfWorkbook = ExcelUtil.createExcelFile(Salarymanage.class, list, map, sheetName);
return xssfWorkbook;
}
这里不写出导出功能的mapper.xml实现语句了,具体实现也就是数据查询,把查询出来的数据转载到一个List中。前端的话便是一个链接的请求,同时补充一点,ajax请求是不支持excel表导出的,因此对于导出时间较长,需要对导出成功做出判断的可以选择在后端生成json数据,在前端利用js进行excel表导出。
以上便是在SSM下使用POI实现excel表的导入和导出的整体思路,主要的导入和导出的核心方法都封装在ExcelUtil这个工具类中,但面对具体的表格需要具体分析循环的开始,以便能够去除表头或者标题栏。