1.maven

  <!-- 解压rar --><dependency><groupId>com.github.junrar</groupId><artifactId>junrar</artifactId><version>0.7</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId></dependency><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.1.2</version></dependency>

2. 工具类

package com.dlax.pinfo.common.utils;import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;/*** @author l* @version 1.0* @PACKAGE_NAME: com.dlax.pinfo.common.utils* @date 2022/3/31 16:27 周四* 解压上传zip文件*/
@Slf4j
public class ZipUtils {public ZipUtils() {}/*** @param sourcefiles       源文件(服务器上的zip包存放地址)* @param decompreDirectory 解压缩后文件存放的目录* @throws IOException IO异常*                     <p>*                     例子 unzip(new File("E:/Study/java.zip"), "E:/Study/unzip/");*/@SuppressWarnings("unchecked")public static void unzip(String sourcefiles, String decompreDirectory) throws IOException {ZipFile readfile = null;try {readfile = new ZipFile(sourcefiles, Charset.forName("GBK"));//,枚举Enumeration takeentrie = readfile.entries();ZipEntry zipEntry = null;File credirectory = new File(decompreDirectory);credirectory.mkdirs();while (takeentrie.hasMoreElements()) {zipEntry = (ZipEntry) takeentrie.nextElement();String entryName = zipEntry.getName();InputStream in = null;FileOutputStream out = null;try {if (zipEntry.isDirectory()) {String name = zipEntry.getName();name = name.substring(0, name.length() - 1);File createDirectory = new File(decompreDirectory + File.separator + name);createDirectory.mkdirs();} else {int index = entryName.lastIndexOf("\\");if (index != -1) {File createDirectory = new File(decompreDirectory + File.separator + entryName.substring(0, index));createDirectory.mkdirs();}index = entryName.lastIndexOf("/");if (index != -1) {File createDirectory = new File(decompreDirectory + File.separator + entryName.substring(0, index));createDirectory.mkdirs();}File unpackfile = new File(decompreDirectory + File.separator + zipEntry.getName());in = readfile.getInputStream(zipEntry);out = new FileOutputStream(unpackfile);int c;byte[] by = new byte[1024];while ((c = in.read(by)) != -1) {out.write(by, 0, c);}out.flush();}} catch (IOException ex) {ex.printStackTrace();throw new IOException("解压失败:" + ex.toString());} finally {if (in != null) {try {in.close();} catch (IOException ex) {}}if (out != null) {try {out.close();} catch (IOException ex) {ex.printStackTrace();}}in = null;out = null;}}} catch (IOException ex) {throw new IOException("解压失败:" + ex.toString());} finally {if (readfile != null) {try {readfile.close();} catch (IOException ex) {throw new IOException("解压失败:" + ex.toString());}}}}/*** 解压rar格式压缩包。* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar*/@SuppressWarnings("unchecked")public static void unrar(String sourceRar, String destDir) throws Exception {Archive a = null;FileOutputStream fos = null;try {a = new Archive(new File(sourceRar));FileHeader fh = a.nextFileHeader();while (fh != null) {if (!fh.isDirectory()) {//1 根据不同的操作系统拿到相应的 destDirName 和 destFileName//String compressFileName = fh.getFileNameString().trim();String compressFileName = fh.getFileNameW().trim();if (!existZH(compressFileName)) {compressFileName = fh.getFileNameString().trim();}String destFileName = "";String destDirName = "";//非windows系统if (File.separator.equals("/")) {destFileName = destDir + compressFileName.replaceAll("\\\\", "/");destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));//windows系统} else {destFileName = destDir + compressFileName.replaceAll("/", "\\\\");destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));}//2创建文件夹File dir = new File(destDirName);if (!dir.exists() || !dir.isDirectory()) {dir.mkdirs();}//3解压缩文件fos = new FileOutputStream(new File(destFileName));a.extractFile(fh, fos);fos.close();fos = null;}fh = a.nextFileHeader();}a.close();a = null;} catch (Exception e) {log.error("解压rar格式压缩包失败:"+ e.getMessage());} finally {if (fos != null) {try {fos.close();fos = null;} catch (Exception e) {log.error("fos.close失败:"+ e.getMessage());}}if (a != null) {try {a.close();a = null;} catch (Exception e) {log.error("a.close失败:"+ e.getMessage());}}}}/*** 获得以.xls为后缀的Excel文件** @param path* @return*/public static File getExcelFile(String path) {File file = new File(path);//判断当前目录是否存在if (!file.exists()) {log.error("获得以.xls为后缀的Excel文件失败!");return null;}//取得当前目录下所有文件和文件夹String[] content = file.list();for (String name : content) {File temp = new File(path, name);//判断是否是目录if (temp.isDirectory()) {String[] con = temp.list();for (String name1 : con) {if (name1.endsWith(".xls") || name1.endsWith(".xlsx")) {File excelFile = new File(temp, name1);return excelFile;}}} else if (name.endsWith(".xls") || name.endsWith(".xlsx")) {return temp;}}return null;}/*** 解决linux下rar包名字中文乱码** @param str* @return*/public static boolean existZH(String str) {String regEx = "[\\u4e00-\\u9fa5]";Pattern p = Pattern.compile(regEx);Matcher m = p.matcher(str);while (m.find()) {return true;}return false;}/*** 获取zip包下的文件夹名称** @param path* @return* @throws IOException*/public static String readZipFile(String path) {String mFileChange  = null;ZipEntry zipEntry = null;ZipInputStream zipInputStream = null;File file = new File(path);try {//判断文件是否存在if (file.exists()) {//解决包内文件存在中文时的中文乱码问题FileInputStream fileInputStream = new FileInputStream(path);zipInputStream = new ZipInputStream(fileInputStream, Charset.forName("GBK"));while ((zipEntry = zipInputStream.getNextEntry()) != null) {//只读取包内根目录文件的文件名if (zipEntry.isDirectory()) {mFileChange = zipEntry.getName();}
//                    else {
//                        mFileChange += zipEntry.getName().substring(zipEntry.getName().lastIndexOf("/") + 1, zipEntry.getName().lastIndexOf(".")) + "\n";
//                    }}}log.info("拼接后的文件名称为:" + mFileChange);} catch (Exception e) {log.error("获取zip包下的文件夹名称失败:"+ e.getMessage());} finally {if (zipInputStream != null) {try {zipInputStream.close();} catch (IOException e) {log.error("关闭zip包下的文件夹名称失败:" + e.getMessage());}}}return mFileChange;}/*** 删除生成的zip包* @param f* @param name*/public static void delete(File f, String name) {//数组指向文件夹中的文件和文件夹File[] fi = f.listFiles();//遍历文件和文件夹for (File file : fi) {if (file.isFile()) {//是文件的话,把文件名放到一个字符串中String filename = file.getName();if (filename.equals(name)) {file.delete();}}}}/*** 删除文件夹* @param file*/public static void deleteFile(File file) {//判断文件不为null或文件目录存在if (file == null || !file.exists()) {log.info("文件删除失败,请检查文件路径是否正确");}//取得这个目录下的所有子文件对象File[] files = file.listFiles();//遍历该目录下的文件对象for (File f : files) {//判断子目录是否存在子目录,如果是文件则删除if (f.isDirectory()) {deleteFile(f);} else {f.delete();}}//删除空文件夹  for循环已经把上一层节点的目录清空。file.delete();}}

3.POIutils 工具类

package com.dlax.pinfo.common.utils;import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.extern.slf4j.Slf4j;import java.io.InputStream;
import java.util.List;/*** @author l* @version 1.0* @PACKAGE_NAME: com.dlax.pinfo.common.utils* @date 2022/3/31 16:38 周四*/
@Slf4j
public class POIutils {/*** poi获取表格数据** @param input* @param pojoClass* @param <T>* @return*/public static <T> List<T> importExcel(InputStream input, Class<T> pojoClass) {if (input == null) {return null;}ImportParams params = new ImportParams();List<T> list = null;try {list = ExcelImportUtil.importExcel(input, pojoClass, params);} catch (Exception e) {list.add((T) "");log.error("poi获取表格数据失败:" + e.getMessage());}return list;}}

4.引用类

