java导出数据到excel表中

java导出数据到excel表中

  • 环境说明
  • 项目结构
    • 1.controller层
    • 2.service层
    • 3.实现层
    • 4.工具类:ExcelUtil.java
    • 5.ProductModel.java类
  • 使用的Maven依赖
  • postman请求展示,返回内容需要前端接收
  • 浏览器接收说明(如果下载下来的为zip类型,记得将后缀改为:xlsx,再打开)
    • 更改后再下载
    • 查看文件

环境说明

jdk1.8,springboot2.5.3

项目结构

1.controller层

package com.example.pdf.controller;

import com.example.pdf.service.ExportDataToExcelService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping(value = "export")
public class ExportDataToExcelController {

    @Resource
    private ExportDataToExcelService exportDataToExcelService;

    @GetMapping("dataToExcel")
    public void dataToExcel(HttpServletResponse response) {
        exportDataToExcelService.dataToExcel(response);

    }
}


2.service层

package com.example.pdf.service;

import javax.servlet.http.HttpServletResponse;

public interface ExportDataToExcelService {
    /**
     * 导出数据到excel表中
     *
     * @param response
     */
    void dataToExcel(HttpServletResponse response);
}

3.实现层

package com.example.pdf.service.impl;

import com.example.pdf.model.ProductModel;
import com.example.pdf.service.ExportDataToExcelService;
import com.example.utils.ExcelUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExportDataToExcelServiceImpl implements ExportDataToExcelService {
    /**
     * 导出数据到excel表中
     *
     * @param response
     */
    @Override
    public void dataToExcel(HttpServletResponse response) {

        List<ProductModel> models = new ArrayList<>();

        // 模拟5条数据
        ProductModel p1 = new ProductModel("矿泉水", 2, "瓶");
        ProductModel p2 = new ProductModel("凤梨", 4, "个");
        ProductModel p3 = new ProductModel("笔记本", 1, "台");
        ProductModel p4 = new ProductModel("球鞋", 1, "双");
        ProductModel p5 = new ProductModel("超跑", 10, "辆");

        // 将模拟数据存入集合
        models.add(p1);
        models.add(p2);
        models.add(p3);
        models.add(p4);
        models.add(p5);

        try {
            // 导出数据
            ExcelUtil.export(response, ProductModel.class, models, "商品列表", ExcelUtil.getStyleStrategy());
        } catch (Exception e) {
            System.out.println("商品列表导出异常!");
        }
    }
}


4.工具类:ExcelUtil.java

package com.example.utils;

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.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param response
     * @param head
     * @param data
     * @param sheetName
     * @param horizontalCellStyleStrategy
     */
    public static void export(HttpServletResponse response, Class head, List data, String sheetName, HorizontalCellStyleStrategy horizontalCellStyleStrategy) throws IOException {
        //给定导出实体类
        EasyExcel.write(response.getOutputStream(), head)
                //给定工作表名称
                .sheet(sheetName)
                //给定样式
                .registerWriteHandler(horizontalCellStyleStrategy)
                //给定导出数据
                .doWrite(data);
    }

    /**
     * 设置生成excel样式 去除默认表头样式及设置内容居中,如有必要可重载该方法给定参数配置不同样式
     *
     * @return HorizontalCellStyleStrategy
     */
    public static HorizontalCellStyleStrategy getStyleStrategy() {
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置单元格边框
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(false);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        //头策略使用默认
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }

}

5.ProductModel.java类

package com.example.pdf.model;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.Data;

@Data
public class ProductModel {

    public ProductModel(String productName, Integer number, String unit) {
        this.productName = productName;
        this.number = number;
        this.unit = unit;
    }

    @ColumnWidth(15)
    @ExcelProperty("商品名称")
    private String productName;

    @ColumnWidth(15)
    @ExcelProperty("商品数量")
    private Integer number;

    @ColumnWidth(15)
    @ExcelProperty("商品单位")
    private String unit;
}

使用的Maven依赖

<!-- lombok插件 -->
        <dependency>
            <artifactId>lombok</artifactId>
            <groupId>org.projectlombok</groupId>
            <scope>provided</scope>
            <version>1.18.10</version>
        </dependency>
        
