未修改之前的代码链接:https://blog.csdn.net/liuchangjie0112/article/details/79479362
代码:
package com.group.express.api.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
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.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.group.express.api.bean.DmsAreaBean;
@SuppressWarnings("serial")
public class ReadExcel implements Serializable{
//总行数
private int totalRows = 0;
//总条数
private int totalCells = 0;
//错误信息接收器
private String errorMsg;
//构造方法
public ReadExcel(){}
//获取总行数
public int getTotalRows(){ return totalRows;}
//获取总列数
public int getTotalCells() { return totalCells;}
//获取错误信息
public String getErrorInfo() { return errorMsg;}
/**
* 读EXCEL文件,获取信息集合
* @param fielName
* @return
*/
public List getExcelInfo(byte[] pic,String name) {
List areaList=new ArrayList();
try {
if (!validateExcel(name)) {// 验证文件名是否合格
return null;
}
boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
if (isExcel2007(name)){
isExcel2003 = false;
}
areaList = createExcel(new ByteArrayInputStream(pic),isExcel2003);
} catch (Exception e) {
e.printStackTrace();
}
return areaList;
}
//mFile.getInputStream()
/**
* 根据excel里面的内容读取客户信息
* @param is 输入流
* @param isExcel2003 excel是2003还是2007版本
* @return
* @throws IOException
*/
public List createExcel(InputStream is, boolean isExcel2003) {
List areaList=new ArrayList();
try{
Workbook wb = null;
if (isExcel2003) {// 当excel是2003时,创建excel2003
wb = new HSSFWorkbook(is);
} else {// 当excel是2007时,创建excel2007
wb = new XSSFWorkbook(is);
}
areaList = readExcelValue(wb);//读取Excel里面客户的信息
} catch (IOException e) {
e.printStackTrace();
}
return areaList;
}
/**
* 读取Excel里面客户的信息
* @param wb
* @return
*/
@SuppressWarnings("deprecation")
private List 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 userList = new ArrayList();
// 循环Excel行数
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null){
continue;
}
DmsAreaBean user = new DmsAreaBean();
// 循环Excel的列
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) {
//如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
String areaName = String.valueOf(cell.getNumericCellValue());
user.setAreaName(areaName.substring(0, areaName.length()-2>0?areaName.length()-2:1));//区域名称
}else{
user.setAreaName(cell.getStringCellValue());//区域名称
}
} else if (c == 1) {
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
String areaNameCh = String.valueOf(cell.getNumericCellValue());
user.setAreaNameCh(areaNameCh.substring(0, areaNameCh.length()-2>0?areaNameCh.length()-2:1));//区域名称英文
}else{
user.setAreaNameCh(cell.getStringCellValue());//区域名称英文
}
} else if (c == 2){
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
String level = String.valueOf(cell.getNumericCellValue());
user.setLevel(Integer.valueOf(level.substring(0, level.length()-2>0?level.length()-2:1)));//级别
}else{
user.setLevel(Integer.valueOf(cell.getStringCellValue()));//级别
}
}else if (c == 3){
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
String parentId = String.valueOf(cell.getNumericCellValue());
user.setParentId(Integer.valueOf(parentId.substring(0, parentId.length()-2>0?parentId.length()-2:1)));//父级ID
}else{
user.setParentId(Integer.valueOf(cell.getStringCellValue()));//父级ID
}
}else if (c == 4){
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
String code = String.valueOf(cell.getNumericCellValue());
user.setCode(code.substring(0, code.length()-2>0?code.length()-2:1));//代码
}else{
user.setCode(cell.getStringCellValue());//代码
}
}else if (c == 5){
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
String sorting = String.valueOf(cell.getNumericCellValue());
user.setSorting(Integer.valueOf(sorting.substring(0, sorting.length()-2>0?sorting.length()-2:1)));//排序
}else{
user.setSorting(Integer.valueOf(cell.getStringCellValue()));//排序
}
}
}
}
// 添加到list
userList.add(user);
}
return userList;
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath){
return filePath.matches("^.+\\.(?i)(xls)$");
}
//@描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
Pom.xml:
commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.5
org.apache.poi
poi
3.17
org.apache.poi
poi-ooxml
3.17
Service层:
/**
* 读取excel中的数据,生成list
*/
String readExcelFile(byte[] pic, String name);
ServiceImpl实现层:
public String readExcelFile(byte[] pic,String name) {
String result ="";
//创建处理EXCEL的类
ReadExcel readExcel=new ReadExcel();
//解析excel,获取上传的事件单
List area = readExcel.getExcelInfo(pic,name);
for (int i = 0; i < area.size(); i++) {
System.out.println("areaLevel="+area.get(i).getLevel());
areabean.insertArea(area.get(i));
}
if(area != null && !area.isEmpty()){
result = "上传成功";
}else{
result = "上传失败";
}
return result;
}
Controller控制层:
public String bulkImport(@RequestParam(value="file",required = false)MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws IOException{
byte[] pic = file.getBytes();
String name = file.getOriginalFilename();
String result = dmsAreaService.readExcelFile(pic,name);
return result;
}
到这一步如果报NULL错在properties加配置文件:
#关闭springboot自带上传组件
spring.http.multipart.enabled=false。
到这一步如果报:Dubbo-Fail to decode request due to: RpcInvocation
将MultipartFile流用byte去进行传输,问题原因,dubbo不支持将MultipartFile序列化。我上面代码已经将MultipartFile用byte代为传输了。
另外我的框架是springboot+mybatis+dubbo,如果框架不同可能会有些许的不同。
比如不用springboot和用springboot以及用springboot+dubbo三者之间就会有些许的不同