poi 导出excel工具类包含导出内容为List<Map<String,Object>>,List<List<Object>>

2023-11-05

导入jar

<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>

工具类ExportExcel


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
//这里所需要的参数是  表格文件名  表格的sheet的名称   与表格的头部内容 和数据集合,以及response
/**
 * Created by Bob on 2021/4/7.
 */
public class ExportExcel
{
    public static boolean exportExcel(String excelName, String title, String[] headers, List<Map> dataset, String pattern, HttpServletResponse response) throws IOException {
//        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long milliSecond = System.currentTimeMillis();
        String fileName = excelName + "-" + milliSecond + ".xls";
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/x-xls;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        boolean flag = false;
        Workbook workbook = null;
        if (fileName.endsWith("xlsx"))
        {
            workbook = new XSSFWorkbook();
        } else if (fileName.endsWith("xls"))
        {
            workbook = new HSSFWorkbook();
        } else
        {
            try
            {
                throw new Exception("invalid file name, should be xls or xlsx");
            } catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        Sheet sheet = workbook.createSheet(title);
        CellStyle style = workbook.createCellStyle();

        // 列名
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++)
        {
            Cell cell = row.createCell(i);
            sheet.setColumnWidth(i, 5000);
//            style.setAlignment(CellStyle.ALIGN_CENTER);
            cell.setCellValue(headers[i]);
        }

        Iterator<Map> it = dataset.iterator();
        int index = 0;
        while (it.hasNext())
        {
            index++;
            row = sheet.createRow(index);

            Map map = it.next();//当前这个list集合中的map
//            logger.info(map.toString());

            Set<String> mapKey = (Set<String>)map.keySet();//获取当前这个map的键的set集合
//            logger.info(mapKey.toString());
            Iterator<String> iterator = mapKey.iterator();
//            logger.info(iterator.toString());
            int num  = 0;
            while(iterator.hasNext()){
                Cell cell = row.createCell(num);
                num++;
                String key = iterator.next();//这个iterator.next就是这个map中的key
                //为保证map有序用linkedhashmap
//                LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
//                logger.info(key);
                Object obj = map.get(key);
                if (obj instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    cell.setCellValue(sdf.format(obj));
                } else if (obj instanceof Integer)
                {
                    cell.setCellValue((Integer) obj);
                } else if (obj instanceof Double)
                {
                    cell.setCellValue((Double) obj);
                } else
                {
                    cell.setCellValue((String) obj);
                }
            }
        }
        FileOutputStream fos;
        try
        {
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            flag = true;
        } catch (FileNotFoundException e)
        {
//            logger.info("文件不存在");
            flag = false;
            e.printStackTrace();
        } catch (IOException e)
        {
//            logger.info("文件写入错误");
            flag = false;
            e.printStackTrace();

        }
        return flag;
    }


    /**
     * 改造后的方法
     *
     */


