首页 > 其他分享 >利用EasyPoi 实现 传入List数据,输出excel文件

利用EasyPoi 实现 传入List数据,输出excel文件

时间:2024-03-22 10:02:15浏览次数:15  
标签:java excel List EasyPoi ExcelExportEntity new import response

基本描述

场景

用户传入List数据,要求生成Excel文件

(糟糕的需求是真糟糕!!!)

本次算是未完成版[应付需求还是可以的](需要硬代码去编写模板,各位宝子们先将就下,后续会跟新传参版)

特别提醒

时间字段 我们当做字符处理的写模板的时候不要用format属性(暂无特别好的解决方案,有大神可以以指导下喽)

原理

利用Easypoi 中的本身提供ExcelExportEntity去处理

实现描述

输入信息:

[
	{
		"name": "西索",
		"sex": 1,
		"createTime": "2023-11-11 12:12:12",
		"address": [
			{
				"currentAddress": "友客鑫市",
				"beforeAddress": "天空竞技场"
			},
			{
				"currentAddress": "黑暗大陆",
				"beforeAddress": "玛塔卡王国"
			}
		]
	},
	{
		"name": "库洛洛",
		"sex": 1,
		"createTime": "2023-11-11 12:12:12",
		"address": [
			{
				"currentAddress": "东方",
				"beforeAddress": "流星街"
			}
		]
	}
]

输出结果:

代码实现

控制层

/**
 *
 * @param list
 * @param response
 * @throws IOException
 */
@RequestMapping(value = "export/data/map")
public void exportDataFactory(@RequestBody List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
        // 创建一个 Excel 导出参数对象
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("用户信息表");
        exportParams.setSheetName("用户信息");
        // 使用 EasyPoi 创建一个 Excel 文件
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息表", "用户信息"), ExcelExtraFactory.build(ExcelExtraFactory.TEMPLATE1), list);
        //使用工具类导出
        ZExcelUtils.export(response, workbook, exportParams.getTitle() + ".xlsx");
}

工具类

package com.example.extra;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSONObject;

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

/**
 * @author sszdzq
 */
public class ExcelExtraFactory {
    public static final String TEMPLATE1 = "TEMPLATE1";

    /**
     * 模板数据生成
     *
     * @param template
     * @return
     */
    public static List<ExcelExportEntity> build(String template) {
        switch (template) {
            case "TEMPLATE1":
                return template1Entity();
            default:
                ;
        }
        throw new NoSuchElementException("no template " + template);
    }

    /**
     * 自定义模板示例 [新模板就按照这个写就可以]
     *
     * @return
     */
    private static List<ExcelExportEntity> template1Entity() {
        List<ExcelExportEntity> entityList = new ArrayList<>();

        ExcelExportEntity nameEntity = new ExcelExportEntity("姓名", "name");
        nameEntity.setNeedMerge(true);
        entityList.add(nameEntity);

        ExcelExportEntity sexEntity = new ExcelExportEntity("性别", "sex");
        sexEntity.setNeedMerge(true);//合并单元格
        sexEntity.setReplace(new String[]{"男_1", "女_0", "_null"});//replace 格式话
        entityList.add(sexEntity);

        ExcelExportEntity createTimeEntity = new ExcelExportEntity("录入时间", "createTime");
        createTimeEntity.setNeedMerge(true);
        entityList.add(createTimeEntity);

        ExcelExportEntity addressEntity = new ExcelExportEntity("地址", "address");
        List<ExcelExportEntity> temp = new ArrayList<>();
        temp.add(new ExcelExportEntity("现居地", "currentAddress"));
        temp.add(new ExcelExportEntity("曾居地", "beforeAddress"));
        addressEntity.setList(temp);

        entityList.add(addressEntity);
        return entityList;
    }

}

工具类

package com.example.util;


import cn.afterturn.easypoi.excel.annotation.Excel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.lang.reflect.*;
import java.util.Map;

/**
 * @author sszdzq
 */
public class ZExcelUtils {

    // Excel 导出 通过浏览器下载的形式
    public static void export(HttpServletResponse response, Workbook workbook, String fileName) throws IOException {
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Pragma", "no-cache");
        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
        workbook.write(bufferedOutPut);
        bufferedOutPut.flush();
        bufferedOutPut.close();
    }
}


