JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现(实例)

JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现(实例)

参考链接 :https://www.yuque.com/easyexcel/doc/easyexcel

第一步在pom.xml中导入EasyExcel依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.2</version>
</dependency>

第二步实体类中添加注解

@Data
public class ProductOutboundDetail implements Serializable {
	private static final long serialVersionUID = 1L;
	@ExcelProperty("序号")
	private Integer num;
	@ExcelProperty("品名")
	private String productName;
	@ExcelProperty("规格")
	private String productGrades;
	@ExcelProperty("单位")
	private String drugUnit;
	@ExcelProperty("生产批次")
	private String batchNum;
	@DateTimeFormat("yyyy-MM-dd")
	private Date bestBefore;
	@ExcelProperty("单价(元)")
	private BigDecimal sellPrice;
	@ExcelProperty("数量")
	private Integer outboundNum;
	@ExcelProperty("金额(元)")
    private BigDecimal  outmoney;

第三步 制定导出excel模版

  • { } 表示表中主体部分的变量
  • { . } list集合数据 的时候要注意模板中{.} 多了个点 表示list

在web项目的webapp下新建一个文件夹template用来存放excel模版,导出的时候要引入这个模版。
JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现(实例)_第1张图片
excel模版制定为
id改为num
JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现(实例)_第2张图片
注意

  • 表格中品名、规格…字段名需要跟实体类中的名称保持一致
  • { } 变量名可以自己定义,也可以跟数据库保持一致
  • excel后缀名为.xlsx

第四步 Mapper.xml中写查询sql

JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现(实例)_第3张图片

