<!-- 引入excel jar包依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
首先导入依赖
package com.springboot.first.Util;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 com.alibaba.fastjson.JSONObject;
/**
* @ClassName: ImportExcelUtil
* @Description:TODO(导入Excel工具)
* @author: Ironman
* @date: 2019年5月11日 下午11:00:08
*/
public class ImportExcelUtil {
/**
* @Description 导入Excel
* @param fileName 文件名
* @param file 文件
* @param sheetNum 需要导入的表
* @return
* @throws Exception
*/
public static JSONObject importMain(String fileName, MultipartFile file, int sheetNum) throws Exception {
JSONObject ret = new JSONObject();
boolean isSave = true;
String msg = "导入失败!";
List<Map<String, String>> movieList = new ArrayList<Map<String, String>>();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
msg += "\n"+"上传文件格式不正确";
}else {
InputStream is = file.getInputStream();
Workbook wb = null;//声明一个工作簿
if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
wb = new XSSFWorkbook(is);
}else {
wb = new HSSFWorkbook(is);
}
Sheet sheet = wb.getSheetAt(sheetNum);
if(sheet != null){
int columnNum ;
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
Map<String, String> map = new HashMap<String, String>();
Row row = sheet.getRow(r);
if (row == null){
continue;
}else {
// 获取总列数
columnNum = row.getLastCellNum();
for(int i=0; i<columnNum; i++) {
String str = null;
if(row.getCell(i) == null) {
str = row.createCell(i).getStringCellValue();
}else {
row.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
str = row.getCell(i).getStringCellValue();
}
if(str == null || str.isEmpty()){
isSave = false;
msg += "\n"+"第"+(r+1)+"行,"+sheet.getRow(0).getCell(i).getStringCellValue()+"为空!";
}else {
map.put(sheet.getRow(0).getCell(i).getStringCellValue(), str);
}
}
}
movieList.add(map);
}
}
}
if(isSave) {
ret.put("data", movieList);
ret.put("success", true);
}else {
ret.put("data", msg);
ret.put("success", false);
}
return ret;
}
}