标签:java,excel,List,EasyPoi,ExcelExportEntity,new,import,response
From: https://blog.csdn.net/sszdzq/article/details/136928794

相关文章

  • cad vba 打开excel并弹窗打开指定文件
     CADvba代码实现打开excel,并通过对话框选择xls文件,并打开此文件进行下一步操作。代码如下:OptionExplicit#IfVBA7ThenPrivateDeclarePtrSafeFunctionts_apiGetOpenFileNameLib"comdlg32.dll"Alias"GetOpenFileNameA"(tsFNAstsFileName)AsBooleanPriva......
  • ArrayList的扩容机制以及ArrayList与LinkedList的区别
    ArrayList的扩容机制假设采用无参构造器来实列化ArrayList对象ArrayListarrayList=newArrayList();此时,arrayList的初始容量为零,当第一次调用add方法时,会触发扩容机制,容量扩容为10。此后,在调用add方法时,如果容量不足,则容量会扩容为当前容量的1.5倍。capcity=capacity......
  • Java list初始化的几种办法
    在Java中初始化List的五种方法1.构造List后使用List.add初始化2.使用{{}}双括号语法3.使用Arrays.asList4.使用Stream(JDK8)5.使用Lists(JDK9)在Java中初始化List的五种方法Java中经常需要使用到List,下面简单介绍几种常见的初始化方式。1.构造......
  • 询问ChatGPT4,改造TodoList:把本地存储的localStorage修改成PHP+Redis
    这里照搬的是:免费极简设计网页版Todo  https://www.ricocc.com/todo/非常感谢原作者Rico。我很喜欢这个设计和风格,但是可惜只能本地存储,我又不想使用微软的TODO,登录倒无所谓,但是数据同步问题很大,实在头痛,所以放弃。我是菜鸟,只是刚好前段时间安装了Apache、PHP的一键安装包和......
  • 从数据库查询数据并导出到excel
    importpymysqlimportdatetimeimportxlwtimportosimportpandasaspddefexport_excel(output_dir):current_datetime=datetime.datetime.now()#将日期时间格式化为字符串,例如:2023-10-23_14-30-15formatted_datetime=current_datetime.strftime('%......
  • list转树状结构 非递归 多个顶级节点 通用工具类
    有时候,需要返给前端需要的树状结构数据。需要后端转换组装。做了个通用工具类,非递归方式,简单易用。上代码:树结构类:packagecom.ruoyi.shop;importlombok.Data;importjava.util.List;/***返回前端树结构*@Authorwql*@Date2024/3/219:36*/@Datapubl......
  • C# 使用HttpListener时候异常(此平台不支持此操作:System.PlatformNotSupportedExceptio
    ​ C#使用HttpListener时候异常(此平台不支持此操作:System.PlatformNotSupportedException)代码:HttpListenerlistener=newHttpListener();错误:System.PlatformNotSupportedException:OperationisnotsupportedonthisplatformInSystem.Net.HttpListener..ctor()......
  • WPS WORD EXCEL 不合并显示
    WPSWORDEXCEL不合并显示 版本:WPS12,下载时间约是2023年。 1.在开始菜单里找到WPSOFFICE-配置工具2.点击“高级(A)”。3.在“其他选项”选项卡中,点击“切换到旧版的多组件模式”。4.选择“多组件模式”,然后确定。11......
  • 从时间复杂度的角度出发,list和vector之间查找,插入,删除等数据操作的区别
    list和vector是STL(标准模板库)中常用的两种序列容器,它们各自在不同类型的操作上有着不同的优势。下面是list和vector在不同操作上的擅长之处:list的擅长操作插入和删除操作:list是一个双向链表,插入和删除元素时只需要调整相邻节点的指针,因此在中间或任意位置插入或删除元素时效率很......
  • python之自定义表头、列表内容导出excel文件例子
    函数三个参数outputfile:导出excel文件的位置,没有的话在该位置建该文件title:表头args:列的内容,每列是一个列表importxlsxwriterdefwriteExcel(outputfile,title,*args):wb=xlsxwriter.Workbook(outputfile)#创建sheetsheet=wb.add_worksheet("Sh......