引言
项目中需要Excel文件的导入与导出Excel并下载,例如,导入员工信息,导出员工信息,手动输入比较繁琐,所以本篇博文教大家如何在Java中导入Excel文件与导出Excel文件
技术栈
Excel工具:EasyExcel
选用框架:Spring、Spring MVC、MyBatis(SSM)
项目构建管理工具:Maven
需求:
1.要求利用excel工具实现员工信息的导入与导出
2.导出要求为输出到指定位置并下载
3.导入文件导入后,存入数据库,并显示在页面
4.导出文件,点击导出后写入指定地址,并下载该文件
效果图
项目结构
核心源码
导入阿里巴巴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("全部解析完成");
}
public static List<Employee> getStudentList() {
return employeeList;
}
}
EasyExcel导入文件
Test测试类实现文件导入并存入数据库
@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类:
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;
}
EasyExcel导出文件
Test测试类导出文件到指定文件
@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("写入完成!");
}
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();
}
}
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();
}
以上就是Java+EasyExcel实现文件的导入导出的详细内容,更多关于Java EasyExcel文件的导入导出的资料请关注编程网其它相关文章!