<!-- alibaba Excel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>

postman请求展示,返回内容需要前端接收

在这里插入图片描述

浏览器接收说明(如果下载下来的为zip类型,记得将后缀改为:xlsx,再打开)

在这里插入图片描述

更改后再下载

在这里插入图片描述

查看文件

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/561399.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

矽塔SA8321 单通道 2.7-12.0V 持续电流 3.0A H 桥驱动芯片

描述 SA8321是为消费类产品&#xff0c;玩具和其他低压或者电池供电的运动控制类应用提供了一个集成的电机驱动器解决方案。此器件能够驱动一个直流无刷电机&#xff0c;由一个内部电荷泵生成所需的栅极驱动电压电路和4个功率 NMOS组成H桥驱动&#xff0c;集成了电机正转/反…

polkit服务启动失败

使用systemctl 命令报错 Authorization not available. Check if polkit service is running or see debug message for more information. 查看polkit状态是失败的状态&#xff0c;报缺少libstdc.so.6 systemctl status polkit 需要安装libstdc.so.6库 先加载所有安装包 …

网络安全产品---堡垒机

what 在网上搜索 运维审计与风险控制系统就是是堡垒机 我认为的堡垒机就是提供高效运维、认证管理、访问控制、安全审计和报表分析功能的云服务设备 实现高效运维的同时最大程度控制运维风险。 how 能够对运维人员维护过程进行全面跟踪、控制、记录、回放 支持细粒度配置…

最新Java面试题3【2024中级】

互联网大厂面试题 1&#xff1a;阿里巴巴Java面试题 2&#xff1a;阿里云Java面试题-实习生岗 3&#xff1a;腾讯Java面试题-高级 4&#xff1a;字节跳动Java面试题 5&#xff1a;字节跳动Java面试题-大数据方向 6&#xff1a;百度Java面试题 7&#xff1a;蚂蚁金服Java…

SpringMVC02:注解模式

SpringMVC02&#xff1a;注解模式 文章目录 SpringMVC02&#xff1a;注解模式前言一、代码编写&#xff1a;1. 编写jsp页面2. 在web.xml中&#xff0c;注册DispatcherServlet&#xff08;须要绑定SpringMVC配置文件&#xff09;3. 编写SpringMVC 的 配置文件4. 编写Controller类…

医学临床预测模型发展新趋势-并联式

医学临床预测模型发展新姿势-并联式 现有的预测模型是对单个结局指标进行分类或者回归&#xff0c;得出最终的结论&#xff0c;而辅助医生进行临床决策。众所周知&#xff0c;临床决策过程中&#xff0c;医生通常会考虑多个结局指标来做出最终的决策&#xff1b;临床研究中也通…

【JavaScript编程实操14】DOM实操_回到顶部

前言 本次主要是针对Javascript阶段的DOM实操方面的练习&#xff0c;本次主要实现当页面内容过多时&#xff0c;可以点击按钮&#xff0c;快速回到页面顶部的效果。这次的实现逻辑比较简单&#xff0c;主要是应用函数实现页面的回到顶部功能&#xff0c;this.scrollTo(0, 0)可以…

万界星空科技机器人组装行业MES系统

一、为什么选择万界星空科技&#xff1f; 万界星空科技作为一家在云MES系统的研发、生产自动化方面拥有很多年行业经验的科技型企业&#xff0c;多年来专注于云MES系统的研发与技术支持服务&#xff0c;目前已成为国内知名的智能制造整体解决方案提供商。 公司凝聚了一支经验…

Redis系列之Cluster集群搭建

在上一篇博客&#xff0c;我们学习Redis哨兵Sentinel集群的搭建&#xff0c;redis的哨兵模式提供了比如监控、自动故障转移等高可用方案&#xff0c;但是这种方案&#xff0c;容量相对固定&#xff0c;要进行持续扩容或者数据分片就不适合&#xff0c;所以有另外一种更复杂的集…

线性代数基础3 行列式

