easypoi导入导出下载模板

基于easypoi实现导入导出,下载模板,快来看看吧,超简单

1. 依赖

<dependency>
   <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-spring-boot-starter</artifactId>
     <version>4.4.0</version>
</dependency>

//  如果是根据本地模板操作需要加上
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
     <version>2.6</version>
     <artifactId>maven-resources-plugin</artifactId>
     <configuration>
         <encoding>UTF-8</encoding>
         <nonFilteredFileExtensions>
             <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
         </nonFilteredFileExtensions>
     </configuration>
</plugin>

2. 实体类

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

import java.util.Date;

@Data
public class AgentGuaranteeExportDTO {

    @Excel(name = "代理人名称")
    private String agentName;

    @Excel(name = "票证前缀")
    private String carrier;

    @Excel(name = "协议编号")
    private String serial;

    @Excel(name = "可用押金")
    private Double paidMoney;

    @Excel(name = "汇款银行")
    private String moneyBank;

    @Excel(name = "缴纳时间",exportFormat = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
}

注意:@Excel:对应导入或者导出字段,默认按照顺序对应excel文件中的字段,也可以使用orderNum属性来排序,但是只能是123456,不能是123465,一定要按顺序来

3.ExcelUtils 工具类

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.TemplateExportParams;
import com.itran.agent.boot.util.excel.ExcelErrorResult;
import com.itran.agent.boot.util.excel.ExcelErrorResults;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.springframework.web.multipart.MultipartFile;

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

public class ExcelUtils {

