读取Excel文件存储在实体类中
1.Maven文件
<!--读取Excel的架包-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.15</version>
</dependency>
2.实体类对象
package com.mz.monotoring.Domain; /**
* @author sjl
* @date 2019-03-28 10:09
*/
public class User {
private String name; private String sex; private String age; private String money; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} public String getMoney() {
return money;
} public void setMoney(String money) {
this.money = money;
}
}
3.Controller层接收Base64位的Excel文件(Postman测试界面)

4.Controller层
package com.mz.monotoring.Controller; import com.mz.monotoring.Domain.User;
import com.mz.monotoring.Util.Base64File;
import com.mz.monotoring.Util.ReadExcelUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID; /**
* @author sjl
* @date 2019-03-26 13:56
*/
@Controller
public class ExcelController { @RequestMapping("excel")
@ResponseBody
public List<User> excel(@RequestBody Map map) {
List<User> excelInfo = null;
//读取到的Excel保存的位置
//linux保存路径
//String path1 = "/usr/local/tomcatusps/apache-tomcat-8.5.15/Root/excel/";
try {
//Window保存路径
String path1 = "F:\\excel";
File files = new File(path1);
files.mkdir(); String[] w1 = map.get("key").toString().split(",");
String s1 = new StringBuilder().append(UUID.randomUUID().toString()).append(".").append("xlsx").toString();
String s = new StringBuilder().append(path1).append("\\").append(s1).toString();
Base64File.decoderBase64File(w1[1], path1 + "\\" + s1);
ReadExcelUtils excelUtils = new ReadExcelUtils();
File newFile = new File(s);
FileInputStream input = new FileInputStream(newFile);
MultipartFile multipartFile = new MockMultipartFile("excelUtils", newFile.getName(), "text/plain", input); excelInfo = excelUtils.getExcelInfo(multipartFile);
} catch (IOException e) {
e.printStackTrace();
}
return excelInfo;
}
}
5.Base64File将读取到的base64位字符串转化为文件存储至本地
package com.mz.monotoring.Util; import sun.misc.BASE64Decoder; import java.io.FileOutputStream;
import java.io.IOException; public class Base64File { /**
* 将base64字符解码保存文件
*
* @param base64Code
* @param targetPath
* @throws Exception
*/ public static void decoderBase64File(String base64Code, String targetPath) {
byte[] buffer;
FileOutputStream out = null;
try {
buffer = new BASE64Decoder().decodeBuffer(base64Code);
out = new FileOutputStream(targetPath);
out.write(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} }
6.读取文件 判断是什么版本Excel并且循环读取每层数据存储实体类中
package com.mz.monotoring.Util; import com.mz.monotoring.Domain.User;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile; import java.io.IOException;
import java.io.InputStream;
import java.util.*; /**
* @author sjl
* @date 2019-03-27 11:11
*/
public class ReadExcelUtils {
// 总行数
private int totalRows = 0;
// 总条数
private int totalCells = 0;
// 错误信息接收器
private String errorMsg; //构造方法
public ReadExcelUtils() {
} public int getTotalRows() {
return totalRows;
} public int getTotalCells() {
return totalCells;
} public String getErrorMsg() {
return errorMsg;
} public List<User> getExcelInfo(MultipartFile mFile) {
//获取文件名
String fileName = mFile.getOriginalFilename();
try {
//验证文件名是否合格
if (!validateExcel(fileName)) {
return null;
}
//根据文件名判断文件是2003版本还是2007版本
boolean isExcel2003 = true;
if (isExcel2007(fileName)) {
isExcel2003 = false;
}
return createExcel(mFile.getInputStream(), isExcel2003);
} catch (IOException e) {
e.printStackTrace();
}
return null;
} /**
* 根据excel里面的内容读取客户信息
*
* @param is 输入流
* @param isExcel2003 excel是2003还是2007版本
* @return
* @throws IOException
*/
private List<User> createExcel(InputStream is, boolean isExcel2003) {
try {
Workbook wb = null;
//当excel是2003时,创建excel2003
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
//读取Excel里面的信息
return readExcelValue(wb);
} catch (IOException e) {
e.printStackTrace();
}
return null;
} private List<User> readExcelValue(Workbook wb) {
//得到都一个shell
Sheet sheet = wb.getSheetAt(0);
//得到Excel的行数
this.totalRows = sheet.getPhysicalNumberOfRows();
//得到Excel的列数(前提是有行数)
if (totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<User> userList = new ArrayList<>();
//循环Excel行数
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
//循环Excel的列
Map<String, Object> map = new HashMap<>(16);
if (isRowEmpty(row) == false) {
User user = new User();
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (cell != null) {
if (c == 0) {
//判断其中是否包含空格
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String name = String.valueOf(cell.getNumericCellValue());
user.setName(name.substring(0, name.length() - 2 > 0 ? name.length() - 2 : 1));
} else if (cell.getStringCellValue() != null) {
//导入姓名
user.setName(cell.getStringCellValue());
} else {
user.setName("");
}
} else if (c == 1) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String sex = String.valueOf(cell.getNumericCellValue());
user.setSex(sex.substring(0, sex.length() - 2 > 0 ? sex.length() - 2 : 1));
} else if (cell.getStringCellValue() != null) {
//性别
user.setSex(cell.getStringCellValue());
} else {
user.setSex("");
}
} else if (c == 2) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String age = String.valueOf(cell.getNumericCellValue());
user.setAge(age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));
} else if (cell.getStringCellValue() != null) {
//年龄
user.setAge(cell.getStringCellValue());
} else {
user.setAge("");
}
} else if (c == 3) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String money = String.valueOf(cell.getNumericCellValue());
user.setMoney(money.substring(0, money.length() - 2 > 0 ? money.length() - 2 : 1));
} else if (cell.getStringCellValue() != null) {
//工资
user.setMoney(cell.getStringCellValue());
} else {
user.setMoney("");
}
}
}
}
//将读取到的数据添加到list集合中
userList.add(user);
}
} return userList;
} /**
* 判断EXCEL是否为空
*
* @param row
* @return
*/
private boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
return false;
} }
return false;
} /**
* 验证EXCEL文件
*
* @param fileName
* @return
*/
private boolean validateExcel(String fileName) {
if (fileName == null || !(isExcel2003(fileName) || isExcel2007(fileName))) {
errorMsg = "文件不是excel格式";
return false;
}
return true;
} /**
* 是否是2007的excel,返回true是2007
*
* @param fileName
* @return
*/
private boolean isExcel2007(String fileName) {
return fileName.matches("^.+\\.(?i)(xlsx)$");
} /**
* 是否是2003的excel,返回true是2003
*
* @param fileName
* @return
*/
private boolean isExcel2003(String fileName) {
return fileName.matches("^.+\\.(?i)(xls)$");
}
}
7.读取的Excel文件内容截图

