JAVA ( EasyExcel 通过模板 导入、导出、下载模板)——亲测有用
生活随笔
收集整理的這篇文章主要介紹了
JAVA ( EasyExcel 通过模板 导入、导出、下载模板)——亲测有用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文參考:https://liuyanzhao.com/10060.html
先說兩個實體類對象。
我這里舉例 Student 和 StudentExcel
Student 就是你數據庫表的對象
StudentExcel 是你導入進來的Excel對應的字段 ,為啥寫他,用來校驗數據格式,判空處理
你要把你導入進來的對象 StudentExcel 轉換成 你業務對象 Student ,轉換方式我下面有工具類,大家可以參考去改一下。
如果你導入的參數有校驗,或者不能為null,可以加注解來校驗,日期校驗注解是我自己寫的注解,我一會下面會放大家直接copy就可以用。
目錄
- 1.模板copy到項目里
- 2.下載模板
- 3.導入
- 4.導出
- 5.工具類 FileUtil :
- 6.工具類 ValidatorUtils (導入的時候參數校驗)
- 7.校驗日期注解
1.模板copy到項目里
這個模板是你自己定義的寫好的直接扔到項目里就行,不要直接扔在resources目錄下,創一個文件夾(template)放進去。 看圖:
pom.xml添加依賴
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version>
</dependency>
**StudentExcel Excel對象
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.io.Serializable;/*** @author ext.libo15* @title: 導入員工花名冊* @date 2022/3/2 13:49*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@HeadRowHeight(value = 40)
public class StudentExcel implements Serializable {private static final long serialVersionUID = -5144055068797033748L;/*** 姓名*/@ExcelProperty(value = "姓名", index = 0)@ColumnWidth(value = 20)@NotBlank(message="姓名不能為空")private String name;/*** 性別 1:男 :2女*/@ExcelProperty(value = "性別\r1:男 :2女", index = 1)@ColumnWidth(value = 20)@NotBlank(message="性別不能為空")private String gender;/*** 出生日期*/@ExcelProperty(value = "出生日期", index = 2)@ColumnWidth(value = 20)@NotBlank(message="出生日期不能為空")@DateTimeStr(format ="yyyy-MM-dd", message = "出生日期格式錯誤,正確格式為:yyyy-MM-dd")private String birthday;/*** 年齡*/@ExcelProperty(value = "年齡", index = 3)@ColumnWidth(value = 20)@NotBlank(message="年齡不能為空")private String age;/*** 身份證號碼*/@ExcelProperty(value = "身份證號碼", index = 4)@ColumnWidth(value = 20)@NotBlank(message="身份證號碼不能為空")@Pattern(regexp = "^\\d{15}$|^\\d{17}[0-9Xx]$",message = "身份證格式不正確!")//長度18,0-9private String cardNo;/*** 聯系電話*/@ExcelProperty(value = "聯系電話", index = 5)@ColumnWidth(value = 20)@NotBlank(message="聯系電話不能為空")@Pattern(regexp = "^[1][3,4,5,7,8][0-9]{9}$",message = "聯系電話格式不正確!")//長度11private String telephone;/*** 是否已婚 1:是 2:否*/@ExcelProperty(value = "是否已婚", index = 6)@ColumnWidth(value = 20)@NotBlank(message="是否已婚不能為空")private String marryStatus;/*** 銀行卡號*/@ExcelProperty(value = "銀行卡號", index = 8)@ColumnWidth(value = 20)@NotBlank(message="銀行卡號不能為空")@Pattern(regexp = "^([1-9]{1})(\\d{14}|\\d{18})$",message = "銀行卡號格式不正確!")//長度11private String bankCardNo;
Student 對象(你的業務對象,就是數據庫對應的對象)
public class Student implements Serializable {private static final long serialVersionUID = -5144055068797033748L;/*** 姓名*/private String name;/*** 性別 1:男 :2女*/private int gender;/*** 出生日期*/private Date birthday;/*** 年齡*/private int age;/*** 身份證號碼*/private String cardNo;/*** 聯系電話*/private String telephone;/*** 是否已婚 1:是 2:否*/private int marryStatus;/*** 銀行卡號*/private String bankCardNo;/*** 時間*/private Date dimissionDate;
Controller 代碼:
/*** 導入*/@RequestMapping(value="/import")public void importExcel(HttpServletRequest request, HttpServletResponse response,@RequestBody MultipartFile file) throws Exception {staffManageService.importExcel(file);}/*** 導出*/@RequestMapping(value="/export",method = RequestMethod.POST)public void batchExport(HttpServletResponse response) throws ParseException {staffManageService.export(response,staffRosterVo);}/*** 下載模板** @param* @return* @throws Exception* @author ext.libo15* @date 2022/2/28 17:23*/@GetMapping(value="/download")public void download(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {FileUtil.downloadExcel(request,response);}
}
2.下載模板
這里其實 Controller + FileUtil 工具類,下載模板的操作已經做好了。工具類我放最下面了
**
3.導入
**
/*** 導入* @param file*/@Overridepublic void importExcel(MultipartFile file) throws Exception {List<Student> ExcelList = null;String validate = "";//校驗文件大小 100Mboolean size = FileUtil.checkFileSize(file.getSize(), 100, ResponseResultEnum.FILE_UNIT.getMsg());if(size == false){//文件過大啦,只能100M}//excel讀取數據staffExcelList = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(StaffDataExcel.class).sheet().doReadSync();if (ExcelList.size() > 1000) {//最多導入1000條哦}// excel數據校驗validate = ValidatorUtils.beanValidate(ExcelList);if(!validate.equals("success")){//參數異常提示 如:姓名不能為空哦~}//把Excel數據轉換成你對應的對象集合ListList<Student> studentList = ExcelUtil.excelListConvertList(ExcelList);//拿到數據后就可以 入庫操作啦 -----我自己的入庫就不給你們寫了StudentService.importExcel(studentList );}
4.導出
/*** 導出* @param response* @param staffRosterVo* @return* @throws ParseException*/@Overridepublic void export(HttpServletResponse response) throws ParseException {String fileName = "導出的文件名稱";String sheetName = "導出的 sheetName ";List<Student> list = studentService.findList();List<StaffDataExportExcel> studentExcelList = ExcelUtil.listConvertexcelList(list );try {ExcelUtil.writeExcel(response, studentExcelList , fileName, sheetName, StaffDataExportExcel.class);} catch (Exception e) {e.printStackTrace();}}
5.工具類 FileUtil :
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;public class FileUtil {/*** 判斷文件大小** @param len* 文件長度* @param size* 限制大小* @param unit* 限制單位(B,K,M,G)* @return*/public static boolean checkFileSize(Long len, int size, String unit) {
// long len = file.length();double fileSize = 0;if ("B".equals(unit.toUpperCase())) {fileSize = (double) len;} else if ("K".equals(unit.toUpperCase())) {fileSize = (double) len / 1024;} else if ("M".equals(unit.toUpperCase())) {fileSize = (double) len / 1048576;} else if ("G".equals(unit.toUpperCase())) {fileSize = (double) len / 1073741824;}if (fileSize > size) {return false;}return true;}public static void downLoadFile(String filePath, String fileName, HttpServletResponse response) {try (InputStream inStream = new FileInputStream(filePath);OutputStream os = response.getOutputStream()) {response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(fileName, "UTF-8"));response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");byte[] buff = new byte[100];int len;while ((len = inStream.read(buff)) > 0) {os.write(buff, 0, len);}os.flush();} catch (Exception e) {throw new BusinessException(ResponseResultEnum.FILE_IMPMOT_SIZE.getCode(), ResponseResultEnum.FILE_IMPMOT_SIZE.getMsg());}}//下載模板public static void downloadExcel(HttpServletRequest request, HttpServletResponse response){//方法一:直接下載路徑下的文件模板(這種方式貌似在SpringCloud和Springboot中,打包成JAR包時,無法讀取到指定路徑下面的文件,不知道記錯沒,你們可以自己嘗試下!!!)try {//文件名稱String fileName = "importStaffRoster.xlsx";//設置要下載的文件的名稱response.setHeader("Content-disposition", "attachment;fileName=" + fileName);//通知客服文件的MIME類型response.setContentType("application/vnd.ms-excel;charset=UTF-8");//獲取文件的路徑String filePath = FileUtil.class.getResource("/template/" + fileName).getPath();FileInputStream input = new FileInputStream(filePath);OutputStream out = response.getOutputStream();byte[] b = new byte[2048];int len;while ((len = input.read(b)) != -1) {out.write(b, 0, len);}//修正 Excel在“xxx.xlsx”中發現不可讀取的內容。是否恢復此工作薄的內容?如果信任此工作簿的來源,請點擊"是"response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));input.close();} catch (Exception ex) {ex.printStackTrace();}}}
6.工具類 ValidatorUtils (導入的時候參數校驗)
import cn.hutool.core.lang.Assert;
import org.apache.commons.lang3.ObjectUtils;import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;public class ValidatorUtils {private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();public static String beanValidate(@Valid Object obj) throws IllegalArgumentException {if (obj instanceof Collection) {ValidCollection<Object> validCollection = new ValidCollection<>();validCollection.setList((Collection) obj);return validate(validCollection);} else {return validate(obj);}}public static String validate(@Valid Object obj) {try {Map<String, String> validatedMsg = new HashMap<>();Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);String validate = "";String message = "";for (ConstraintViolation<Object> c : constraintViolations) {validate = c.getPropertyPath().toString();validate = validate.substring(5,6);int unm = Integer.valueOf(validate) +1;validatedMsg.put( "表格第"+unm+"條 ", c.getMessage());}Assert.isTrue(ObjectUtils.isEmpty(constraintViolations), validatedMsg.toString());} catch (IllegalArgumentException e) {e.printStackTrace();return e.getMessage();}return "success";}private static class ValidCollection<T> {@Validprivate Collection<T> list;public Collection<T> getList() {return list;}public void setList(Collection<T> list) {this.list = list;}}
}
工具類
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;public class ExcelUtil {/*** 導出* @param response* @param data* @param fileName* @param sheetName* @param clazz* @throws Exception*/public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class clazz) throws Exception {//表頭樣式WriteCellStyle headWriteCellStyle = new WriteCellStyle();//設置表頭居中對齊headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//內容樣式WriteCellStyle contentWriteCellStyle = new WriteCellStyle();//設置內容靠左對齊contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);EasyExcel.write(getOutputStream(fileName, response), clazz).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy).doWrite(data);}private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {fileName = URLEncoder.encode(fileName, "UTF-8");response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf8");response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");return response.getOutputStream();}/** Excel轉換實體類對象*/public static List<Student> excelListConvertList(List<StudentExcel> studentExcelList) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");List<Student> list = new ArrayList<>();for (StudentExcel s : studentExcelList) {Student student = Student.builder().name(staffDataExcel.getname()).age(staffDataExcel.age()).city(staffDataExcel.getCity()).sex(staffDataExcel.getsex().equals("男")?1:2).birthday(sdf.parse(staffDataExcel.getBirthday())).build();list.add(student);}return list ;}/** 導出的List集合 轉換 Excel*/public static List<StudentExportExcel> listConvertexcelList(List<Student> student) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");List<StudentExcel> list= new ArrayList<>();for (Student s : student) {StudentExcel excel = StudentExcel.builder().name(staffDataExcel.getname()).age(staffDataExcel.age()).city(staffDataExcel.getCity()).sex(staffDataExcel.getsex().equals("男")?1:2).birthday(sdf.parse(staffDataExcel.getBirthday())).build();.build();list.add(excel);}return list;}}
7.校驗日期注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CheckDateTimeCaseValidator.class)
public @interface DateTimeStr {String message() default "{javax.validation.constraints.DateTimeStr.message}";String format() default "yyyy-MM-dd";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};
}
總結
以上是生活随笔為你收集整理的JAVA ( EasyExcel 通过模板 导入、导出、下载模板)——亲测有用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通达oa 2017 php,【通达OA】
- 下一篇: 升级ios13后怎么删除其他系统数据