SpringBoot 实现Excel文件解析(简单版)

这篇博客介绍了如何在SpringBoot中实现Excel文件的简单解析。通过引入Apache POI依赖,创建工具类ExcelUtils和Controller层,实现了前后端分离的数据导入功能。教程详细讲解了每个步骤,包括创建工程、编写工具类和测试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、回顾

在我以前的一篇博客中,我们已经详细的介绍了Excel的解析

        SpringBoot 实现Excel文件解析_cyc&阿灿的博客-CSDN博客一、前言对于现在的后台管理系统而言,批量导入数据是一个再熟悉不过的功能了。批量导入能够快速的实现数据流的输入,减少了管理员手动添加数据的时间成本。接下来由阿灿我来介绍一下集成SpringBoot 实现批量导入Excel数据的功能。二、依赖准备:这里我们使用apache下的poi依赖,当然你也可以使用阿里巴巴的easyexcel工具类(下次我们再聊) <dependency> <groupId>org.apache.poi<https://blog.csdn.net/m0_66884848/article/details/123652998

在这篇博客里,我们用了最为底层的办法进行封装和解析数据,那接下来我们来介绍一个最简单的解析方法!

二、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>

六、测试

 

这样子,就出结果啦! 

 

 是不是超级简单呢!赶紧试试看吧!