    @RequestMapping(value = "/importZip", method = RequestMethod.POST)public synchronized CommonResult importStaffZip(MultipartFile file) {CommonResult  commonResult=null;if (file == null || file.isEmpty()) {return CommonResult.failed("请选择导入文件");}String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));if (!".zip".equals(suffix) && !".rar".equals(suffix)) {return CommonResult.failed("导入文件格式错误");}
//        // 判断是否可以导入  系统中同一时间只能有一处导入
//        if (excelProgressUtils.canImport()) {
//            return CommonResult.ok(null, "导入功能正在使用,请稍后再试!", -1);
//        }// 保存文件到指定目录String filePath = dPath  + file.getOriginalFilename();//解压后的文件路径String fileUrl = null;InputStream inputStream =null;try {// 保存文件File dest = new File(filePath);if (!dest.getParentFile().exists()) {dest.getParentFile().mkdirs();}if (!file.isEmpty()) {//转存文件到服务器//file.transferTo(dest);//这个方法需要待考证FileUtils.copyInputStreamToFile(file.getInputStream(), dest);}//保证文件夹路径最后是"/"或者"\"char lastChar = dPath.charAt(dPath.length() - 1);if (lastChar != '/' && lastChar != '\\') {dPath += File.separator;}// 压缩包里面的文件名String getfileName= ZipUtils.readZipFile(filePath);//根据类型,进行相应的解压缩String type = filePath.substring(filePath.lastIndexOf(".") + 1);if (type.equals("zip")) {ZipUtils.unzip(filePath, dPath);} else if (type.equals("rar")) {ZipUtils.unrar(filePath, dPath);}if(StringUtils.isBlank(getfileName)){return CommonResult.failed("获取压缩包里面的文件名失败");}//解压后的文件路径fileUrl = dPath + getfileName.split("/")[0];//判断导入的包是否为空File excelFile = ZipUtils.getExcelFile(dPath);if (excelFile== null) {// 删除压缩包以及文件夹File file1 = new File(dPath);//删除文件ZipUtils.delete(file1, file.getOriginalFilename());//删除文件夹ZipUtils.deleteFile(file1);return CommonResult.failed("导入文件格式错误");}//读取Excel文件获取值Class<ExcelPersonTable> entity = ExcelPersonTable.class;File newFile = ZipUtils.getExcelFile(fileUrl);inputStream = new FileInputStream(newFile);List<ExcelPersonTable> excelPersonDataList = POIutils.importExcel(inputStream, entity);if (excelPersonDataList == null) {//删除文件File file1 = new File(dPath);ZipUtils.delete(file1, file.getOriginalFilename());ZipUtils.deleteFile(file1);return CommonResult.failed("人员信息为空");}log.info("获取excel表格的数据:"+JSONUtil.toJsonStr(excelPersonDataList));commonResult=basaePersonService.addExcelPersonData(fileUrl,excelPersonDataList);} catch (Exception e) {log.error("导入人员失败:" + e.getMessage());} finally {if (inputStream != null) {try {inputStream.close();} catch (Exception e) {log.error("inputStream.close失败:"+ e.getMessage());}}// 删除压缩包以及文件夹File file1 = new File(dPath);ZipUtils.delete(file1, file.getOriginalFilename());File file2 = new File(fileUrl);ZipUtils.deleteFile(file2);}return commonResult;}

解压上传zip文件并获取excel表数据相关推荐

