今天教甲方导入。因为甲方想自己导入Excel。。所以写一个解析Excel的功能,用户前端上传文件,后台解析文件获得内容存入数据库。
所以写个解析excel的东东,我解析的是.xls文件。
导入依赖:我是gradle,maven的话可以搜一下:
compile'org.apache.poi:poi:3.15'
compile'org.apache.poi:poi-ooxml:3.15'
compile'net.sourceforge.jexcelapi:jxl:2.6.10'
新建了一个Controller。
在这个controller层写上接收前端传过来文件的方法。
Controller层:
@GetMapping(value="/update/price")
public Response updatePrice(@RequestParam("prices",requried=false) MultipartFile file){
Boolean result=updatePrice(file);
return ReponseUtils.createSuccessData(null);
}
Service层:
public Boolean updatePrice(MultipartFile file) throws Exception{
// 创建输入流,读取Excel
InputStream is = file.getInputStream();
// jxl提供的Workbook类
Workbook wb = Workbook.getWorkbook(is);
// Excel的页签数量
int sheetSize = wb.getNumberOfSheets();
if (sheetSize <=0) {
throw new RuntimeException("excel's sheet is zero");
}
// 每个页签创建一个Sheet对象
Sheet sheet = wb.getSheet(0);
List outerList =new ArrayList<>();
TreeMap columnMap =new TreeMap<>();
Date nowTime =new Date();
// sheet.getRows()返回该页的总行数
int rowCnt = sheet.getRows();
for (int i =0; i < rowCnt; i++) {
User user =new User();
if (i ==0) {
// 忽略第一行表头
for (int j =0; j < sheet.getColumns(); j++) {
//坐标位置的内容
String cell = sheet.getCell(j, i).getContents();
if (cell.isEmpty()) {
continue;
}
columnMap.put(j, cell);
}
System.out.println("表头" + columnMap);
continue;
}
// sheet.getColumns()返回该页的总列数
for (int j =0; j < sheet.getColumns(); j++) {
String cell = sheet.getCell(j, i).getContents();
if (cell.isEmpty()) {
continue;
}
String columnName=columnMap.get(j);
if("表头".equals(columnName)){
//"进行赋值",字段=坐标位置的内容;
}
}
outerList.add(user);
}
}
excel文件已经成功解析了,然后可以操作数据了。