首页 > 其他分享 >EasyExcel

EasyExcel

时间:2024-10-16 14:44:50浏览次数:1  
标签:head EasyExcel excel new import com response

1、自动换行

/**
     * 导出 Excel,多个 sheet
     *
     * @param response    response
     * @param fileName    文件名
     * @param head        表头
     * @param sheetMap    sheetName -> 数据
     */
    public static void exportExcelMultiSheet(HttpServletResponse response,
                                             String fileName,
                                             List<List<String>> head,
                                             Map<String, List<List<Object>>> sheetMap) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置自动换行,前提内容中需要加「\n」才有效
        contentWriteCellStyle.setWrapped(true);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);

        ExcelWriter excelWriter = null;
        try {
            // 防止乱码
            String finalFileName = URLEncoder.encode(fileName, "UTF-8").replace("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + finalFileName);
            excelWriter = EasyExcelFactory
                    .write(response.getOutputStream())
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .build();
            for (Map.Entry<String, List<List<Object>>> entry : sheetMap.entrySet()) {
                WriteSheet writeSheet = EasyExcelFactory.writerSheet(entry.getKey()).head(head).build();
                excelWriter.write(entry.getValue(), writeSheet);
            }
            excelWriter.finish();
        } catch (Exception e) {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            log.error("Excel 导出失败", e);
        }
    }

2、easyexcel,导出Excel,设置单元格样式,

easyexcel 2.2版本

((XSSFCellStyle) cellStyle) 强转类型后设置背景色,调用父类的方法

try {
            response.setContentType(ReportMapKeyConstant.CONTENT_TYPE_EXCEL.getValue());
            String fileName = "年度考核得分总体组.xlsx";
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            ExcelWriter writer = EasyExcelFactory.write(response.getOutputStream()).build();
            WriteSheet writeSheet = EasyExcelFactory.writerSheet("sheet")
                    .head(head)
                    .registerWriteHandler(new AssessmentOverallCellStyleStrategy())
                    .registerWriteHandler(new MyWidthStrategy(widthMap))
                    .registerWriteHandler(new SimpleRowHeightStyleStrategy(null, (short) 19))
                    .build();
            writer.write(exportList, writeSheet);
            writer.finish();
        } catch (Exception e) {
            response.setStatus(SC_BAD_REQUEST);
        }

行高设置

  ​new SimpleRowHeightStyleStrategy(null, (short) 19)

宽度设置

package com.unicom.diamond.report.excel;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;
import java.util.Map;

/**
 * @author wc
 * @since 2021-10-11
 */
@RequiredArgsConstructor
public class MyWidthStrategy extends AbstractColumnWidthStyleStrategy {
    private final Map<Integer, Integer> widthMap;

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
        Sheet sheet = writeSheetHolder.getSheet();

        int i = cell.getColumnIndex();

        sheet.setColumnWidth(i, 256 * widthMap.get(i) + 184);
    }
}

样式设置

package com.unicom.diamond.report.excel;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;

import java.awt.Color;
import java.util.ArrayList;

/**
 * @Description 年度考核-总体组-导出样式策略
 * @Author kj
 * @Date 2023/12/14
 */
public class AssessmentOverallCellStyleStrategy extends AbstractCellStyleStrategy {
    private Workbook workbook;

    @Override
    protected void initCellStyle(Workbook workbook) {
        this.workbook = workbook;
    }

    @Override
    protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
        CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, this.getHeadStyle());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置背景色
        ArrayList<Integer> blueList = CollectionUtil.newArrayList(0, 1, 9, 23, 32, 33, 34);
        Color color;
        if (blueList.contains(cell.getColumnIndex())) {
            color = new Color(91, 155, 213);
        } else {
            color = new Color(152, 210, 119);
        }
        ((XSSFCellStyle) cellStyle).setFillForegroundColor(new XSSFColor(color, null));
        cell.setCellStyle(cellStyle);
    }

    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

    }

    private WriteCellStyle getHeadStyle() {
        // 表头字体样式
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("微软雅黑");
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteFont.setColor(IndexedColors.WHITE.getIndex());
        // 表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 无背景颜色
        headWriteCellStyle.setFillPatternType(FillPatternType.NO_FILL);
        // 无边框
        headWriteCellStyle.setBorderBottom(BorderStyle.NONE);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        headWriteCellStyle.setWriteFont(headWriteFont);

        return headWriteCellStyle;
    }
}