  1. Java解压上传zip或rar文件,并解压遍历文件中的html的路径

    1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception {HttpSession session = request.getSes ...

  2. C#压缩或解压(rar和zip文件)

    为了便于文件在网络中的传输和保存,通常将文件进行压缩操作,常用的压缩格式有rar.zip和7z,本文将介绍在C#中如何对这几种类型的文件进行压缩和解压,并提供一些在C#中解压缩文件的开源库. 在C#. ...

  3. 推荐一款好用解压RAR、ZIP文件Mac软件,可以输入密码Dr. Unarchiver

    推荐一款好用解压RAR.ZIP文件Mac软件,可以输入密码Dr. Unarchiver. 今天工作中Windows发给我一个加密RAR文件,是公司很重要的文件,可是Mac不支持呀,因此我把App St ...

  4. java上传zip文件并解压读取

    最近遇到一个这样的需求:传一个压缩包给后台,后台保存后解压读取里面的文件,现学现做.在这里做个记录 文件上传 文件上传有很多方法,这里推荐一个自己感觉挺好用的一种,代码奉上: @PostMapping ...

  5. Java实现minio文件服务web在线解压上传工具类

    前言 文章中的web解压工具类结合了minio文件服务,上传解压文件过程中,先解压成文件流,再将解压的文件又上传到minio文件服务器上.(不同本地文件服务,可以直接用文件copy的方式,cpoy到服 ...

  6. 【Ubuntu】使用zip方法解压分卷压缩ZIP文件

    提前检查磁盘是否有足够的空间,合并分卷压缩文件,合并完成后正常解压即可 分卷压缩文件示例:dataset.zip dataset.z01 - zip -s 0 dataset.zip --out DA ...

  7. vue上传zip文件到服务器,element+Vue上传zip文件

    ref : 绑定DOM元素 action:接口地址 data : 你要传入的参数 on-preview:点击文件列表中已上传的文件时的钩子 name:文件的参数名 on-remove :移除你上传的文 ...

  8. java解压两层zip文件_Java解压缩zip - 解压缩多个文件或文件夹实例

    java解压缩zip - 多个文件(包括文件夹),具体如下: 对多个文件和文件夹进行压缩,对复杂的文件目录进行解压. 压缩方法使用的是可变参数,可以压缩1到多个文件..可以写数组的方式或者一个个写到参 ...

  9. vue上传zip文件到服务器,vue.js zip文件上传

    vue.js zip文件上传 内容精选 换一换 开发过程中,您有任何问题可以在github上提交issue,或者在华为云对象存储服务论坛中发帖求助.接口参考文档详细介绍了每个接口的参数和使用方法.在O ...

最新文章

  1. 数字双胞胎技术和物联网如何帮助企业取得成功
  2. shell笔记之sed编辑器的基础用法(上)
  3. 关于weblogic server对docker的支持
  4. Python3中的 Filter的改变
  5. 带有Hibernate OGM的NoSQL –第三部分:在WildFly上构建REST应用程序
  6. 广州市城市智能交通大数据体系研究与实践
  7. ECCV 2020 论文大盘点-3D人体姿态估计篇
  8. 梳理数仓FI manager节点健康检查逻辑
  9. Go 神坑 1 —— interface{} 与 nil 的比较
  10. 中缀表达式转后缀表达式规则
  11. html 警告图标,HTML+CSS入门 CSS实现核辐射警告标志
  12. vs 2019生成类试图
  13. Revit建模软件:如何在Revit中准确放置族组件?
  14. echarts 环状图中添加图片
  15. iOS 6与iOS 7的增量更新的区别
  16. 南卡VS明基护眼台灯对比评测,2022买哪款护眼灯比较好?
  17. Astro VG876图像信号发生器控制软件
  18. 浅析硬件“好声音”:喇叭技术指标及选型指南
  19. 新概念英语第一册 (1)
  20. java文件预览和文件下载响应设置

热门文章

  1. 2017年9月10日训练日记
  2. Object,byte[],ByteBuffer之间的转换。
  3. 阿里CEO盒马内部演讲实录:跑得久才是最关键的
  4. Java概述-Java技术体系标准:SE、EE、ME
  5. C语言标准化输入、输出字符
  6. c语言中void的用法
  7. 外文翻译原文附在后面_外文翻译及外文原文(参考格式).doc
  8. 关于Cron表达式中的周一至周五正确的配置
  9. python 正则表达式-匹配规则
  10. win 10家庭版升专业版报错:0xC004F069在运行Microsoft Windows非核心版本的计算机上……