“ 最近项目上需要用到 Excel 的导入导出功能,想着之前使用的都有点麻烦,所以结合多方资料,终于找到了这个还算不错的 Excel 处理工具,一起来看”
今日安利好物名为 Hutool-poi
Hutool-poi 是什么?
Java 针对MS Office的操作的库屈指可数,比较有名的就是Apache的POI库。这个库异常强大,但是使用起来也并不容易。Hutool针对POI封装一些常用工具,使Java操作Excel等文件变得异常简单。
Hutool-poi是针对Apache POI的封装,因此需要用户自行引入POI库,Hutool默认不引入。到目前为止,Hutool-poi支持:
Excel文件(xls, xlsx)的读取(ExcelReader)
Excel文件(xls,xlsx)的写出(ExcelWriter)
Hutool-poi 有什么作用?
Hutool-poi 包含了对 Excel 读取和写出的多种 API 封装
ExcelUtil Excel工具类,读取的快捷方法都被封装于此
ExcelReader Excel读取器,Excel读取的封装,可以直接构造后使用。
ExcelWriter Excel生成并写出器,Excel写出的封装(写出到流或者文件),可以直接构造后使用
Hutool-poi 能帮我干什么?
这里我们用 Hutool-poi 来简单实现 Excel 的导入导出
01
—
引入相关依赖
引入 基础相关依赖
<dependency> <groupId>org.apache.poigroupId> <artifactId>poiartifactId> <version>3.17version> dependency> <dependency> <groupId>org.apache.poigroupId> <artifactId>poi-ooxmlartifactId> <version>3.17version> dependency><dependency> <groupId>xercesgroupId> <artifactId>xercesImplartifactId> <version>2.11.0version>dependency>
02
—
实现 Excel 导入导出
1、FileUtil 类
package me.zhengjie.service.impl;import cn.hutool.core.io.IoUtil;import cn.hutool.core.util.IdUtil;import cn.hutool.poi.excel.BigExcelWriter;import cn.hutool.poi.excel.ExcelUtil;import cn.hutool.poi.excel.sax.handler.RowHandler;import com.alibaba.fastjson.JSONArray;import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.text.SimpleDateFormat;import java.util.*;/** * File工具类,扩展 hutool 工具包 * * @author Zheng Jie * @date 2018-12-27 */public class FileUtil extends cn.hutool.core.io.FileUtil { private static ListObject>> lineList = /** * 获取文件扩展名,不带 . */ public static String getExtensionName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length() - 1))) { return filename.substring(dot + 1); } } return filename; } /** * Java文件操作 获取不带扩展名的文件名 */ public static String getFileNameNoEx(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length()))) { return filename.substring(0, dot); } } return filename; } /** * 将文件名解析成文件的上传路径 */ public static File upload(MultipartFile file, String filePath) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS"); String name = getFileNameNoEx(file.getOriginalFilename()); String suffix = getExtensionName(file.getOriginalFilename()); String nowStr = "-" + format.format(date); try { String fileName = name + nowStr + "." + suffix; String path = filePath + fileName; // getCanonicalFile 可解析正确各种路径 File dest = new File(path).getCanonicalFile(); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 文件写入 file.transferTo(dest); return dest; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 导出excel */ public static void downloadExcel(ListString, String tempPath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx"; File file = new File(tempPath); BigExcelWriter writer = ExcelUtil.getBigWriter(file); // 一次性写出内容,使用默认样式,强制输出标题 writer.write(list, true); //response为HttpServletResponse对象 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 response.setHeader("Content-Disposition", "attachment;filename=file.xlsx"); ServletOutputStream out = response.getOutputStream(); // 终止后删除临时文件 file.deleteOnExit(); writer.flush(out, true); //此处记得关闭输出Servlet流 IoUtil.close(out); } /** * excel导入工具类 * * @param file 文件 * @param columNames 列对应的字段名 * @return 返回数据集合 * @throws IOException */ public static ListString, FileInputStream inNew = new FileInputStream(file); if (file.getPath().endsWith(".xlsx")) { //读取数据 ExcelUtil.read07BySax(file, 0, createRowHandler()); } if (file.getPath().endsWith(".xls")) { //读取数据 ExcelUtil.read03BySax(file, 0, createRowHandler()); } //去除excel中的第一行数据 lineList.remove(0); //将数据封装到list中 ListString, for (int i = 0; i < lineList.size(); i++) { if (null != lineList.get(i)) { Map<String, Object> hashMap = new HashMap<>(); for (int j = 0; j < columNames.length; j++) { Object property = lineList.get(i).get(j); hashMap.put(columNames[j], property); } dataList.add(hashMap); } else { break; } } return dataList; } /** * 通过实现handle方法编写我们要对每行数据的操作方式 */ private static RowHandler createRowHandler() { //清空一下集合中的数据 lineList.removeAll(lineList); return new RowHandler() { @Override public void handle(int sheetIndex, int rowIndex, List rowlist) { //将读取到的每一行数据放入到list集合中 JSONArray jsonObject = new JSONArray(rowlist); lineList.add(jsonObject.toJavaList(Object.class)); } }; }}
2、导出
public void downloadTemplate(HttpServletResponse response) throws IOException { List> list = Lists.newArrayList(); Map map = Maps.newLinkedHashMap(); map.put("仓库编号", ""); map.put("仓库名称", ""); list.add(map); FileUtil.downloadExcel(list, response); }
3、导入
public void uploadTemplate(HttpServletRequest request) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map fileMap = multipartRequest.getFileMap(); if (fileMap == null || fileMap.size() == 0) { System.out.println("请上传文件,注意文件的name属性为file"); } for (Map.Entry entry : fileMap.entrySet()) { MultipartFile multipartFile = entry.getValue(); // 4.获取要保存的路径文件夹 String property = request.getSession().getServletContext().getRealPath("/"); property = property.substring(0, property.length() - 5) + "/upload/"; File file = FileUtil.upload(multipartFile, property); List list = new ArrayList<>(); //list list.add("warehouseCode"); list.add("warehouseName"); // list 转 string 数组 String[] str = list.toArray(new String[list.size()]); List> leading = FileUtil.leading(file, str); } }
Hutool 中还有许多实用方法,感兴趣的小伙伴可以多研究下哦
https://hutool.cn/docs/#/