[springboot+easypoi] One line of code to import and export excel

In development, we often encounter excel processing, import and export analysis, etc. Poi is more popular in java, but every time we have to write a large number of tool classes to do this, here we recommend a wheel made by others [ easypoi], the following introduces the use of "wheels".
pom introduction

no longer requires other jars
       <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId> cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <

        </dependency>
Write entity class Note that there must be an empty constructor

here , otherwise an error "object creation error" will be reported.
Regarding the annotation @Excel, there are other @ExcelCollection, @ExcelEntity, @ExcelIgnore, @ExcelTarget, etc. Here we use If not, you can go to the official to see more
Attribute type type description
name String null Column name
needMerge boolean fasle Vertically merge cells
orderNum String "0" Sorting of columns, support name_id
replace String[] {} Worth replacing the export is {a_id,b_id } Import in turn
savePath String "upload" Import file save path
type int 1 Export type 1 is text 2 is a picture, 3 is a function, 10 is a number The default is text
width double 10 column width
height double 10 column height, it is planned to be used uniformly later @ExcelTarget's height, this will be discarded, pay attention to
isStatistics boolean fasle Automatic statistics, add a line of statistics, and output all the data will engulf the exception, please pay attention to this
isHyperlink boolean false hyperlink, if you need to implement the interface return object
isImportField boolean true Check the field to see if this field is included in the imported Excel. If there is no indication that it is an incorrect Excel, the reading fails, and it supports name_id
exportFormat String "" The exported time format is determined by whether it is empty or not. Need to format the date
importFormat String "" The imported time format, which is empty to judge whether the date
format String "" time format needs to be formatted, which is equivalent to setting both exportFormat and importFormat
databaseFormat String "yyyyMMddHHmmss" Export time settings, if If the field is a Date type, you do not need to set the database. If it is a string type, you need to set the database format to convert the time format and output
numFormat String "" Number format, the parameter is Pattern, the object used is DecimalFormat
imageType int 1 Export type 1 Reading 2 from file is reading from the database. The default is the file. The same is true for
importing . For example, if the second column is merged based on the first column, {1} is fine. mergeVertical boolean fasle Vertically merge cells with the same content import cn.afterturn.easypoi.excel. annotation.Excel;





import java.util.Date;

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(String name, String sex, Date birthday) {
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}
导入导出公用方法

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 NormalException(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 NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new NormalException(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 NormalException("excel file cannot be empty");     }
        catch (Exception e) {
            throw new NormalException(e.getMessage()); }
        return
        list; You can export and import it. It seems that there is a lot of code, but in fact, it provides multiple import and export methods. Test   @RequestMapping("export")     public void export(HttpServletResponse response){







        //Simulate the data to be exported from the database
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person("Luffy","1",new Date());
        Person person2 = new Person( "Nami","2", DateUtils.addDate(new Date(),3));
        Person person3 = new Person("Sauron","1", DateUtils.addDate(new Date(),10));
        Person person4 = new Person("Little civet cat","1", DateUtils.addDate(new Date(),-10));
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        personList.add(person4);

        //Export operation
        FileUtil.exportExcel(personList,"Roster","Straw Hat Crew",Person.class,"One Piece. xls",response);
    }

    @RequestMapping("importExcel")
    public void importExcel(){
        String filePath = "F:\\One Piece.xls";
        //Parse excel,
        List<Person> personList = FileUtil.importExcel(filePath,1,1,Person.class);
        //Can also be used MultipartFile, use FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) to import
        System.out.println("Import data a total of ["+personList.size()+"] rows");

        // TODO save database
    }
Export results

Export results
Test

import Add a row to the export results, execute, and output the number of rows of imported data

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326175082&siteId=291194637