通过excel表导入数据到数据库
以下为具体代码:
controller类代码
@Autowired
private SzyPanoramaService szyPanoramaService;
@Autowired
private ImportExcelService excelService;
/**
* 通过excel导入数据库
* @param file
* @return
* @throws Exception
*/
@RequestMapping(value = "/upload")
public ResponseUtils excelupload(@RequestParam(value = "file", required = true) MultipartFile file) throws Exception{
//获取文件名
String fileName = file.getOriginalFilename();
//获取输入流
InputStream inputStream = file.getInputStream();
List<Map<String,String>> mapList = excelService.importExcel(inputStream, fileName);
szyPanoramaService.savePanorama(mapList);
return ResponseUtils.successmsg("返回数据成功",null);
}
新建一个ImportExcelService类
@Service
public class ImportExcelService {
public List<Map<String,String>> importExcel(InputStream inputStream, String fileName) throws Exception {
List<Map<String,String>> list = new ArrayList<>();
boolean notNull = false;
List<SzyPanorama> userList = new ArrayList<SzyPanorama>();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
throw new Exception("上传文件格式不正确");
}
boolean isExcel2003 = true;
if (fileName.matches("^.+\\.(?i)(xlsx)$")