8.Postman测试返回的List<User>数据

读取Excel文件存储在实体类中的更多相关文章
- .Net Core NPOI读取Excel 并转为数据实体类
创建应用程序 这里直接创建Console程序 引用NPOI的NuGet包 PM> Install-Package NPOI -Version 2.5.1 直接Nuget包管理器添加 导入Exce ...
- Java实现POI读取Excel文件,兼容后缀名xls和xlsx
1.引入所需的jar包: maven管理项目的话直接添加以下坐标即可: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -- ...
- 读取Excel文件中的单元格的内容和颜色
怎样读取Excel文件中的单元格的内容和颜色 先创建一个Excel文件,在A1和A2中随意输入内容,设置A1的字体颜色为红色,A2的背景为黄色.需要 using Excel = Microsoft.O ...
- 如何在C#中打开和读取EXCEL文件
这篇文章向您展示如何在C#Windows Forms Application中使用ExcelDataReader,ExcelDataReader.DataSet打开和读取Excel文件.创建一个新的W ...
- 用python的pandas读取excel文件中的数据
一.读取Excel文件 使用pandas的read_excel()方法,可通过文件路径直接读取.注意到,在一个excel文件中有多个sheet,因此,对excel文件的读取实际上是读取指定文件.并 ...
- java 读取Excel文件并数据持久化方法Demo
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util ...
- 读取Excel文件的两种方法
第一种方法:传统方法,采用OleDB读取EXCEL文件, 优点:写法简单,缺点:服务器必须安有此组件才能用,不推荐使用 private DataSet GetConnect_DataSet2(stri ...
- 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据
1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...
- 基于Java+Selenium的WebUI自动化测试框架(十一)-----读取Excel文件(POI)(1)
上一篇说了利用JXL的jar包来读取Excel的代码.在Java中,还可以用另外一种jar包来读取Excel的内容,那就是Apache的POI. 这里和之前一样,需要导入POI的jar包,建议导入这三 ...
随机推荐
- pycharm+selenium搭建环境
1.在你的python安装目录D:\Python36\Scripts下执行pip install selenium 2.安装完成后最好直接打开python,在下面输入from selenium imp ...
- 奇yin技巧
关于一些奇yin技巧 关于删除字符串中的一些字串,并且考虑新的字串 例题:luogu4824 luogu3121 方法:开一个栈记录,发现字串后剪去字串长度. for(int i=1;i<=le ...
- openwrt查看flash、RAM、CPU信息
1.查看Flash容量大小(存储空间,可以理解为电脑的硬盘) root@OpenWrt:/# dmesg |grep spi |grep Kbytes #查看Flash容量[ 0.660000 ...
- tomcat 网页管理tomcat
一.设置管理员账户密码 进入tomcat安装目录 ->进入conf目录->修改user.xml->加入下面内容 模板 <role rolename="manager- ...
- 键盘keyCode值
参考地址: https://blog.csdn.net/qq_25835645/article/details/78788987
- 防XSS攻击解决方法
1.web.xml文件中新增filter配置 <!-- URL请求参数字符过滤或合法性校验 --> <filter> <filter-name>XssFilter& ...
- 出错: IOException parsing XML document from ServletContext resource [/cn.mgy.conig]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/cn.mgy.conig]
错误的详细内容: 严重: StandardWrapper.Throwable org.springframework.beans.factory.BeanDefinitionStoreExceptio ...
- 出错:Error creating bean with name 'studentServiceImpl': Unsatisfied dependency expressed through field 'studentMapper';
详细错误: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with nam ...
- python-常见数据类型及其方法
常见数据类型及其方法 1.None: 表示空(无任何功能,专门用于提供空值) 2.整形(int) 3.布尔类型(bool) 只有两个结果:True/False: 0/''/[]/()/{}/set() ...
- Python之copy模块
概念 官方解释:Python中的赋值语句不复制对象,它们在目标和对象之间建立索引.对于可变项目或可变项目的集合,有时需要一个副本,以便可以更改一个副本而不更改其他副本.该模块提供通用的浅层和深层cop ...