SpringBoot implements Excel file upload and download analysis with easypoi

pom

In addition to the necessary scene starter (starter) of the springboot project, the pom also needs to add the following dependencies, esaypoi.
Pay attention to the version of easypoi, the 3.2.0 blogger used before, always reported an error when starting, and rebuilt a project and replaced it with a lower version to run successfully.

		<dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.0.1</version>
        </dependency>

Controller

	@GetMapping("/export")
    public void export(HttpServletResponse response){
    
    
        //模拟从数据库获取需要导出的数据
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person("柱间","1",new Date());
        Person person2 = new Person("小南","2", new Date());
        Person person3 = new Person("鼬","1", new Date());
        Person person4 = new Person("萨斯给","1",new Date());
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);

        //导出操作
        ExcelUtil.exportExcel(personList,"报名表","忍者",Person.class,"火影.xls",response);
    }

    @PostMapping("/importExcel")
    public void importExcel(MultipartFile file){
    
    
        String filePath = "D:\\火影.xls";
        //解析excel,
//      方式一:根据文件路径解析
//        List<Person> personList = ExcelUtil.importExcel(filePath,1,1,Person.class);

//      方式二:也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
        List<Person> personList = ExcelUtil.importExcel(file, 1, 1, Person.class);
        System.out.println("导入数据一共【"+personList.size()+"】行");
        //TODO 保存数据库
        System.out.println(personList);
    }

bean

	public class Person {
    
    

    @Excel(name = "姓名", orderNum = "0")
    private String name;

    @Excel(name = "性别", replace = {
    
    "男_1", "女_2"}, orderNum = "1")
    private String sex;

    @Excel(name = "生日", exportFormat = "yyyy-MM-dd", orderNum = "2")
    private Date birthday;

    public Person() {
    
    
    }
	
	getter setter略...

Tools

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

public class ExcelUtil {
    
    
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response){
    
    
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
    
    
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
    
    
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
    
    
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
    
    
        try {
    
    
            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());
        } catch (IOException e) {
    
    
            throw new RuntimeException(e.getMessage());
        }
    }
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
    
    
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
    
    
        if (StringUtils.isBlank(filePath)){
    
    
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
    
    
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
    
    
            throw new RuntimeException("模板不能为空");
        } catch (Exception e) {
    
    
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
    
    
        if (file == null){
    
    
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
    
    
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
    
    
            throw new RuntimeException("excel文件不能为空");
        } catch (Exception e) {
    
    
            throw new RuntimeException(e.getMessage());
        }
        return list;
    }
}

front-end code

        <div id="center">
            <form method="post" action="/importExcel" enctype="multipart/form-data">
                上传Excel: <input type="file" name="file"/>
                <br />
                <button>上传</button>
            </form>
            <br />
            <a href="/export">下载</a>
        </div>

test

download

insert image description here

upload

insert image description here

console print information

insert image description here

Summarize

By using easypoi, the uploading, downloading and parsing operations of Excel files are easily realized. The above code is just a simple demo. In specific business scenarios, some security verification work needs to be added, and the uploaded files need to be parsed according to business requirements. The data is then saved to the database.

Guess you like

Origin blog.csdn.net/qq_41570752/article/details/113241423