行列式 行列式其实在机器学习中用的并不多&#xff0c;一个矩阵必须是方阵&#xff0c;才能计算它的行列式 行列式是把矩阵变成一个标量 import numpy as np A np.array([[1,3],[2,5]]) display(A) print(矩阵A的行列式是&#xff1a;\n,np.linalg.det(A))array([[1, 3],[2, …

视频质量评价 PSNR 算法详细介绍

PSNR PSNR(Peak Signal-to-Noise Ratio,峰值信噪比)是一种常用的评价图像质量的指标,尤其在图像压缩和图像处理领域。它基于最大可能的图像信号功率和图像的噪声功率之间的比率,通常用于衡量图像恢复或图像压缩算法的效果。 原理 PSNR是基于MSE(Mean Squared Error,均…

『 论文解读 』大语言模型(LLM)代理能够自主地利用1 day漏洞,利用成功率竟高达87%,单次利用成本仅8.8美元

1. 概览 该论文主要展示了大语言模型LLM代理能够自主利用现实世界的 1 day 漏洞。研究我发现&#xff0c; GPT-4 在提供了CVE描述的情况下&#xff0c;能够成功利用 87% 的漏洞。 这与其他测试模型&#xff08;如 GPT-3.5 和其他开源 LLM &#xff09;以及开源漏洞扫描器&…

Tomcat核心组件深度解析

Server组件 Service组件 连接器Connector组件 容器Container组件

【hackmyVM】whitedoor靶机

文章目录 信息收集1.IP地址2.端口探测nmapftp服务 3.访问主页 漏洞利用1.反弹shell2.尝试提权3.base64解密 提权1.切换用户2.john爆破3.切换Gonzalo用户4.vim提权 信息收集 1.IP地址 ┌─[✗]─[userparrot]─[~] └──╼ $fping -ag 192.168.9.0/24 2> /dev/null192.168…

【小程序】IOS wx小程序解压获取源文件

根据自己手机的系统&#xff0c;获取wx小程序的缓存目录 一、微信小程序文件存放路径 安卓&#xff1a; /data/data/com.tencent.mm/MicroMsg/{{user哈希值}}/appbrand/pkg/iOS越狱&#xff1a; /User/Containers/Data/Application/{{系统UUID}}/Library/WechatPrivate/{{user…

PCIe复位方式介绍

前言 PCIe总线中定义了四种复位名称&#xff1a;冷复位&#xff08;Cold Reset&#xff09;、暖复位&#xff08;Warm Reset&#xff09;、热复位&#xff08;Hot Reset&#xff09;和功能层复位&#xff08;Function-Level Reset&#xff0c;FLR&#xff09;。其中FLR是PCIe …

RocketMQ学习笔记

kafka适合于日志收集的场景&#xff08;不需要太多topic&#xff1b;topic下面的partition多了会造成写文件的速度变慢&#xff0c;因为要造很多索引&#xff09; RocketMQ更适合于电商场景&#xff08;适用于topic特别多的情况&#xff09; 快速安装RocketMQ RocketMQ的官网…

js 函数节流和函数防抖及区别详解

文章目录 1. 前言2. 函数节流3. 函数防抖4. 总结 1. 前言 浏览器中总是有一些操作非常耗费性能。所以就有了函数节流和函数防抖来提高浏览器性能。 函数节流&#xff1a;频繁触发一个事件时候&#xff0c;每隔一段时间&#xff0c;函数只会执行一次。 函数防抖&#xff1a;当触…

某零售企业招聘管理体系搭建咨询项目

科学岗位分析&#xff0c;改善招聘流程&#xff0c;提高招聘及时率随着公司不断发展壮大&#xff0c;企业规模逐渐增大&#xff0c;部门设置也日益增多&#xff0c;因此对人员的需求也日益提高。但是目前该企业在人员招聘方面逐渐暴露出一些诸如岗位分析不到位、缺乏整体面试计…

Java中对象如何拷贝?

hi&#xff0c;我是程序员王也&#xff0c;一个资深Java开发工程师&#xff0c;平时十分热衷于技术副业变现和各种搞钱项目的程序员~&#xff0c;如果你也是&#xff0c;可以一起交流交流。 今天我们来聊一聊Java中的对象拷贝~ 浅拷贝与深拷贝 在Java中&#xff0c;对象拷贝可…