对于批量数据的操作,在项目中引进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 Serializable {
private String headTextName; //列头(标题)名
private String propertyName; //对应字段名
private Integer cols; //合并单元格数
private XSSFCellStyle cellStyle;
/* 省略了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);
}
到这里,excel表的导入功能便完成了。这里补充一下mybatis里
导出:
Excel导出Controller端实现
@RequestMapping("/export")
@ResponseBody
public void export(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, IntrospectionException, IllegalAccessException, ParseException, InvocationTargetException {
response.reset(); //清除buffer缓存
Map map=new HashMap();
// 指定下载的文件名,浏览器都会使用本地编码,即GBK,浏览器收到这个文件名后,用ISO-8859-1来解码,然后用GBK来显示
// 所以我们用GBK解码,ISO-8859-1来编码,在浏览器那边会反过来执行。
try {
response.setHeader("Content-Disposition", "attachment;filename=" + new String("test.xlsx".getBytes("GBK"),"ISO-8859-1")); //此处的文件名后缀为xlsx,不然生成的文件会报损坏
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/vnd.ms-excel--MSEXCEL;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
XSSFWorkbook workbook=null;
//导出Excel对象
workbook = excleService.exportExcelInfo();
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() throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException {
//根据条件查询数据,把数据装载到一个list中
List list = departmentMapper.selectAll();
List excel=new ArrayList<>();
Map> map=new LinkedHashMap<>();
XSSFWorkbook xssfWorkbook=null;
//设置标题栏
excel.add(new ExcelBean("序号","detailedId",0));
excel.add(new ExcelBean("名称","planBaseInfoDate",0));
excel.add(new ExcelBean("编号","deptNo",0));
excel.add(new ExcelBean("前编号","preDeptNo",0));
excel.add(new ExcelBean("电话","phone",0));
map.put(0, excel);
String sheetName = "员工信息"; //sheet名
//调用ExcelUtil的方法
xssfWorkbook = ExcelUtil.createExcelFile(Department.class, list, map, sheetName);
return xssfWorkbook;
}
具体实现也就是数据查询,把查询出来的数据转载到一个List中。前端的话便是一个链接的请求,同时补充一点,ajax请求是不支持excel表导出的,因此对于导出时间较长,需要对导出成功做出判断的可以选择在后端生成json数据,在前端利用js进行excel表导出。
以上便是在SSM下使用POI实现excel表的导入和导出的整体思路,主要的导入和导出的核心方法都封装在ExcelUtil这个工具类中,但面对具体的表格需要具体分析循环的开始,以便能够去除表头或者标题栏。
使用POI导出xls和xlsx格式要注意的问题:
导出xlsx格式:
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.addHeader("Content-Disposition", "attachment;filename=fileName" + ".xlsx");
创建工作薄的时候,用Workbook workbook = new XSSFWorkbook();
导出xls格式:
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename=fileName"+".xls");
创建工作薄的时候,用Workbook workbook = new HSSFWorkbook();
如果创建xlsx工作薄的时候,用
Workbook workbook = new HSSFWorkbook();
生成的excel将无法打开,并有如下提示:
参考:https://blog.csdn.net/hsf15768615284/article/details/73136029
https://blog.csdn.net/a602049511/article/details/52367563