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

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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
easypoi是一个用于Excel和Word文档操作的Java库。它提供了简单易用的API,可以通过模板导出Excel文件。下面是使用easypoi进行模板导出的示例代码: 1. 导入easypoi的maven坐标: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.2.0</version> </dependency> ``` 2. 在Spring Boot的配置文件(bootstrap.yml或application.yml)中配置模板的URL: ```yaml easypoi: template: 'http://www.xxx.cn/statics/template/port.xlsx' ``` 3. 使用easypoi进行模板导出: ```java import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.TemplateExportParams; import org.apache.poi.ss.usermodel.Workbook; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; public class TemplateExportDemo { public static void main(String[] args) throws IOException { // 模板文件的URL String templateUrl = "http://www.xxx.cn/statics/template/port.xlsx"; // 下载模板文件 URL url = new URL(templateUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); // 加载模板文件 Workbook workbook = ExcelExportUtil.importExcel(inputStream); // 创建模板参数 TemplateExportParams params = new TemplateExportParams(); params.setSheetNum(0); // 指定导出的Sheet页 // 创建数据模型 Map<String, Object> dataModel = new HashMap<>(); dataModel.put("name", "John"); dataModel.put("age", 25); // 导出Excel文件 FileOutputStream outputStream = new FileOutputStream("output.xlsx"); ExcelExportUtil.exportExcel(params, dataModel, workbook.getSheetAt(params.getSheetNum()), outputStream); // 关闭流 outputStream.close(); inputStream.close(); } } ``` 这段代码会从指定的URL下载模板文件,然后根据模板和数据模型生成新的Excel文件。你可以根据自己的需求修改模板文件和数据模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值