引入maven配置
2.1接收数据
@PostMapping("/lead/excel")
public boolean leadExecl(HttpServletRequest request,
@RequestParam("lead") MultipartFile file) {
System.out.println(file);
if (!file.isEmpty()) {
// ImportEexlService(file);
if (ImportEexlService(file)) {
return true;
}else {
return false;
}
}else {
return false;
}
}
public boolean ImportEexlService(MultipartFile file) {
try {
//解析xlsx后缀的excel文件 xls后缀的暂时没写
//调用方法得到数据
List objects = readXlsx(file.getInputStream());
if (objects.size() !=0) {
//数据存入数据库
String s = writeSql(objects);
}else {
return false;
}
}catch (Exception e) {
e.printStackTrace();
}
return true;
}
2.2分析数据代码
private List readXlsx(InputStream inputStream) {
//XSSFWorkbook 需要一个inputStream流 在上面我们已经把file转成了流所以现在直接用就可以了
try {
//使用此方法不支持excel 2003
// XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
// 为了解决针对excel 2003 和 excel 2007 的多种格式,提高兼容
Workbook sheets = WorkbookFactory.create(inputStream);
//获取第0页信息
Sheet xssfSheet = sheets.getSheetAt(0);
if (xssfSheet !=null) {
List objects =new ArrayList<>();
for (int rowNum =1; rowNum < xssfSheet.getLastRowNum(); rowNum++) {
Row row = xssfSheet.getRow(rowNum);
Menu menu =new Menu();
row.getCell(0).setCellType(XSSFCell.CELL_TYPE_STRING);
String stringCellValue = row.getCell(0).getStringCellValue();
Integer integer = Integer.valueOf(stringCellValue);
menu.setMeId(integer);
row.getCell(1).setCellType(XSSFCell.CELL_TYPE_STRING);
String stringCellValue1 = row.getCell(1).getStringCellValue();
menu.setMeName(stringCellValue1);
row.getCell(2).setCellType(XSSFCell.CELL_TYPE_STRING);
String stringCellValue2 = row.getCell(2).getStringCellValue();
Integer integer1 = Integer.valueOf(stringCellValue2);
menu.setUcId(integer1);
row.getCell(3).setCellType(XSSFCell.CELL_TYPE_STRING);
String stringCellValue3 = row.getCell(3).getStringCellValue();
menu.setUrl(stringCellValue3);
objects.add(menu);
}
return objects;
}
}catch (IOException e) {
e.printStackTrace();
}catch (InvalidFormatException e) {
e.printStackTrace();
}
return null;
}
3.写入数据库
public String writeSql(List objects) {
System.out.println("=======" + objects);
int j =projectService.writeSql(objects);
return null;
}