    /**
     *
     * @param results 校错信息集合
     * @param workbook 表格对象
     * @param msgCol 消息行
     * @param header 从哪行开始
     * @param index
     * @return
     */
    public static Workbook exportWrong(List<ExcelErrorResults> results, Workbook workbook, int msgCol, int index, int header){
        CellStyle style = workbook.createCellStyle();
        CellStyle redFontStyle = workbook.createCellStyle();

        Font font = workbook.createFont();
        font.setColor(IndexedColors.RED.getIndex());

        redFontStyle.setFont(font);

        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFont(font);


        Sheet sheet = workbook.getSheetAt(index);
        Drawing<?> paint = sheet.createDrawingPatriarch();
        for(ExcelErrorResults result : results){
            for(ExcelErrorResult cellResult:result.getList()){
                Row row = sheet.getRow(cellResult.getRow()+header);
                if(row == null){
                    row = sheet.createRow(cellResult.getRow());
                }
                Cell cell = row.getCell(cellResult.getCol());
                if(cell == null){
                    cell = row.createCell(cellResult.getCol());
                }
                if(StringUtils.isNotBlank(cellResult.getMsg())){
                    Comment comment = null;
                    try {
                        comment = paint.createCellComment( new XSSFClientAnchor(0, 0, 0, 0, (short)3, 3, (short)5, 6));
                        comment.setString(new XSSFRichTextString(cellResult.getMsg()));
                    } catch (Exception e) {
                        comment = paint.createCellComment(new HSSFClientAnchor(0, 0, 0, 0, (short)3, 3, (short)5, 6));
                        comment.setString(new HSSFRichTextString(cellResult.getMsg()));
                    }
                    cell.setCellComment(comment);
                }
                style.setDataFormat(cell.getCellStyle().getDataFormat());
                cell.setCellStyle(style);
            }
            Row row = sheet.getRow(result.getRowNum());
            if(row == null) row = sheet.createRow(result.getRowNum());
            Cell msg = row.getCell(msgCol);
            if(msg == null) msg = row.createCell(msgCol);
            msg.setCellStyle(redFontStyle);
            msg.setCellValue(result.getMsg());
        }

        return workbook;
    }


    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        return importExcel(file,titleRows,headerRows,0,pojoClass);
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,Integer startIndex, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setStartSheetIndex(startIndex);
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);

        }catch (NoSuchElementException e){
            throw new NullPointerException("excel文件不能为空");
        } catch (Exception e) {
            throw new NullPointerException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(File file, Integer titleRows, Integer headerRows, Integer startIndex, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setStartSheetIndex(startIndex);
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new FileInputStream(file), pojoClass, params);

        }catch (NoSuchElementException e){
            throw new NullPointerException("excel文件不能为空");
        } catch (Exception e) {
            throw new NullPointerException(e.getMessage());
        }
        return list;
    }

    //模板导出 templateUrl文件地址map数据
    public static void exportExcel(String templateUrl,Map map, HttpServletResponse response) throws IOException {
        TemplateExportParams params = new TemplateExportParams(templateUrl);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        ExcelUtils.export(response, workbook, StringUtils.substringAfterLast(templateUrl, "/"));
    }

    // Excel 导出 通过浏览器下载的形式
    public static void export(HttpServletResponse response, Workbook workbook, String fileName) throws IOException {
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
        workbook.write(bufferedOutPut);
        bufferedOutPut.flush();
        bufferedOutPut.close();
    }


    /**
     * excel 导出
     *
     * @param list           数据列表
     * @param title          表格内数据标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       导出时的excel名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    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);
        // 设置样式可以不要
        // exportParams.setStyle(ExcelStyleUtil.class);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    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.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new AgentException(e.getMessage());
        }
    }
}

相关联的类

import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class ExcelErrorResult {
    @ApiModelProperty(name = "第几行")
    private int col;

    @ApiModelProperty(name = "第几列")
    private int row;

    @ApiModelProperty(name = "每个单元格内的标注")
    private String msg;

    @ApiModelProperty(name = "属性名称")
    private String property;
}

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

//错误集合,代表excel一行中的错误总计,只允许插入行号相同的元素,否则抛出异常
@NoArgsConstructor
@Data
public class ExcelErrorResults {
    private int rowNum;//限定行号
    private List<ExcelErrorResult> list = new ArrayList<>();
    private String msg;//标注在行后的信息

    public boolean isEmpty(){
        return list.isEmpty();
    }

    public ExcelErrorResults add(int rowNum,int colNum){
        ExcelErrorResult result = ExcelErrorResult.builder().row(rowNum).col(colNum).build();
        add(result);
        return this;
    }

    public void add(ExcelErrorResult result){
        if(result == null)return;
        if (list.isEmpty()){
            this.rowNum = result.getRow();
        }
        if(this.rowNum != result.getRow()){
            throw new RuntimeException("只允许加入行号相同的元素!");
        }
        list.add(result);
    }
    public void add(Collection<ExcelErrorResult> collect){
        List<Integer> rows = collect.stream().map(ExcelErrorResult::getCol).collect(Collectors.toList());
        if(rows.stream().distinct().collect(Collectors.toList()).size()!=1){
            throw new RuntimeException("只允许加入行号相同的元素!");
        }
        list.addAll(collect);
    }

}

4.导入

导入视乎就很简单了

 @PostMapping("/import")
 public Result importGuarantee(MultipartFile file) {
 List<AgentGuaranteeExportDTO > list= ExcelUtils.importExcel(file, 1, 1, AgentGuaranteeExportDTO .class);
}

5.导出

 public void export(PriceRateSearchParam param, HttpServletResponse response) {
        List<PriceRate> list = priceRateMapper.findList(param);
        List<PriceRateExportDTO> priceRateDTOS = CopyUtils.listCopy(PriceRateExportDTO.class, list);
        String templateUrl = "excel/policy/汇率数据导入模板.xlsx";
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",priceRateDTOS);
        try {
            ExcelUtils.exportExcel(templateUrl,map,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

我这是根据指定模板导出,所以还要在pom文件添加一个插件

模板格式

语法:{{$fe:list t.agentName t.carrier}} 其中list,t,都是可以顺便取名的
在这里插入图片描述
模版使用语法如下:
下面列举下EasyPoi支持的指令以及作用,最主要的就是各种fe的用法

  • 空格分割
  • 三目运算 {{test ? obj:obj2}}
  • n: 表示 这个cell是数值类型 {{n:}}
  • le: 代表长度{{le:()}} 在if/else 运用{{le:() > 8 ? obj1 : obj2}}
  • fd: 格式化时间 {{fd:(obj;yyyy-MM-dd)}}
  • fn: 格式化数字 {{fn:(obj;###.00)}}
  • fe: 遍历数据,创建row
  • !fe: 遍历数据不创建row
  • $fe: 下移插入,把当前行,下面的行全部下移.size()行,然后插入
  • #fe: 横向遍历
  • v_fe: 横向遍历值
  • !if: 删除当前列 {{!if:(test)}}
  • 单引号表示常量值 ‘’ 比如’1’ 那么输出的就是 1
  • &NULL& 空格
  • ]] 换行符 多行遍历导出
    sum: 统计数据

6.下载模板

这个是最简单的,没错就是这样,很简单

@GetMapping("/export/template")
    public void template(HttpServletResponse response) {
        HashMap<String, Object> map = new HashMap<>();
        String templateUrl = "excel/policy/template/模板.xlsx"; // 模板位置resource中
        try {
            ExcelUtils.exportExcel(templateUrl,map,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这样导入导出下载模板就完成了,是不是很简单,我这都是根据模板来操作的,后面可以试试自定义表格,有兴趣可以试一试。

你可能感兴趣的:(easypoi,excel,java,开发语言,spring,boot)