发布于2021-03-13 14:05 阅读(1452) 评论(0) 点赞(29) 收藏(0)
/**
* 导入人员列表
*/
@PostMapping("/workSheet/upload")
public void importExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
String fileName = file.getOriginalFilename();
boolean fileIsExcel = Objects.requireNonNull(fileName).matches("^.+\\.(?i)(xls)$") || fileName.matches("^.+\\.(?i)(xlsx)$");
if (!fileIsExcel) {
throw new GlobalException(400,"文件格式错误");
}
InputStream inputStream = file.getInputStream();
ImportParams importParams = new ImportParams();
// 需要验证
importParams.setNeedVerfiy(true);
ExcelImportResult<ImUsersPO> requestList = ExcelImportUtil.importExcelMore(inputStream, ImUsersPO.class, importParams);
List<ImUsersPO> list = requestList.getList();
list.forEach(o->{
if(null != o){
//保存到数据库
baseUserService.addUser(o);
}
});
//判断是否有错误
if(requestList.isVerfiyFail()){
//getFailList()里面的就是所有校验失败的excel数据
List<ImUsersPO> failList = requestList.getFailList();
System.out.println(failList);
ExportParams params = new ExportParams();
params.setSheetName("工单批量导入错误数据");
Workbook workbook = ExcelExportUtil.exportExcel(params, ImUsersPO.class, failList);
EasypoiUtil.downLoadExcel("workSheet_error.xls", response, workbook);
}
}
/**
* 导出人员列表
*/
@RequestMapping(value = "/downLoadExcel", method = RequestMethod.GET)
@ResponseBody
public void downLoadExcel( HttpServletResponse response) {
try {
String title = "人员表"; //标题名
String sheetName = "人员表"; //表名
//需要导出的数据
List<UserBaseInfoDTO> userBaseInfoDTOS = baseUserService.loadAllUserList();
ExcelUtils.exportExcel(userBaseInfoDTOS, title, sheetName, UserBaseInfoDTO.class, String.valueOf(System.currentTimeMillis()), response);
} catch (Exception e) {
throw new GlobalException(400,"导出失败");
}
}
/**
* Excel导入导出工具类
*/
public class ExcelUtils {
private static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
/**
* excel 导出
*
* @param list 数据列表
* @param fileName 导出时的excel名称
* @param response
*/
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, fileName, response);
}
/**
* 默认的 excel 导出
*
* @param list 数据列表
* @param fileName 导出时的excel名称
* @param response
*/
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
//把数据添加到excel表格中
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
downLoadExcel(fileName, response, workbook);
}
/**
* excel 导出
*
* @param list 数据列表
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @param response
* @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
*/
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
//把数据添加到excel表格中
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
/**
* excel 导出
*
* @param list 数据列表
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
* @param response
*/
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/**
* excel 导出
*
* @param list 数据列表
* @param title 表格内数据标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
}
/**
* excel 导出
*
* @param list 数据列表
* @param title 表格内数据标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @param isCreateHeader 是否创建表头
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/**
* excel下载
*
* @param fileName 下载时的文件名称
* @param response
* @param workbook excel数据
*/
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param file excel文件
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
return importExcel(file, 1, 1, pojoClass);
}
/**
* excel 导入
*
* @param filePath excel文件路径
* @param titleRows 表格内数据标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setNeedSave(true);
params.setSaveUrl("/excel/");
try {
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("模板不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param file 上传的文件
* @param titleRows 表格内数据标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (file == null) {
return null;
}
try {
return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param inputStream 文件输入流
* @param titleRows 表格内数据标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setSaveUrl("/excel/");
params.setNeedSave(true);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel文件不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
}
public class EasypoiUtil {
public EasypoiUtil() {
}
public static void templateExport(TemplateExportParams templateExcel, Map<String, Object> dataMap, String fileName, HttpServletResponse response) throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(templateExcel, dataMap);
if (workbook != null) {
downLoadExcel(fileName, response, workbook);
}
}
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
}
private static String filename(HttpServletRequest request, String filename) throws Exception {
String userAgent = request.getHeader("User-Agent");
if (!userAgent.contains("MSIE") && !userAgent.contains("Trident")) {
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
} else {
filename = URLEncoder.encode(filename, "UTF-8");
}
return filename;
}
}
@Builder
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("im_users")
@NoArgsConstructor
@AllArgsConstructor
public class ImUsersPO extends Model<ImUsersPO> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 头像地址
*/
@TableField("avatar_url")
private String avatarUrl;
/**
* 家庭住址
*/
@TableField("family_address")
private String familyAddress;
/**
* 昵称
*/
@TableField("nickname")
@Excel(name = "姓名")
private String nickname;
/**
* 密码
*/
@TableField("password")
private String password;
/**
* 性别 1男 2女
*/
@TableField("u_sex")
@Excel(name = "性别",replace = {"男_1", "女_2"})
// @Pattern(regexp = "[12]", message = "性别错误")
private String usex;
@TableField("update_time")
private LocalDateTime updateTime;
/**
* 用户名
*/
@TableField("username")
private String username;
/**
* 手机号
*/
@TableField("phone_number")
@Excel(name = "联系方式")
private String phoneNumber;
/**
* 职位
*/
@TableField("position")
@Excel(name = "职务")
private String position;
/**
* 状态 是否可用 0可用 1不可用
*/
@TableField("status")
private Long status;
@Override
protected Serializable pkVal() {
return this.id;
}
}
作者:天天在家
链接:http://www.javaheidong.com/blog/article/114419/59046add23844858d8ff/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!