    public static boolean exportMap(String excelName, String title, String[] headers, List<LinkedHashMap<String,Object>> dataset, String pattern, HttpServletResponse response) throws IOException {
//        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long milliSecond = System.currentTimeMillis();
        String fileName = excelName + "-" + milliSecond + ".xls";
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/x-xls;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        boolean flag = false;
        Workbook workbook = null;
        if (fileName.endsWith("xlsx"))
        {
            workbook = new XSSFWorkbook();
        } else if (fileName.endsWith("xls"))
        {
            workbook = new HSSFWorkbook();
        } else
        {
            try
            {
                throw new Exception("invalid file name, should be xls or xlsx");
            } catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        Sheet sheet = workbook.createSheet(title);
        CellStyle style = workbook.createCellStyle();

        // 列名
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++)
        {
            Cell cell = row.createCell(i);
            sheet.setColumnWidth(i, 5000);
//            style.setAlignment(CellStyle.ALIGN_CENTER);
            cell.setCellValue(headers[i]);
        }

//        Iterator<Map> it = dataset.iterator();quchu
        Iterator<LinkedHashMap<String, Object>> it = dataset.iterator();

        int index = 0;
        int judgecount = 0;
        while (it.hasNext())
        {
            index++;
            judgecount++;
            row = sheet.createRow(index);
            LinkedHashMap<String, Object> linkedHashMap = it.next();
            Set<String> linkkey = linkedHashMap.keySet();

            Iterator<String> keyiterator = linkkey.iterator();//每一行key的集合
            int a = 0;
            Cell cell1 = row .createCell(a);
            a++;
            if (judgecount == 1){
                cell1.setCellValue(index);//新增添加序号
            }
            while (keyiterator.hasNext()){
                Cell cell = row.createCell(a);
                a++;
                if (judgecount == 1){
                    judgecount--;
                }

                String link_key = keyiterator.next();
                Object obj = linkedHashMap.get(link_key);
                if (obj instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    cell.setCellValue(sdf.format(obj));
                } else if (obj instanceof Integer)
                {
                    cell.setCellValue((Integer) obj);
                } else if (obj instanceof Double)
                {
                    cell.setCellValue((Double) obj);
                } else if (obj instanceof BigDecimal){
                    int i = ((BigDecimal) obj).intValue();
                    cell.setCellValue(i);
                } else
                {
                    cell.setCellValue((String) obj);
                }

            }
        }
        FileOutputStream fos;
        try
        {
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            flag = true;
        } catch (FileNotFoundException e)
        {
//            logger.info("文件不存在");
            flag = false;
            e.printStackTrace();
        } catch (IOException e)
        {
//            logger.info("文件写入错误");
            flag = false;
            e.printStackTrace();

        }
        return flag;
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

poi 导出excel工具类包含导出内容为List<Map<String,Object>>,List<List<Object>> 的相关文章

随机推荐

  • 在matlab中实现图像的自相关和互相关

    图像的自相关 clear I1 imread lenna bmp bmp 输入图像1 参考图像 I1 I1 1 figure 1 显示输入图像1 colormap gray 255 image I1 axis off FI1 fft2 I1
  • XCode14 & iOS16适配 pod签名

    一 iOS16手机开启开发者模式 developer mode disable iOS16手机未打开开发者模式时 1 Xcode 无法选中 iOS16的设备 报错 developer mode disable 2 无法打开升级前编译的App
  • 解决 Axios 跨域问题,轻松实现接口调用

    跨域是指访问另外一个域的资源 由于浏览器的同源策略 默认情况下使用 XMLHttpRequest 和 Fetch 请求时是不允许跨域的 跨域的根本原因是浏览器的同源策略 这是由浏览器对 JavaScript 施加的安全限制 Axios 跨域
  • 使用python简单创建自动点击脚本,使用的是pyautogui

    所有代码在最后面 首先引入包 首先引入包 import pyautogui 鼠标控制包 import time 时间包 后面要用 然后获取需要点击的坐标 for i in range 5 通过循环加延迟 获取鼠标位置 mouse pyaut
  • 推荐 9 个经典前后端分离项目

    前后端分离是现在主流的架构设计模式 它初衷是用 单一职责 原则把代码质量提上去从而达到节省人力和减少沟通时的信息损失的目的 本文推荐九个前后端分离的开源项目 都是采用最流行的技术栈 本文推荐的开源项目已经收录到 Awesome GitHub
  • 黑苹果Mac系统快捷键修改

    由于苹果机的键盘和普通PC机的键盘不同 因此苹果机的快捷键也会与普通PC不同 这对于我们这些经常使用键盘的人来说非常不便 下面附上两者的不同 普通键盘 苹果键盘 修改快捷键 我推荐的软件是KeyBindingsEditor 它很好用 另外需
  • The Evaluation of Language Model (语言模型的性能评价方法 Perplexity)

    The Evaluation of Language Model 语言模型的性能评价 语言模型 Language Model 以下简称LM 直观理解 用于判断一句话是否从语法上通顺 Question 1 训练好的LM效果是好还是坏 如何评价
  • L2-014 列车调度 (25 分)详解

    火车站的列车调度铁轨的结构如下图所示 两端分别是一条入口 Entrance 轨道和一条出口 Exit 轨道 它们之间有N条平行的轨道 每趟列车从入口可以选择任意一条轨道进入 最后从出口离开 在图中有9趟列车 在入口处按照 8 4 2 5 3
  • kali渗透--msf简单使用

    使用MSF Metasploit 利用MS12 020 RDP远程代码执行漏洞 实验环境准备 1 一台 winXP 作为受害者 最好拍摄好一个快照 IP 10 1 1 2 2 kali 作为攻击者 IP 10 1 1 1 3 将攻击者和受害
  • 常用命令图解 & & git 错误 fatal: Not a valid object name: ‘master‘.

    亲测可用 若有疑问请私信 常用命令图解 转自Git 常用命令详解 二 阳光岛主的博客 CSDN博客 git命令 Git 是一个很强大的分布式版本管理工具 它不但适用于管理大型开源软件的源代码 如 linux kernel 管理私人的文档和源
  • Python画各种爱心

    目录 一行代码画爱心 拆解 输出 I U 填充型 动态画红心 桃心 线性 立体红心 玫瑰 树 一行代码画爱心 print n join join Love x y len Love if x 0 05 2 y 0 1 2 1 3 x 0 0
  • 学科竞赛管理系统服务器错误,学科竞赛管理系统

    系统功能模块如下 1 平台首页 整个平台首页分为政策文件 竞赛列表 在线报名 成果展示 通知公告 新闻中心 联系方式 系统登录 下载中心 快速导航等功能模块 所有模块内容全部支持系统后台进行添加 编辑 删除等操作 2 竞赛管理 1 竞赛项目
  • TensorRT/parsers/caffe/caffeParser/caffeParser.h源碼研讀

    TensorRT parsers caffe caffeParser caffeParser h源碼研讀 前言 TensorRT parsers caffe caffeParser caffeParser h delete this std
  • mysql中的枚举enum_mysql中枚举类型之enum详解

    enum类型就是我们常说的枚举类型 它的取值范围需要在创建表时通过枚举方式 一个个的列出来 显式指定 对1至255个成员的枚举需要1个字节存储 对于255至65535个成员 需要2个字节存储 最多允许有65535个成员 先通过sql语句创建
  • Latex 算法Algorithm

    在计算机科学当中 论文当中经常需要排版算法 相信大家在读论文中也看见了很多排版精美的算法 本文就通过示例来简要介绍一下 algorithms 束的用法 该束主要提供了两个宏包 包含两种进行算法排版的环境 algorithm 和 algori
  • java base64转文件_java之文件与base64字符之间的相互转换

    package cn xuanyuan util import java io File import java io FileInputStream import java io FileOutputStream import sun m
  • 大数据 机器学习 分类算法_13种用于数据科学的机器学习分类算法及其代码

    大数据 机器学习 分类算法 The roundup of most common classification algorithms along with their python and r code 吨 他的Roundup与他们的Pyt
  • WSL安装JDK8

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 下载地址 JDK URL https www oracle com technetwork java javase downloads jdk8 downloads 213
  • 压缩感知进阶——有关稀疏矩阵

    上一篇 初识压缩感知Compressive Sensing 中我们已经讲过了压缩感知的作用和基本想法 涉及的领域 本文通过学习陶哲轩对compressive sensing CS 的课程 对压缩感知做进一步理解 针对其原理做出讲解 本文较为
  • poi 导出excel工具类包含导出内容为List<Map<String,Object>>,List<List<Object>>

    导入jar