一、回顾
在我以前的一篇博客中,我们已经详细的介绍了Excel的解析
在这篇博客里,我们用了最为底层的办法进行封装和解析数据,那接下来我们来介绍一个最简单的解析方法!
二、jar包依赖
首先你需要导入以下的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-poi</artifactId>
<version>5.7.21</version>
<scope>compile</scope>
</dependency>
三、通过SpringBoot脚手架创建工程
这里我们就不创建Thymeleaf模板啦! 而是直接通过前后端分离的方式来访问接口!
四、创建工具类:ExcelUtils
没错相信你的眼睛,就这几行代码!!!
import cn.hutool.poi.excel.ExcelUtil;
import java.io.InputStream;
public class ExcelUtils {
public static void praseExcel(InputStream inputStream){
ExcelUtil.readBySax(inputStream, 0, (sheetIndex, rowIndex, list) -> {
System.out.println(sheetIndex); // 输出第几张表格 从0开始
System.out.println(rowIndex); // 输出第几行数据 从0开始 第一行一般为表头
System.out.println(list); // 每行的数据 封装在一个列表里面
});
}
}
五、创建Controller层和一个html页面
import cn.com.sise.excelprase.utils.ExcelUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class ExcelPraseController {
@RequestMapping("/ExcelPrase")
@ResponseBody
public String pubggupload(@RequestParam("file") MultipartFile file, Model model) throws Exception {
String name=file.getOriginalFilename();
System.out.println(name);
if(!name.substring(name.length()-4).equals(".xls")){
return "格式不正确";
}
ExcelUtils.praseExcel(file.getInputStream());
return "输出成功!";
}
在你的桌面或者其他地方创建一个html页面(地址任意)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="http://localhost:8888/ExcelPrase">
<input type="file" name="file" /><input type="submit" value="上传"/>
</form>
</body>
</html>
六、测试
这样子,就出结果啦!
是不是超级简单呢!赶紧试试看吧!