Springboot中使用 Jxls 导出Excel

Jxls 导出 Excel

Springboot 中使用 Jxls 导出 Excel

添加依赖

  
        <dependency>
            <groupId>org.jxlsgroupId>
            <artifactId>jxlsartifactId>
            <version>2.8.1version>
        dependency>

        
        <dependency>
            <groupId>org.jxlsgroupId>
            <artifactId>jxls-poiartifactId>
            <version>2.8.1version>
        dependency>

        
        
        <dependency>
            <groupId>org.jxlsgroupId>
            <artifactId>jxls-jexcelartifactId>
            <version>1.0.9version>
        dependency>

定义导出实体类Fish.java

package com.gaolei.app.entity;

import lombok.Data;

/**
 * @author DuebassLei
 * @version 1.0
 * @date 2020/10/12 17:07
 */
@Data
public class Fish {
    /**
     * 名称
     * */
    private String name;

    /**
     * 价格
     **/
    private String price;

    /**
     * 品种
     * */
    private String kind;

}

定义excel模板

Springboot中使用 Jxls 导出Excel_第1张图片

定义控制器JxlsController.java

@Slf4j
@Controller
@RequestMapping(value = "/api/jxls")
public class JxlsController {
    @PostMapping(value = "export")
    public void jxlsExport(HttpServletRequest request,HttpServletResponse response) throws IOException {
        log.info("Jxls 导出excel数据");

        //模拟数据
        List<Fish> fishList = new ArrayList<>();
        for (int i = 0; i < 100 ; i++) {
            Fish fish = new Fish();
            fish.setName("小鲤鱼"+i);
            fish.setKind("鲤鱼"+i);
            fish.setPrice("20"+i);
            fishList.add(fish);
        }

        InputStream is = new ClassPathResource("templates/fish.xls").getInputStream();
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + "fish.xls");
            response.setContentType("application/octet-stream");
            Context context = new Context();
            context.putVar("fishList", fishList);
            JxlsHelper.getInstance().processTemplate(is, os, context);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            os.flush();
            os.close();
        }
    }
  }

Postman测试

测试接口地址:
http://localhost:9999/api/jxls/export

##导出数据效果

Springboot中使用 Jxls 导出Excel_第2张图片

更多功能详见Jxls官方Api

博文源码: gitee/Duebasslei

你可能感兴趣的:(SpringBoot,excel)