 <select id="findExcelDataInMasterId" resultType="com.dyt.entity.ProductOutboundDetail">
        select product_name,product_grades,drug_unit,outbound_num,sell_price,
               outbound_num*sell_price as outmoney,batch_num,best_before
        from product_outbound_detail
        where master_id = #{master_id}
    </select>

第五步 dao层—impl层—interface接口—Controller层

第一步:List<ProductOutboundDetail> findExcelDataInMasterId (Integer masterId);
第二步:
/**
 * 导出excel数据
*/
@Override
public List<ProductOutboundDetail> findExcelDataInMasterId(Integer masterId) {
    List<ProductOutboundDetail> excelDataInMasterId = productOutboundDetailDao.findExcelDataInMasterId(masterId);
    return excelDataInMasterId;
}
第三步:
List<ProductOutboundDetail> findExcelDataInMasterId (Integer masterId);

BigDecimalUtil ChineseYuanUtil 在分类常用工具中可以找到

第四步:
 @ApiOperation(value = "导出出库数据")
 @ApiResponses(value = {
        @ApiResponse(code = 200, message = "操作成功,返回成功状态码,保存在data集合元素中"),
        @ApiResponse(code = 500, message = "内部错误,信息由msg字段返回")
    })
 @PostMapping("/EasyExcel")
 @ResponseBody
public String printEasyExcelTemplate(HttpServletRequest req, HttpServletResponse resp, Integer masterId,String name) throws Exception {
        //1.配置下载属性
        resp.setContentType("application/x-msdownload");
        resp.setCharacterEncoding("utf-8");
        //2.设置文件名
        String fileName ="大养堂出库表" + "-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xlsx";
        //3.查询获取数据列表
        List<ProductOutboundDetail> list = productOutboundDetailService.findExcelDataInMasterId(masterId);
        //为表格添加序号
        for(int i=0; i < list.size(); i++){
            int n= i+1;
            list.get(i).setNum(n);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id",masterId);
        map.put("isDel",false);
        ProductOutboundTable outTable = productOutboundTableService.findProductOutboundTableByxxx(map);
        //4.配置对象数据map
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("customerName",outTable.getCustomerName());
        map1.put("outboundDate",new SimpleDateFormat("yyyy-MM-dd").format(outTable.getOutboundDate()));
        map1.put("outboundMoney", BigDecimalUtil.formatToNumber(new BigDecimal(String.valueOf(outTable.getOutboundMoney()))));
        map1.put("outboundMoney1", ChineseYuanUtil.number2CNMontrayUnit(outTable.getOutboundMoney()));
        map1.put("name",name);
        //5.获取模板路径
        HttpSession session = req.getSession();
        String path = session.getServletContext().getRealPath("/")+"/template/outbound.xlsx";
        //6.获取ExcelWrite对象
        ExcelWriter writer = EasyExcel.write(fileName)
                .head(ProductOutboundDetail.class) //指定头
                .withTemplate(path) //加载模板
                .build(); //构造write对象
        //7.获取WriterSheet对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        //8.填充列表,自动的创建数据行
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        writer.fill(list, fillConfig, sheet);
        //9.填充对象数据
        writer.fill(map1,sheet);
        //10.释放资源,完成数据下载
        writer.finish();
        return "success";
    }

第六步 结果图如下

JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现(实例)_第4张图片

第七步 Controller层代码优化,封装到ExcelUtil工具类中

ExcelUtil工具

package com.dyt.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ExcelUtil {
    public static <T> void writeExcel(HttpServletRequest req, HttpServletResponse resp, String name,String path,
                                      List<T> list,Map<String, Object> map,Class model)throws Exception{
        //1.配置下载属性
        resp.setContentType("application/x-msdownload");
        resp.setCharacterEncoding("utf-8");
        //2.设置文件名
        String fileName = name + "-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xlsx";
        //3.获取ExcelWrite对象
        ExcelWriter writer = EasyExcel.write(fileName)
                .head(model) //指定头
                .withTemplate(path) //加载模板
                .build(); //构造write对象
        //4.获取WriterSheet对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        //5.填充列表,自动的创建数据行
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        writer.fill(list, fillConfig, sheet);
        //6.填充对象数据
        writer.fill(map,sheet);
        //7.释放资源,完成数据下载
        writer.finish();
    }
}

Controller层

@ApiOperation(value = "导出出库数据")
@ApiResponses(value = {
           @ApiResponse(code = 200, message = "操作成功,返回成功状态码,保存在data集合元素中"),
           @ApiResponse(code = 500, message = "内部错误,信息由msg字段返回")
    })
 @PostMapping("/EasyExcel")
 @ResponseBody
public String printEasyExcelTemplate(HttpServletRequest req, HttpServletResponse resp, Integer masterId,String name) throws Exception {
        //1.设置表名称
        String fileName ="大养堂出库表";
        HttpSession session = req.getSession();
        //2.获取模版地址
        String path = session.getServletContext().getRealPath("/")+"/template/outbound.xlsx";
        //3.查询获取数据列表                       方法
        List<ProductOutboundDetail> list = productOutboundDetailService.findExcelDataInMasterId(masterId);
         //为表格添加序号
        for(int i=0; i < list.size(); i++){
            int n= i+1;
            list.get(i).setNum(n);
        }
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id",masterId);
        map2.put("isDel",false);                
                                              // 方法
        ProductOutboundTable outTable = productOutboundTableService.findProductOutboundTableByxxx(map2);
        //4.配置对象数据map
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("customerName",outTable.getCustomerName());
        map3.put("outboundDate",new SimpleDateFormat("yyyy-MM-dd").format(outTable.getOutboundDate()));
        map3.put("outboundMoney", BigDecimalUtil.formatToNumber(new BigDecimal(String.valueOf(outTable.getOutboundMoney()))));
        map3.put("outboundMoney1", ChineseYuanUtil.number2CNMontrayUnit(outTable.getOutboundMoney()));
        map3.put("name",name);
        ExcelUtil.writeExcel(req,resp,fileName,path,list,map3,ProductOutboundDetail.class);
        return "success";
    }

最终优化版

ExcelUtil工具

public class ExcelUtil extends HttpServlet {

    public static <T> void writeExcel(HttpServletRequest req, HttpServletResponse resp, String filePath, String path,
                                      List<T> list, Map<String, Object> map, Class model)throws Exception{
        //6.获取ExcelWrite对象
        ExcelWriter writer = EasyExcel.write(filePath)
                .head(model) //指定头
                .withTemplate(path) //加载模板
                .build(); //构造write对象
        //7.获取WriterSheet对象
        WriteSheet sheet = EasyExcel.writerSheet().build();
        //8.填充列表,自动的创建数据行
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        writer.fill(list, fillConfig, sheet);
        //9.填充对象数据
        writer.fill(map,sheet);
        //downLoadFile(substring, resp);
        //10.释放资源,完成数据下载
        writer.finish();
    }
}

Controller层

    @ApiOperation(value = "导出出库数据")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "操作成功,返回成功状态码,保存在data集合元素中"),
            @ApiResponse(code = 500, message = "内部错误,信息由msg字段返回")
    })
    @PostMapping(value ="/EasyExcel")
    @ResponseBody
    public String printEasyExcelTemplate(HttpServletRequest req, HttpServletResponse resp, Integer masterId,String name) throws Exception {
        //1.设置表名称
        HttpSession session = req.getSession();
        String fileName = session.getServletContext().getRealPath("/") + "export" + File.separator
                + "大养堂出库表" + "-"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())
                + "-" + (int)((Math.random()*9+1)*1000) + ".xlsx" ;
        //2.获取模版地址
        //session.getServletContext().getRealPath("/");
        String path =session.getServletContext().getRealPath("/") + "template" + File.separator + "outbound.xlsx";
        //3.查询获取数据列表
        List<ProductOutboundDetail> list = productOutboundDetailService.findExcelDataInMasterId(masterId);
         //为表格添加序号
        for(int i=0; i < list.size(); i++){
            int n= i+1;
            list.get(i).setNum(n);
        }
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id",masterId);
        map2.put("isDel",false);
        ProductOutboundTable outTable = productOutboundTableService.findProductOutboundTableByxxx(map2);
        //4.配置对象数据map
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("customerName",outTable.getCustomerName());
        map3.put("outboundDate",new SimpleDateFormat("yyyy-MM-dd").format(outTable.getOutboundDate()));
        map3.put("outboundMoney", BigDecimalUtil.formatToNumber(new BigDecimal(String.valueOf(outTable.getOutboundMoney()))));
        map3.put("outboundMoney1", ChineseYuanUtil.number2CNMontrayUnit(outTable.getOutboundMoney()));
        map3.put("name",name);
        ExcelUtil.writeExcel(req,resp,fileName,path,list,map3,ProductOutboundDetail.class);
        return  URLEncoder.encode(fileName, "UTF-8");
    }

fileName 返回下载链接让前端使用

前端VUE对接

1.设置一个按钮

导出

2.js逻辑代码

 //查询导出文件url,执行导出程序
        btnExportExcel() {
            var data = Qs.stringify({
                //根据自己需求设置参数
                masterId: this.masterId, 
                name: this.user.name, 
            })
            axios
                .post(
                //后台提供的接口    
                this.GLOBAL.BASE_URL +
                    "KFGL0601-web/productPutInStorageDetail/EasyExcel",
                    data
                )
                .then(res => {
      //url解码 修整正确下载url
     this.fileName = decodeURIComponent(res.data).replace('+', ' ').substring(51)
                    //导出
                    this.downloadExcel();
                })
                .catch(err => {
                    console.log(err);
                });
        },
        //导出Excel
        downloadExcel() {
            var elemIF = document.createElement('iframe')
            elemIF.src = this.GLOBAL.BASE_URL + this.fileName
            elemIF.style.display = 'none'
            document.body.appendChild(elemIF)
        },

你可能感兴趣的:(技术类,java)