最近工作上接手了一个excel导入的功能,记录一下
首先明白一个excel 文件有多个sheet,一个sheet有多个Row 一个Row有多个Cell。
1.需要的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
<scope>compile</scope>
</dependency>
2.首先封装了一个ExcelUtil 工具类用来处理返回的类型
public class ExcelUtil {
public static Object getCellValue(Row row, int column, boolean flag) {
Object val = null;
Cell cell = row.getCell(column);
if (cell != null) {
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
val = cell.getNumericCellValue();
if (flag) {
val = Double.valueOf(cell.getNumericCellValue()).longValue() + "";
}
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
val = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
val = cell.getCellFormula();
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
val = cell.getBooleanCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
val = null;
}
}
return val;
}
}
3.接着就是我的业务层biz代码,我这个数据的字段有点多所以取的也多,不用关注,关键会用就好了
@Service
public class PublicEquipmentUploadBiz {
@Resource
private PublicEquipmentHisBiz publicEquipmentHisBiz;
private Logger logger = LoggerFactory.getLogger(PublicEquipmentUploadBiz.class);
/**
* 上传Excel文件
* @param file
* @return
* @throws IOException
*/
public ToJson ImportExcelService(MultipartFile file) throws IOException {
ToJson toJson=new ToJson();
String filename = file.getOriginalFilename();
if (filename == null) {
toJson.setMsg("文件为空");
toJson.setStatusCode(500);
}
//调用解析excel文件方法
ToJson toJson1 = readXlsx(filename, file.getInputStream());
if(toJson1.getStatusCode()==200){
toJson.setMsg("操作成功");
}else{
toJson.setStatusCode(500);
toJson.setMsg(toJson1.getMsg());
}
return toJson;
}
/**
* 解析Excel文件
* @param filename
* @param inputStream
* @return
* @throws IOException
*/
public ToJson readXlsx(String filename, InputStream inputStream) throws IOException {
ToJson toJson=new ToJson();
//XSSFWorkbook 需要一个inputStream流 在上面我们已经把file转成了流所以现在直接用就可以了
XSSFWorkbook xssfWorkbook = null;
// 判断excel的后缀,不同的后缀用不同的对象去解析
// xls是低版本的Excel文件
if (filename.endsWith(".xls")) {
xssfWorkbook = new XSSFWorkbook(inputStream);
}
// xlsx是高版本的Excel文件
if (file