侧边栏壁纸
博主头像
Epoch

Java开发、Python爬虫、微服务、分布式、前端

  • 累计撰写 92 篇文章
  • 累计创建 109 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Java开发--导出Excel工具类(封装)

Epoch
2021-09-09 / 0 评论 / 0 点赞 / 266 阅读 / 222 字 / 正在检测是否收录...

导出Excel工具类

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class EasyExcelUtils {

    /**
     * @param sheetName 导出的名字
     * @param response  响应的请求
     * @param t         设置导出的文件类型
     * @param list      导出的list集合
     * @throws IOException            异常
     * @throws IllegalAccessException 异常
     * @throws InstantiationException 异常
     */
    public static void download(String sheetName, HttpServletResponse response, Class t, List list) throws IOException, IllegalAccessException, InstantiationException {
        try {
            response.setContentType("application/vnd.ms-excel");// 设置文本内容
            response.setCharacterEncoding("utf-8");// 设置字符编码
            String fileName = URLEncoder.encode(sheetName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); // 设置响应头
            response.setHeader("FileName", fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            EasyExcel.write(response.getOutputStream(), t)
                    .autoCloseStream(Boolean.FALSE).sheet(fileName).doWrite(list); //用io流来写入数据
        } catch (Exception e) {
            log.error("EasyExcelUtils,e:{}", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException();
        }

    }
    
}

详情见 Excel–导入/导出

0

评论区