Excel導入資料
業務場景
批量導入使用者資料
實體類
/**
* Excel表格格式
*
* @author cwt
*/
@Data
public class ImportExcelFile {
/**
* 姓名
*/
private String name;
/**
* 賬号(手機号碼)
*/
private String mobile;
/**
* 密碼
*/
private String password;
}
/**
* 使用者實體類
*
* @author cwt
*/
@Data
public class ImportExcelFile {
/**
* id
*/
private String id;
/**
* 姓名
*/
private String name;
/**
* 賬号(手機号碼)
*/
private String mobile;
/**
* 密碼
*/
private String password;
}
控制層
@Resource
private Service service;
/**
* 批量導入Excel表格資料
* @param file
* @return 響應體
* @author cwt
* @date
*/
@RequestMapping(value = "/importExcel")
public AjaxResult importExcel(MultipartFile file) throws IOException {
service.importExcel(file);
return AjaxResult.success();
}
服務層
public interface Service extends IService<User> {
/**
* 通過excel導入使用者
*
* @param file
* @return java.lang.Boolean
* @author cwt
* @date
*/
Boolean importExcel(MultipartFile file) throws IOException;
}
服務實作類
@Service
public class ServiceImpl extends ServiceImpl<UserMapper, User> implements Service {
@Resource
private UserMapper userMapper;
@Override
public Boolean importExcel(MultipartFile file) throws IOException {
//擷取檔案輸入流
InputStream is = file.getInputStream();
//建立工作蒲用于讀取檔案資訊
ImportExcel importExcel = new ImportExcel();
//調用工作蒲中的方法讀取檔案資訊,此處使用stream流進行周遊插入操作
List<Boolean> userList = importExcel.importDataFromExcel(is, file.getOriginalFilename()).stream.map(a -> {
//原始類型為Object,進行類型強轉
ImportExcelFile userDto = (ImportExcelFile) a;
User user = new User();
BeanUtils.copyBeanProp(user, userDto);
user.setId(UUID.randomUUID().toString())
userMapper.insert(user);
return true;
}).collect(Collectors.toList());
return true;
}
}