easyExcel复杂表头的设置与样式的设置(非注解)

easyExcel复杂表头的设置与样式的设置(非注解)

表头样式一

在这里插入图片描述
引入jar包

  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.6</version>
            <scope>compile</scope>
  </dependency>

excel的样式设置

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;

import java.util.ArrayList;
import java.util.List;

public class HeadContentCellStyle {


    /**
     *  设置表头  和内容样式
     * @return
     */
    public static HorizontalCellStyleStrategy myHorizontalCellStyleStrategy(){
//1 表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //表头前景设置白色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setBold(true);
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short)11);
        headWriteCellStyle.setWriteFont(headWriteFont);

        //内容样式  多个样式则隔行换色
        List<WriteCellStyle>   listCntWritCellSty =  new ArrayList<>();

//2 内容样式策略  样式一
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        //内容字体大小
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short)11);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //背景设置白色(这里一定要设置表格内容的背景色WPS下载下来的文件没有问题,但是office下载下来的文件表格内容会变成黑色)
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        //设置自动换行
        contentWriteCellStyle.setWrapped(true);
        //设置垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 头默认了 FillPatternType所以可以不指定。
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        //设置背景黄色
//        contentWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        //设置水平靠左
        //contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        //设置边框样式
        setBorderStyle(contentWriteCellStyle);
        //内容风格可以定义多个。
        listCntWritCellSty.add(contentWriteCellStyle);

//2 内容样式策略  样式二
        WriteCellStyle contentWriteCellStyle2 = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色。
        // 头默认了 FillPatternType所以可以不指定。
        contentWriteCellStyle2.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        //背景设置白色
        contentWriteCellStyle2.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        // 背景绿色
//        contentWriteCellStyle2.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        //设置垂直居中
        contentWriteCellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置边框样式
        setBorderStyle(contentWriteCellStyle2);
        listCntWritCellSty.add(contentWriteCellStyle2);
        // 水平单元格风格综合策略(表头 + 内容)
        // return  new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        return  new HorizontalCellStyleStrategy(headWriteCellStyle, listCntWritCellSty);
    }

    /**
     * 设置边框样式
     * @param contentWriteCellStyle
     */
    private static void setBorderStyle(WriteCellStyle contentWriteCellStyle){
        //设置边框样式
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        // contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex()); //颜色
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
    }

}


文件流的输出

  /**
     *
     * 
     * @Param 复杂表头文件导出
     * @return 
     */
    public void downloadFile(HttpServletResponse response, List<?> list, String fileNames, String sheetName,List<List<String>> titleList) throws IOException {
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(3698,"当前参考单位无数据");
        }
        if (StringUtils.isEmpty(fileNames)) {
            fileNames = new Date().toString();
        }
        if (StringUtils.isEmpty(sheetName)) {
            sheetName = "Sheet1";
        }
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(fileNames, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
//            EasyExcel.write(response.getOutputStream(), list.get(0).getClass()).autoCloseStream(Boolean.FALSE).sheet(sheetName)
//                    .doWrite(list);
            EasyExcel.write(response.getOutputStream())
                    .head(roateHeadFields(titleList))
                    .registerWriteHandler(HeadContentCellStyle.myHorizontalCellStyleStrategy())
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(15)) // 简单的列宽策略,列宽15
                    .registerWriteHandler(new SimpleRowHeightStyleStrategy((short)25,(short)15)) // 简单的行高策略:头行高30,内容行高15
                    .sheet("sheet").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败------------"+e.getMessage());
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
    
       /**
     * 表头设置
     * @param headFields
     * @return
     */
    private List<List<String>> roateHeadFields(List<List<String>> headFields) {
        List<List<String>> result = new ArrayList<>();
        for (List<String> row : headFields) {
            for (int j = 0; j < row.size(); j++) {
                if (result.size() > j) {
                    // 往对应第j个List<String> 添加添加值
                    result.get(j).add(row.get(j));
                } else {
                    // 分割成单个List<String>
                    result.add(new ArrayList<>(Collections.singletonList(row.get(j))));
                }
            }
        }
        return result;
    }
    /**
     * 文件的头
     * @param titleList
     * @return
     */
    public List<String> makeUpTitle(List<String> titleList) {
        List<String> makeUpList = new ArrayList<>();
        String temp = "";
        for (String e : ListUtils.emptyIfNull(titleList)) {
            if (StringUtils.isNotEmpty(e)) {
                temp = e;
            }
            makeUpList.add(temp);
        }

        return makeUpList;

    }


设置文件头和数据导入


   /**
     * @description 全市单科成绩统计表
     *
     **/
    public void downloadCitySingleScore(HttpServletResponse response, String examId) throws IOException {
        //获取文件名称
        String fileNames = getFileNames(examId,"全市单科成绩统计表");
        //获取单科成绩数据
        List<CitySingleScore> scoreList = getCitySingleScores(examId);
        //建立表头
        List<List<String>> titleList = new ArrayList<>();
        List<String> titleOne = Lists.newArrayList(fileNames,"","","");
        List<String> titleTwo = Lists.newArrayList("科目","平均分","最高分","最高分人数");
        titleList.add(easyExcelUtil.makeUpTitle(titleOne));
        titleList.add(easyExcelUtil.makeUpTitle(titleTwo));
        easyExcelUtil.downloadFile(response,scoreList,fileNames,null,titleList);
    }