大文件读取

流式

使用 poi的 XSSFReader​ 与SAX模式解析,但是目前还没找到处理图片的方法

普通版本

先限制文件的大小

可以对文件进行切分,暂时没实现

  ‍

标签:head,EasyExcel,excel,new,import,com,response
From: https://www.cnblogs.com/kjnotes/p/18469914/easyexcel-zvip2v

相关文章

  • 使用EasyExcel写入Excel后,将多个Excel打包为ZIP压缩包下载
    概述使用EasyExcel写入Excel后,将多个Excel打包为ZIP压缩包下载代码@GetMapping("/downloadToZip")publicvoiddownloadToZip(HttpServletResponseresponse){//设置响应头response.setContentType("application/zip");response.setCharacterEncoding(Standar......
  • Springboot使用EasyExcel 的填充模板导出,导出为多Sheet工作簿
    概述Springboot使用EasyExcel的填充模板导出,导出为多Sheet工作簿详细代码Excel数据填充/***使用EasyExcel写入Excel*@paramexcelModelFilePath 模板文件地址*@paramsheetNameAndDataMap Sheet名称与Sheet数据Map集合,key为Sheet名称,value为Sheet数据集合*@ret......
  • EasyExcel读取合并单元格数据
    EasyExcelEasyExcel文档地址:https://easyexcel.opensource.alibaba.com/docs/current/quickstart/read一、前言当excel表格的数据表头和内容都比较工整,每个单元格对应一个数据时,通过EasyExcel可以很容易就将数据读取出来。但是当表格数据存在合并单元格时,还是按照EasyExc......
  • EasyExcel导出合并单元格
    处理结果:把a,b列相同内容的单元格进行合并引入easyexcel:<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.2.1</version></dependency>示例代码:publicvoidexportStrategyDetail(......
  • EasyExcel导出文件基本流程以及原理分析 学习笔记(持续更新)
    EasyExcel导出文件基本流程导出文件基本流程获取数据首先获得需要导出的文件的数据内容,用一个list保存List<SysStudent>list=sysStudentService.queryList(sysStudent);定义文件名给导出的文件定义一个名字,可以添加日期或者根据输入添加其他信息,保证文件名唯一S......
  • SpringBoot中使用EasyExcel并行导出多个excel文件并压缩zip后下载
    ❃博主首页:「码到三十五」,同名公众号:「码到三十五」♝博主的话:搬的每块砖,皆为峰峦之基;公众号搜索「码到三十五」关注这个爱发技术干货的coder,一起筑基背景SpringBoot的同步导出方式中,服务器会阻塞直到Excel文件生成完毕,在处理大量数据的导出功能,利用CompletableF......
  • 【项目实战】JAVA 项目使用 EasyExcel 读取和导入数据到项目中
    1、easyExcel引入依赖进入官网GetStarted就可以了。(官方文档简单好用,跟着走就可以了。)https://alibaba-easyexcel.github.io/index.html<!--easyExcel--><dependency><groupId>com.alibaba</groupId><artifactId>easye......
  • easyExcel导出大数据量EXCEL文件,前端实现进度条
    需求:页面点击导出,先按照页面条件去数据库查询,然后将查询到的数据导出。问题:由于查询特别耗时,所以点击之后页面会看上去没有反应,就在点击之后在页面增加了一个进度条,等待后盾查询结束之后,导出时,进度条会显示导出进度,导出结束之后进度条会消失。效果如下:注意点:后端需要在响应......
  • EasyExcelUtil导出
    packagecom.istrong.seatom.utils;importcn.hutool.core.collection.ListUtil;importcom.alibaba.excel.EasyExcel;importcom.alibaba.excel.enums.CellDataTypeEnum;importcom.alibaba.excel.metadata.Head;importcom.alibaba.excel.metadata.data.WriteCellData......
  • 【工具使用】【EasyExcel 】EasyExcel 实现 Excel 作者信息、版本信息等的写入和读取
    1 前言导入的功能,想必大家都做过,大家肯定也都遇到过比如我的模板变化了(比如新增一列、删除一列等),客户在使用的时候可能还是用的老模板进行导入,那么我们在写代码的时候,应该怎么快速识别到呢?比如可以比较客户导入的Excel一列一列的去比较或者列的个数等是可以的。我想的一个......