项目中需要Excel文件的导入与导出Excel并下载,例如,导入员工信息,导出员工信息,手动输入比较繁琐,所以本篇博文教大家如何在Java中导入Excel文件与导出Excel文件
技术栈
Excel工具:EasyExcel
选用框架:Spring、Spring MVC、MyBatis(SSM)
项目构建管理工具:Maven
需求:
导入阿里巴巴EasyExcel依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.6</version> </dependency>
这里采用EasyExcel,为什么不采用POI呢?
因为EasyExcel是对POI做的一个升级,POI相对于笨重,EasyExcel去除了一些POI比较繁琐的东西,所以EasyExcel比较轻量级,所以本文采用EasyExcel
EasyExcel是阿里巴巴的产品,POI是Apache基金会的开源产品,EasyExcel对POI做了一个升级
package com.wanshi.spring.entity; import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Employee { @ExcelIgnore private String noid; @ColumnWidth(20) @ExcelProperty("员工姓名") private String emp_name; @ColumnWidth(20) @ExcelProperty("员工年龄") private Integer emp_age; @ExcelIgnore private Integer emp_sex; //冗余字段 @ColumnWidth(20) @ExcelProperty("员工性别") private String str_emp_sex; @ColumnWidth(20) @ExcelProperty("员工工资") private Double emp_salary; @ColumnWidth(20) @ExcelProperty("员工住址") private String emp_address; @ColumnWidth(20) @ExcelProperty("员工岗位") private String emp_position; //分页相关,当前页与每页的数据条数 @ExcelIgnore private Integer pageNum; @ExcelIgnore private Integer pageSize; }
EmployeeListener类:
package com.wanshi.spring.listener; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.wanshi.spring.entity.Employee; import java.util.ArrayList; import java.util.List; public class EmployeeReadListener extends AnalysisEventListener<Employee> { //员工集合 private static List<Employee> employeeList = new ArrayList<>(); // 每读一样,会调用该invoke方法一次 @Override public void invoke(Employee data, AnalysisContext context) { employeeList.add(data); System.out.println("解析到一条数据:" + data); } // 全部读完之后,会调用该方法 @Override public void doAfterAllAnalysed(AnalysisContext context) { System.out.println("全部解析完成"); } /** * 返回读取到的员工集合 * @return */ public static List<Employee> getStudentList() { return employeeList; } }
@Test public void test1(){ ExcelReaderBuilder workBook = EasyExcel.read ("C:\\Users\\王会称\\Desktop\\员工.xlsx", Employee.class, new EmployeeReadListener()); // 封装工作表 ExcelReaderSheetBuilder sheet1 = workBook.sheet(); // 读取 sheet1.doRead(); //写入数据库 List<Employee> studentList = EmployeeReadListener.getStudentList(); for (Employee employee : studentList) { employee.setNoid(PbSecretUtils.uuid()); employeeMapper.insert(employee); } }
EmployeeController类:
@PostMapping("/import_employee_excel") public String importEmployeeExcel(MultipartFile emp_excel) { employeeService.importExcel(emp_excel); return "redirect:/employee/list"; }
EmployeeService类:
/** * 获取用户选择的文件并将文件存入指定位置再将数据存入数据库 * @param emp_excel * @return */ public Integer importExcel(MultipartFile emp_excel) { try { String fileName = FileUploadUtil.upload(emp_excel, ""); ExcelReaderBuilder workBook = EasyExcel.read (GlobalSet.upload_url+fileName, Employee.class, new EmployeeReadListener()); // 封装工作表 ExcelReaderSheetBuilder sheet1 = workBook.sheet(); // 读取 sheet1.doRead(); List<Employee> studentList = EmployeeReadListener.getStudentList(); for (Employee employee : studentList) { employee.setNoid(PbSecretUtils.uuid()); if ("男".equals(employee.getStr_emp_sex())) { employee.setEmp_sex(1); } else { employee.setEmp_sex(2); } employeeMapper.insert(employee); } } catch (IOException e) { e.printStackTrace(); } return 0; }
@Test public void test2() throws FileNotFoundException { List<Employee> employeeList = initData(); ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class); // sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字 workBook.sheet("测试数据表").doWrite(employeeList); System.out.println("写入完成!"); } /** * 生成测试数据 * @return */ public List<Employee> initData() { List<Employee> employeeList = new ArrayList<>(); for (int i = 1; i < 100; i++) { Employee employee = new Employee(); employee.setEmp_name("小王说:"+i); employee.setEmp_age(19); if (i % 10 == 0) { employee.setEmp_sex(1); } else { employee.setEmp_sex(2); } employee.setEmp_salary(19999.00+i); employee.setEmp_address("北京市朝阳区"+i); employee.setEmp_position("Java高级工程师"); employeeList.add(employee); } return employeeList; }
EmployeeController类
@GetMapping("/export_employee_excel") public void exportEmployeeExcel(HttpServletResponse response) { try { employeeService.exportEmployeeExcel(response); } catch (IOException e) { e.printStackTrace(); } }
EmployeeService类:
public void exportEmployeeExcel(HttpServletResponse response) throws IOException { List<Employee> kspwStudentSeatList = list(); try { ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class); // sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字 workBook.sheet("员工信息").doWrite(kspwStudentSeatList); downloadTempalate(response); System.out.println("写入完成!"); } catch (Exception e) { e.printStackTrace(); } } /** * 下载文件 * @param response * @throws IOException */ public static void downloadTempalate(HttpServletResponse response) throws IOException { // 告诉浏览器用什么软件可以打开此文件 response.setHeader("content-Type", "application/vnd.ms-excel"); // 下载文件的默认名称 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("员工信息.xlsx", "utf-8")); //4. 创建输入、输出流 FileInputStream input = new FileInputStream(GlobalSet.download_url); ServletOutputStream sos = response.getOutputStream(); //IO流获取文件的字节流,然后再响应给浏览器 byte[] arr = new byte[1024]; int res = 0; while((res = input.read(arr)) > 0){ //将读取的内容输出到输出流中 sos.write(arr, 0, res); } input.close(); sos.close(); }
至此,数据完美导入导出,该案例通俗易懂,详细一步步带入,通过本案例,可实现文件基本的导入导出,认真学习的你很耀眼,相信你的技术一定会有一个质的飞跃