//maven配置
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
/**
* 解析excel
*
* @param cell
* @return
*/
public void doImport(MultipartFile file) {
InputStream fis = null;
Workbook workBook = null;
try {
fis = file.getInputStream();
String fileName = file.getOriginalFilename();
//截取后缀名
String hz = fileName.substring(fileName.lastIndexOf("."), fileName.length());
Sheet tcsSheet;
if(".xlsx".equalsIgnoreCase(hz) || ".xlsx" == hz){
workBook = new XSSFWorkbook(fis);
}else{
workBook = new HSSFWorkbook(fis);
}
//获取sheet的数量
int sheetNum = workBook.getNumberOfSheets();
//遍历sheet,获取sheet中数据
for(int i=0;i<sheetNum;i++){
//判断文件后缀是“.xlsx”还是“.xls”,并进行不同的操作
if(".xlsx".equalsIgnoreCase(hz) || ".xlsx" == hz){
tcsSheet = (XSSFSheet) workBook.getSheetAt(i);
}else{
tcsSheet = (HSSFSheet) workBook.getSheetAt(i);
}
//sheet名
String sheetName = tcsSheet.getSheetName();
int rows=tcsSheet.getPhysicalNumberOfRows();
for (int r = 2; r < rows; r++) {//从第二行开始读
Row row;
if(".xlsx".equalsIgnoreCase(hz) || ".xlsx" == hz){
row = (XSSFRow) tcsSheet.getRow(r);
}else{
row = (HSSFRow) tcsSheet.getRow(r);
}
//第r行第0个单元格
String cell0=getCellValueToString(row.getCell(0));
//第r行第1个单元格
String cell1=getCellValueToString(row.getCell(1));
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (null != workBook) {
workBook.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取列值
*
* @param cell
* @return
*/
private String getCellValueToString(Cell cell) {
String value = StringUtils.EMPTY;
if(null==cell)
return value;
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue();
return value;
}