首页 > 其他分享 >excel导出(支持多工作表)

excel导出(支持多工作表)

时间:2023-08-23 17:56:32浏览次数:25  
标签:excel 导出 支持 contentWriteCellStyle import new com response

目录

excel导出(支持多工作表)

maven依赖

<!--springboot-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.6</version>
</dependency>
<!--实体类-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>
<!-- excel操作-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.0.5</version>
</dependency>

相关实例

启动文件

package com.ntt.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;


@SpringBootApplication
public class CmsApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(CmsApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(CmsApplication.class);
    }
}
server:
  port: 9999

控制类

package com.ntt.web.controller;


import com.ntt.web.pojo.Student;
import com.ntt.web.utils.ExcelUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/v1")
public class StuController {

    /**
     * 导出
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response) throws Exception{
        // 模拟查询匹配数据
        List<Student> list = new ArrayList<>();
        list.add(new Student().setName("小白").setAge(10).setCreateTime(LocalDateTime.now()));
        list.add(new Student().setName("小黑").setAge(11).setCreateTime(LocalDateTime.now()));
        // 导出
        LinkedHashMap<String, List<?>> resultMap = new LinkedHashMap<>();
        resultMap.put("结果", list);
        ExcelUtils.dataType = Arrays.asList(new Student());
        ExcelUtils.httpSaveByExcel(response, resultMap);
    }

}

实体类

package com.ntt.web.pojo;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.fasterxml.jackson.annotation.JsonFormat;

import java.time.LocalDateTime;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class Student {
    private static final long serialVersionUID = 1L;

    /**
     * 姓名(原始)
     */
    @ExcelProperty(value = "姓名")
    private String name;

    /**
     * 年龄
     */
    @ExcelProperty(value = "年龄")
    private Integer age;

    /**
     * 创建时间
     */
    @ExcelIgnore
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

}

工具类

