[Java+EasyExcel implements file import and export, import and export are so simple]

Java+EasyExcel implements file import and export

introduction

The project needs to import and export Excel files and download them. For example, importing employee information, exporting employee information, and manual input are cumbersome, so this blog post teaches you how to import and export Excel files in Java.

technology stack

Excel Tools:EasyExcel

Selected framework: Spring, Spring MVC, MyBatis (SSM)

Project build management tool: Maven

need:

  1. It is required to use excel tool to realize the import and export of employee information
  2. The export requirement is to output to the specified location and download
  3. After the import file is imported, it is stored in the database and displayed on the page
  4. Export the file, click Export and write to the specified address, and download the file

renderings

insert image description here

Project structure

insert image description here

core source code

Import Alibaba EasyExcel dependencies

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.1.6</version>
</dependency>

EasyExcel is used here, why not POI?

Because EasyExcel is an upgrade to POI, POI is relatively bulky, and EasyExcel removes some cumbersome POI things, so EasyExcel is relatively lightweight, so this article uses EasyExcel

EasyExcel is a product of Alibaba, POI is an open source product of the Apache Foundation, and EasyExcel has made an upgrade to POI

core entity class

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;
}

core listener class

EmployeeListener class:

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;
    }
}

EasyExcel import file

Test test class implementation file is imported and stored in the database

@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);
    }
}

Click on the page to import the file and save it into the database

EmployeeController class:

@PostMapping("/import_employee_excel")
public String importEmployeeExcel(MultipartFile emp_excel) {
    
    
    employeeService.importExcel(emp_excel);
    return "redirect:/employee/list";
}

EmployeeService class:

/**
     * 获取用户选择的文件并将文件存入指定位置再将数据存入数据库
     * @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;
}

EasyExcel export file

Test test class export file to specified file

@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;
}

After exporting to the specified file through the page and downloading the file

EmployeeController class

@GetMapping("/export_employee_excel")
    public void exportEmployeeExcel(HttpServletResponse response) {
    
    
        try {
    
    
            employeeService.exportEmployeeExcel(response);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

EmployeeService class:

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();
    }

Epilogue

So far, the data has been imported and exported perfectly. The case is easy to understand, and the details are introduced step by step. Through this case, the basic import and export of files can be realized. You are very dazzling if you study hard. I believe your technology will definitely have a qualitative leap. Well, this week's technology sharing ends here

I've seen it all here, are you sure you don't like it?

If you encounter technical difficulties in this project, you can leave a message in the comment area below or privately message me. It is better to teach a man to fish than to teach him how to fish.

Baidu network disk address: link: https://pan.baidu.com/s/1vmrL7vl5Hlq-SqjdndOKyQ Extraction code: me3n

If you think the blogger's writing is good, you might as well give a one-click three-link, click the small fist below to one-click three-link.

thank you for your support!

Guess you like

Origin blog.csdn.net/weixin_45526437/article/details/122021373