1、导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
2、解析excel类
public void processModel(MultipartFile modelFile) throws Exception {
List<String> cellList = new ArrayList<>();
List<List<String>> rowList = new ArrayList<>();
boolean a = false;
String modelFilename = modelFile.getOriginalFilename();
if (StringUtils.isBlank(modelFilename)) {
throw new Exception("未选择模板,请重新选择模板!");
}
a = ExcelUtils.validateFileType(modelFilename);
if (a) {
Workbook workbook = null;
try {
workbook = ExcelUtils.getWorkBookFromMultipartFile(modelFile);
} catch (Exception e) {
e.printStackTrace();
log.info("异常信息为:" + e.getMessage());
}
int number = 0;
if (workbook != null) {
number = workbook.getNumberOfSheets();
}
for (int i = 0; i < number; i++) {
Sheet sheet = workbook.getSheetAt(i);
Row row = null;
int lastRowNum = sheet.getLastRowNum();
for (int y = 0; y <= lastRowNum; y++) {
if (y == 0) {
continue;
}
row = sheet.getRow(y);
if (null != row) {
short num = row.getLastCellNum();
log.info("单元格数量为:" + num);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue();
if (StringUtils.isNotBlank(value) && !"".equals(value)) {
cellList.add(value);
log.info(value + "|");
}
}
rowList.add(cellList);
log.info("excel表格行信息为:" + row);
} else {
throw new Exception("excel表内容为空!");
}
}
}
} else {
throw new Exception("excel模板命名异常,请重新命名后上传!");
}
}
3、工具类
package com.fy.service.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.io.*;
public class ExcelUtils {
public static void main(String[] args) throws IOException, InvalidFormatException {
File file = new File("D:\\data\\数据\\数据.xls");
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
HSSFSheet sheet = wb.getSheetAt(i);
Row row = null;
int lastRowNum = sheet.getLastRowNum();
for (int y = 0; y < lastRowNum; y++) {
row = sheet.getRow(y);
if (null != row) {
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
String value = cell.getStringCellValue();
System.out.println(value + "|");
}
System.out.println(row);
}
}
}
}
private final static String excel2003L = ".xls";
private final static String excel2007U = ".xlsx";
private static NumberFormat numberFormat = NumberFormat.getNumberInstance();
static {
numberFormat.setGroupingUsed(false);
}
public static boolean validateFileType(String filename) {
if (!filename.contains(".")) {
return false;
} else {
String fileType = filename.substring(filename.lastIndexOf("."));
switch (fileType) {
case excel2003L: {
return true;
}
case excel2007U: {
return true;
}
default: {
return false;
}
}
}
}
public static Workbook getWork(String url, InputStream inputStream) throws IOException {
Workbook wb = null;
String str = url.substring(url.lastIndexOf("."));
if (excel2003L.equals(str)) {
wb = new HSSFWorkbook(inputStream);
} else if (excel2007U.equals(str)) {
wb = new XSSFWorkbook(inputStream);
} else {
throw new IOException("解析文件格式有误!");
}
return wb;
}
public static String getCellValue(Cell cell) {
Object result = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else {
double d = cell.getNumericCellValue();
result = numberFormat.format(d);
}
break;
case Cell.CELL_TYPE_BOOLEAN:// 布尔
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_FORMULA:// 公式
result = cell.getCellFormula();
break;
case Cell.CELL_TYPE_ERROR:
result = cell.getErrorCellValue();
break;
case Cell.CELL_TYPE_BLANK:
break;
default:
break;
}
}
return result.toString().trim();
}
public static boolean validateExcelHeader(Sheet sheet, int firstRowNum, List<String> columnInfoList) {
Row row = sheet.getRow(firstRowNum);
List<Boolean> flags = new ArrayList<>();
for (int i = 0; i < columnInfoList.size(); i++) {
boolean flag = true;
if (!StringUtils.equals(columnInfoList.get(i).toLowerCase(), ExcelUtils.getCellValue(row.getCell(i)).toLowerCase())) {
flag = false;
break;
}
flags.add(flag);
}
boolean headerFlag = false;
for (Boolean flag : flags) {
headerFlag = (headerFlag || flag);
}
return headerFlag;
}
public static Workbook getWorkBookFromMultipartFile(MultipartFile multipartFile) throws Exception {
Workbook work = null;
try {
work = ExcelUtils.getWork(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
} catch (IOException e) {
throw new Exception("获取excel表对象异常!");
} finally {
if (null != work) {
IOUtils.closeQuietly(work);
}
}
return work;
}
}