package com.ntt.web.utils;

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

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExcelUtils {
    public static List<?> dataType = null;  // 导出的数据实体类型

    /**
     * Web导出结果(http-excel-多sheet)
     * @param response
     * @param resultMap
     * @throws Exception
     */
    public static void httpSaveByExcel(HttpServletResponse response, LinkedHashMap<String,List<?>> resultMap) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try{
            // 获取文件结果
            SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
            String fileName = URLEncoder.encode(dft.format(new Date()), "UTF-8"); // 20220916
            // 响应信息构建
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            // 根据传递过来的map将结果导出到多个sheet
            Integer sheetNum = 0;  // sheet工作表序号
            if (resultMap != null && !resultMap.isEmpty()){
                for(Map.Entry<String, List<?>> entry : resultMap.entrySet()){
                    String rmKey = entry.getKey();  // sheet工作表名称
                    List<?> resultVal = entry.getValue(); // sheet工作表数据
                    if (rmKey != null){
                        resultVal = (resultVal != null && !resultVal.isEmpty()) ? resultVal : new ArrayList<>();
                        excelWriter.write(
                                resultVal, // 相关数据
                                EasyExcel.writerSheet(sheetNum, rmKey)
                                        .head(dataType.get(sheetNum).getClass())
                                        .registerWriteHandler(myHorizontalCellStyleStrategy())
                                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                                        .build()  // 工作表创建
                        );
                        sheetNum ++;
                    }
                }
            }
            // 关闭流
            excelWriter.finish();
        }catch (Exception e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(e);
        }
    }

    /**
     * 本地导出结果(excel-单sheet|多sheet)
     * @param resultMap
     * @param resultPath
     */
    public static void localSaveByExcel(LinkedHashMap<String,List<?>> resultMap, String resultPath) throws IOException {
        // 指定输出的文件流
        File outFile = new File(resultPath);
        OutputStream outputStream = null;
        ExcelWriter excelWriter = null;
        try{
            outputStream = new FileOutputStream(resultPath);
            // 优先创建文件
            if (!outFile.exists()){
                File parentFile = outFile.getParentFile();
                if (!parentFile.exists()){
                    parentFile.mkdirs();
                }
                outFile.createNewFile();
            }
            // 新建ExcelWriter
            excelWriter = EasyExcel.write(outputStream).build();
            // 根据传递过来的map将结果导出到多个sheet
            Integer sheetNum = 0;  // sheet工作表序号
            if (resultMap != null && !resultMap.isEmpty()){
                for(Map.Entry<String, List<?>> entry : resultMap.entrySet()){
                    String rmKey = entry.getKey();  // sheet工作表名称
                    List<?> resultVal = entry.getValue(); // sheet工作表数据
                    if (rmKey != null){
                        resultVal = (resultVal != null && !resultVal.isEmpty()) ? resultVal : new ArrayList<>();
                        excelWriter.write(
                                resultVal, // 相关数据
                                EasyExcel.writerSheet(sheetNum, rmKey)
                                        .head(dataType.get(sheetNum).getClass())
                                        .registerWriteHandler(myHorizontalCellStyleStrategy())
                                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                                        .build()  // 工作表创建
                        );
                        sheetNum ++;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            if (outputStream != null){
                outputStream.close();
            }
        }
    }

    /**
     *  设置表头 和内容样式
     * @return
     */
    public static HorizontalCellStyleStrategy myHorizontalCellStyleStrategy(){
        //1 表头样式策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //表头前景设置浅绿色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        WriteFont headWriteFont = new WriteFont();
        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);
        //背景设置白色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        //设置自动换行
        contentWriteCellStyle.setWrapped(false);
        //设置垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        //设置背景黄色
        //        contentWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        //设置水平靠左
        //contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        //设置边框样式
        setBorderStyle(contentWriteCellStyle);
        //内容风格可以定义多个。
        listCntWritCellSty.add(contentWriteCellStyle);

        // 水平单元格风格综合策略(表头 + 内容));
        return  new HorizontalCellStyleStrategy(headWriteCellStyle, listCntWritCellSty);
    }

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

标签:excel,导出,支持,contentWriteCellStyle,import,new,com,response
From: https://www.cnblogs.com/fsh19991001/p/17652393.html

相关文章

  • 使用easyexcel导入62个字段,十万加行数的excel
    使用easyexcel导入62个字段,十万加行数的excel1️⃣准备工作1.版本对应在easyexcel官网的常见问题栏中往下滑找到2.下载jar包maven项目不想多说,在pom.xml文件下,dependcy标签下引入就可以;在web_inf项目下需要手动引入jar包,在mvn中心仓库,下载对应jar包以及所依赖的其他jar包......
  • 1、postgres数据导出
    目录postgres数据导出1、只导出所有对象的数据库结构2、只导出对应的数据库与数据3、只导出所有的表数据4、整个数据库导出postgres数据导出1、只导出所有对象的数据库结构pg_dump-fuser_export.sql-i-C-EUTF8-nmyschema-s-Umypguser-hlocalhost-Wmypostgres......
  • 盘点一个pandas读取excel数据并处理的小需求
    大家好,我是皮皮。一、前言前几天在Python最强王者群【wen】问了一个pandas数据处理的问题,一起来看看吧。通过pandas读取excel数据,其中两列是交易的备注信息,对A列数据筛选并把结果输出到C列。如果A列中有['吉利','奔驰','福特']三个字段,C列标记为‘汽车品牌’,如果A列有['NIKE','......
  • 获取音频播放时长,支持wav格式(环境无声卡)
    获取音频文件时长/***获取音频播放时长,支持wav格式(环境无声卡)*@paramfilePath文件授权地址*@authorknight-jzc*@return秒数*/publicstaticIntegergetDuration(StringfilePath){try{Stringbath=filePath.split(":")[0];AudioInp......
  • 多轨模式——保存导出混缩
    贴在一起的时候,会自动匹配到如果想把多轨变成三轨,就可以这样子做......
  • 导出数据库表格为特定格式
    导出数据库表格为excel格式:SELECTCOLUMN_NAME列名,DATA_TYPE字段类型,ifnull(ifnull(CHARACTER_MAXIMUM_LENGTH,NUMERIC_PRECISION),DATETIME_PRECISION)长度,ifnull(NUMERIC......
  • WebRTC 支持H265探索之路
    截至目前为止,参考了大量的文献和博客,都通过datachannel进行码流的传输,然后在浏览器端重新实现解码和渲染,因此意味着WebRTC不再具有任何的研究价值,还不如自身实现通过websocket对码流的传输,相比WebRTC庞大的体量,暂时不会做任何的调整。相信在专利面前,Google不会做任何的改善,还有UDP......
  • LightDB支持drop table时cascade constraints语法
    在Oracle数据库中,droptable语法如下:即droptable时通过cascadeconstraints级联删除所有该表中的约束。在LightDB23.3版本中,droptable同样支持了constraints关键字,自动删除依赖于表的所有约束对象。语法结构如下:DROPTABLE[IFEXISTS]name[,...][CASCADE[CONSTRA......
  • # yyds干货盘点 # 盘点一个pandas读取excel数据并处理的小需求
    大家好,我是皮皮。一、前言前几天在Python最强王者群【wen】问了一个pandas数据处理的问题,一起来看看吧。通过pandas读取excel数据,其中两列是交易的备注信息,对A列数据筛选并把结果输出到C列。如果A列中有['吉利','奔驰','福特']三个字段,C列标记为‘汽车品牌’,如果A列有['NIKE','李宁......
  • excel的烦恼
    Smiling&Weeping----他未对我好半分,偏巧这感情疯长似野草 题目链接:https://www.matiji.net思路:与新三进制2思路相似,转化为纯26进制,然后往前遍历创造出符合题目要求的Talkischeap,showmethecode 1#include<bits/stdc++.......