ExcelUtils

导包:

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId>poi-ooxml</artifactId>
                </exclusion>
            </exclusions>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
    </dependencies>

工具类:

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.ycsyxt.boot.utils.listener.ContentListener;
import com.ycsyxt.boot.utils.listener.ObjectListener;

/**
 * @author ycs
 */
public class ExcelUtils {

    /**
     * 将 Excel 文件流解析成二维行列 List
     * @param inputStream 输入流
     * @return
     */
    public static List<List<String>> parseToContent(InputStream inputStream) {
        List<List<String>> result = new ArrayList<>();
        EasyExcel.read(inputStream, new ContentListener(result)).sheet().doRead();
        return result;
    }

    /**
     * 将 Excel 文件流解析成 List 对象
     * @param inputStream 输入流
     * @param <T> 泛型,使用时传具体对象
     * @param type 具体对象.class
     * @return
     */
    public static <T> List<T> parseToObject(InputStream inputStream, Class<?> type) {
        List<T> result = new ArrayList<>();
        EasyExcel.read(inputStream, type, new ObjectListener(result)).sheet().doRead();
        return result;
    }

    /**
     * 将对象List 写到 Excel 输出流
     * @param type 对象
     * @param data 对象List
     * @param outputStream 输出流
     * @param <T>
     */
    public static <T> void objectToExcel(Class<?> type, List<T> data, OutputStream outputStream) {
        EasyExcel.write(outputStream, type).sheet().doWrite(data);
    }

    /**
     * 将二维List 写到 Excel 输出流
     * @param head Excel头
     * @param data 内容
     * @param outputStream 输出流
     */
    public static void contentToExcel(List<List<String>> head,
                                      List<List<Object>> data,
                                      OutputStream outputStream) {

        EasyExcel.write(outputStream).head(head).sheet().doWrite(data);
    }
}

演示demo:

目录结构:
在这里插入图片描述

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author ycs
 */
@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ycsyxt.boot.entity.DemoRead;
import com.ycsyxt.boot.entity.DemoWrite;
import com.ycsyxt.boot.utils.ExcelUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ycs
 */
@RestController
@Slf4j
public class TestController {

    @PostMapping("/testFile1")
    public List<List<String>> testFile1(@RequestParam MultipartFile file) throws IOException {
        return ExcelUtils.parseToContent(file.getInputStream());
    }

    @PostMapping("/testFile2")
    public List<DemoRead> testFile2(@RequestParam MultipartFile file) throws IOException {
         return ExcelUtils.parseToObject(file.getInputStream(), DemoRead.class);
    }

    @GetMapping("/getFile1")
    public void serveFile1(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        List<DemoWrite> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            DemoWrite data = new DemoWrite();
            data.setString("字符串" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }

        ExcelUtils.objectToExcel(DemoWrite.class, list, response.getOutputStream());
    }

    @GetMapping("/getFile2")
    public void serveFile2(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        List<List<String>> head = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add("字符串标题");
        List<String> head1 = new ArrayList<String>();
        head1.add("数字标题");
        List<String> head2 = new ArrayList<String>();
        head2.add("日期标题");
        head.add(head0);
        head.add(head1);
        head.add(head2);

        List<List<Object>> data = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            List<Object> row = new ArrayList<>();
            row.add("字符串" + i);
            row.add(new Date());
            row.add(0.56);
            data.add(row);
        }

        ExcelUtils.contentToExcel(head, data, response.getOutputStream());
    }
}

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;

import lombok.Data;

/**
 * @author ycs
 */
@Data
public class DemoRead {
    @ExcelProperty(index = 0)
    private String string;

    @ExcelProperty(index = 1)
    @DateTimeFormat("yyyy/MM/dd")
    private Date date;

    @ExcelProperty(index = 2)
    private Double doubleData;
}
import java.util.Date;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;

import lombok.Data;

/**
 * @author ycs
 */
@Data
public class DemoWrite {
    @ExcelProperty("字符串标题")
    private String string;

    // 宽度值尽量小于100
    @ColumnWidth(50)
    @ExcelProperty("日期标题")
    private Date date;

    @ExcelProperty("数字标题")
    private Double doubleData;
}
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

/**
 * @author ycs
 */
public class ContentListener extends AnalysisEventListener<Map<Integer, String>> {
    private List<List<String>> result;

    public ContentListener(List<List<String>> result) {
        this.result = result;
    }

    @Override
    public void invoke(Map<Integer, String> rowMap, AnalysisContext analysisContext) {
        Set<Integer> colIndexSet = rowMap.keySet();
        List<String> rowList = new ArrayList<>();
        for (int colIndex : colIndexSet) {
            rowList.add(rowMap.get(colIndex));
        }
        result.add(rowList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}

import java.util.List;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

/**
 * @author ycs
 */
public class ObjectListener<T> extends AnalysisEventListener<T> {

    private List<T> result;

    public ObjectListener(List<T> result) {
        this.result = result;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        result.add(t);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜长思

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值