SpringBoot implementa el análisis de carga y descarga de archivos de Excel con easypoi

pompón

Además del iniciador de escena necesario (iniciador) del proyecto springboot, el pom también debe agregar las siguientes dependencias, esaypoi.
Preste atención a la versión de easypoi, el blogger 3.2.0 que se usaba antes, siempre informaba de un error al iniciar, y reconstruía un proyecto y lo reemplazaba con una versión inferior para que se ejecutara correctamente.

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

Controlador

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

frijol

	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略...

Instrumentos

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

código de front-end

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

prueba

descargar

inserte la descripción de la imagen aquí

subir

inserte la descripción de la imagen aquí

información de impresión de la consola

inserte la descripción de la imagen aquí

Resumir

Al usar easypoi, las operaciones de carga, descarga y análisis de archivos de Excel se realizan fácilmente. El código anterior es solo una demostración simple. En escenarios comerciales específicos, es necesario agregar algún trabajo de verificación de seguridad y los archivos cargados deben analizarse de acuerdo con a los requisitos del negocio Los datos se guardan en la base de datos.

Supongo que te gusta

Origin blog.csdn.net/qq_41570752/article/details/113241423
Recomendado
Clasificación