应用场景:
后台web页面上传数据excel文件,java后端接口实现excel转换到集合中,进行具体业务操作,例批量导入数据库等;
1.maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
2.utils类
/**
* 读取EXCEL文件
*
* @param fielName
* @return
*/
public List<String> getExcelInfo(String fileName, MultipartFile Mfile) {
// 把spring文件上传的MultipartFile转换成File
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File file = fi.getStoreLocation();
List<String> userList = new ArrayList<String>();
InputStream is = null;
try {
// 验证文件名是否合格
if (!validateExcel(fileName)) {
return null;
}
// 判断文件时2003版本还是2007版本
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
is = new FileInputStream(file);
userList = getExcelInfo(is, isExcel2003);
is.close();
}
catch (Exception e) {
log.getLogger("excelUtil_s").error("getExcelInfo-ex", e.getMessage());
// e.printStackTrace();
}
finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
is = null;
log.getLogger("excelUtil_s").error("FileInputStream-close-fail", e.getMessage());
// e.printStackTrace();
}
}
}
return userList;
}
public List<String> getExcelInfo(InputStream is, boolean isExcel2003) {
List<String> userList = null;
try {
Workbook wb = null;
// 当excel是2003时
if (isExcel2003) {
wb = new HSSFWorkbook(is);
}
else {
wb = new XSSFWorkbook(is);
}
userList = readExcelValue(wb);
}
catch (IOException e) {
log.getLogger("excelUtil_s").error("readExcel-IOException", e.getMessage());
// e.printStackTrace();
}
return userList;
}
/**
* 获取Excel的信息:行和列
*
* @param wb
* @return
*/
private List<String> 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<String> userList = new ArrayList<String>();
String String;
// 循环row:行
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null)
continue;
// String = new String();
// for (int c = 0; c < this.totalCells; c++) {
// Cell cell = row.getCell(c);
// if (null != cell) {
// // 第一列
// if (c == 0) {
// String.setUserName(cell.getStringCellValue());
// }
// else if (c == 1) {
// DecimalFormat df = new DecimalFormat("#");
// String cellValue = df.format(cell.getNumericCellValue());
// String.setUserNumber(cellValue);
// }
// }
// }
// 循环每个row的cell:列,本次业务只有一列
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
// 第一列
if (c == 0 && !"".equals(cell.getStringCellValue())) {
userList.add(cell.getStringCellValue());// 获取cell中的字符串值(cell提供获取各种类型的api)
}
}
break;
}
}
return userList;
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
// excel 2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// excel 2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
private int totalRows = 0; private int totalCells = 0; private String errorMsg;
public ReadExcelUtil() {
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getTotalCells() {
return totalCells;
}
public void setTotalCells(int totalCells) {
this.totalCells = totalCells;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
3.test
1)postman
2)controller层
/**
* 批量导入数据
*
* @param headerKey 提货码商品编号,inputFile 导入的文件
* @param request
* @return
*/
@RequestMapping(value = "/import.ctrl", produces = "application/json")
@ResponseBody
public void importCode(@RequestParam Long headerKey, @RequestParam(required = true) MultipartFile inputFile, HttpServletRequest request) {
pickCodeService.batchInputCode(inputFile, request, headerKey);
}
3)service 具体业务的实现
public Map<String, Object> batchInputCode(MultipartFile inputFile, HttpServletRequest request, Long headerKey) {
Map<String, Object> response = Maps.newHashMap();
List<String> excel_list = Lists.newArrayList();
excel_list = this.excelIntoList(inputFile);
if (excel_list != null && excel_list.size() > 0) {
//使用获取的数据执行数据库操作
}
response.put("status", "success");
return response;
}
4.参考文章:https://blog.csdn.net/m0_37527542/article/details/74542587