表头样式二

在这里插入图片描述

jar包和excel的样式设置不变 ,表头数据需要自己组装

  /**
     * 创建表头
     * @return
     */
    public   List<List<String>> head(String examId) {
        List<List<String>> list = new ArrayList<List<String>>();
        //表头数据
        String basicInfo=examUitl.getFileNames(examId,"全市赋分等级区间表");
        String a="等级",b="比例",c="赋分区间",d="原始分分布区间";
        //第一列,1/2/3行
        list.add( Lists.newArrayList(basicInfo,a,a ));
        //第二列,1/2/3行
        list.add( Lists.newArrayList(basicInfo,b,b));
        //第三列
        list.add( Lists.newArrayList(basicInfo,c,c));
        //动态根据月份生成
        List<String> orderSpeaces = Lists.newArrayList("政治","地理","化学","生物");
        orderSpeaces.forEach(title->{
            list.add( Lists.newArrayList(basicInfo,d ,title) );
        });

        return list;
    }

数据导入


/**
     * @description 全市赋分等级区间表
     *
     * @params [response, examId]
     * @return void
     * @author xiaoyinchuan
     * @date 2020/11/24 0024 15:08
     **/
    public void downloadGraduation(HttpServletResponse response, String examId) throws IOException {
       
        List<NaturalGradeVO> list = highScoresNewService.selectNaturalGrade(examId);
          //生成数据
        List<Graduation> resultList = JSON.parseArray(JSON.toJSONString(list), Graduation.class);
        List<List<String>> head = head(examId);
        easyExcelUtil.downloadFileNext(response,resultList,examUitl.getFileNames(examId,"全市赋分等级区间表"),null,head);
    }

导入util

   /**
     *
     * 和方式一导入的差异是.head(titleList) ,表头直接放入
     * @Param 复杂表头文件导出
     * @return
     */
    public void downloadFileNext(HttpServletResponse response, List<?> list, String fileNames, String sheetName,List<List<String>> titleList) throws IOException {
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(3698,"当前参考单位无数据");
        }
        if (StringUtils.isEmpty(fileNames)) {
            fileNames = new Date().toString();
        }
        if (StringUtils.isEmpty(sheetName)) {
            sheetName = "Sheet1";
        }
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(fileNames, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
//            EasyExcel.write(response.getOutputStream(), list.get(0).getClass()).autoCloseStream(Boolean.FALSE).sheet(sheetName)
//                    .doWrite(list);
            EasyExcel.write(response.getOutputStream())
                    .head(titleList)  
                    .registerWriteHandler(HeadContentCellStyle.myHorizontalCellStyleStrategy())
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(15)) // 简单的列宽策略,列宽15
                    .registerWriteHandler(new SimpleRowHeightStyleStrategy((short)25,(short)15)) // 简单的行高策略:头行高25,内容行高15
                    .sheet("sheet").doWrite(list);
        } catch (Exception e) {
            log.error("导出失败------------"+e.getMessage());
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

参考文章:https://blog.csdn.net/qq_35461948/article/details/116658131
参考文章:https://blog.csdn.net/jie873440996/article/details/106399471

  • 6
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
对多行表头样式EasyExcel提供了一方法来实现。你可以使用`FillPatternType`类中`SOLID_FOREGROUND`来设置单元格的背景颜。另外,你可以使用`CellStyle`类中的`setAlignment`方法来单元格内容的对齐方式。下是一个示例代码,展示了如创建一个带有多行表头样式Excel文件: ```java // 创建工簿 Workbook workbook = new SXSSFWorkbook(); Sheet = workbook.createSheet("Sheet1"); // 设置字体样 Font font = workbookFont(); font.setBold(true); font.setFontHeightPoints((short) // 设置单元格样式 CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setFont(font); cellStyle.setAlignment(HorizontalAlignment.CENTER// 创建表头 Row row1 = sheet.createRow(0); Cell cell11 = row1.createCell(0); cell11.setCellValue("表头1"); cell11.setCellStyle(cellStyle); Row row2 = sheet.createRow(1); Cell cell21 = row2.createCell(0); cell21.setCellValue("表头2"); cell21.setCellStyle(cellStyle); // 合并单元格 CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 1, 0, 0); sheet.addMergedRegion(cellRangeAddress); // 设置列宽 sheet.setColumnWidth(0, 15 * 256); // 保存Excel文件 FileOutputStream outputStream = new FileOutputStream("多行表头样式.xlsx"); workbook.write(outputStream); outputStream.close(); workbook.close(); ``` 这个示例代码会创建一个包含两行表头的Excel文件,并且第一列的单元格会被合并为一个单元格。你可以根据自己的需求进行修改和扩展。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱上编程2705

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

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

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

打赏作者

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

抵扣说明:

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

余额充值