excel表格的导入和导出(Java+element)

news2025/6/17 12:57:05

本项目是前端vue3,后端springboot开发
需求为:前端导入表格,后端处理表格存储数据,点击按钮可以导出表格。

上传效果:前端点击上传按钮,会跳出选择文件框,选择文件,点击上传。
导出效果:前端点击导出按钮,会跳出下载框,选择位置自动下载。

上传效果图:
在这里插入图片描述
下载效果图:
在这里插入图片描述

一、上传excel前端代码

            <el-upload
              ref="file"
              class="upload-demo"
              :limit="1"
              accept=".xlsx, .xls"
              action="http://localhost:8081/admin/perform/importexcel"
              auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>

              <el-button
                class="ml-3"
                style="margin-left: 20px"
                type="success"
                @click="submitUpload"
              >
                上传文件
              </el-button>

              <span style="color: red; margin-left: 10px"
                >仅允许导入xls、xlsx格式文件。</span
              >
            </el-upload>

import { ref, reactive, computed } from "vue"
import { ElMessage, UploadInstance } from "element-plus"

const file = ref<UploadInstance>()

const submitUpload = () => {
  file.value!.submit()
  ElMessage({
    message: "上传成功",
    type: "success",
  })
  window.location.reload()
}

效果图
在这里插入图片描述

二、上传excel后端代码

Controller层

    @PostMapping("/importexcel")
    public Result importData(MultipartFile file) throws Exception {
        return performService.importData(file.getInputStream());
    }

Service层

  @Override
    public Result importData(InputStream inputStream) throws IOException {
    // Perform根据自己表格的表头创建的实体,要意义对应
        List<Perform> res = new ArrayList<>();
        try {
            ins = (FileInputStream) inputStream;
            //true xls文件,false xlsx文件
            Workbook workbook = null;
            // XSSFWorkbook instance of HSSFWorkbook 所以通用
            workbook = new XSSFWorkbook(ins);
            //获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //获取表头
            Row rowHead = sheet.getRow(0);
            //判断表头是否正确
            if (rowHead.getPhysicalNumberOfCells() < 1) {
                return Result.error("表头错误");
            }
            //获取数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //获取第一行的用户信息
                Row row = sheet.getRow(i);

                String tId;
                if (row.getCell(0) == null) {
                    tId = "";
                    row.createCell(0).setCellValue(tId);
                } else {
                    //先设置为字符串再作为数字读出来
                    row.getCell(0).setCellType(CellType.STRING);
                    tId = row.getCell(0).getStringCellValue();
                }

                String tName;
                if (row.getCell(1) == null) {
                    tName = "";
                    row.createCell(1).setCellValue(tName);
                } else {
                    tName = row.getCell(1).getStringCellValue();
                }

                String tDept;
                if (row.getCell(2) == null) {
                    tDept = "";
                    row.createCell(2).setCellValue(tDept);
                } else {
                    tDept = row.getCell(2).getStringCellValue();
                }
				....................
               Perorm perform=new Perform()
               xxxset创建实体
               
                System.out.println(perform);
                res.add(perform);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        new Thread(() -> {
            //批处理比较快
            batchInsert(res);
        }).start();
        return Result.success(res);

    }
      /**
     * 批量插入更快
     *
     * @param performList
     */
    private void batchInsert(List<Perform> performList) {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        performList.stream().forEach(perform -> {
            performMapper.insert(perform);
        });
        sqlSession.commit();
        sqlSession.clearCache();
    }

三、下载excel前端代码

                <el-button
                  type="warning"
                  style="width: 100px"
                  @click="exportInfo()"
                >
            <a href="http://localhost:8081/admin/perform/exportexcel"
                    >导出</a
                  >
                </el-button>
const exportInfo = () => {
  ElMessage({
    message: "请稍等",
    type: "warning",
  })
}

四、下载excel后端代码

Controller层

    /**
     * 导出表格
     *
     * @return
     */
    @GetMapping("/exportexcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        performService.exportExcel(response);
    }

Service层

    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        System.out.println("导出表格");
        List<Perform> list = performMapper.selectList(new QueryWrapper<>());
        String sheetName = "教师业绩表";
        Map<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("tId", "教师工号");
        titleMap.put("tName", "教师姓名");
		.....根据自己的表头来
        ExportExcel.excelExport(response, list, titleMap, sheetName);
    }

ExportExcel类:

 package com.performance.back.common.utils;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.performance.back.admin.dao.entity.Perform;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExportExcel
 * @Descriotion TODO
 * @Author nitaotao
 * @Date 2022/11/14 11:55
 * @Version 1.0
 **/
public class ExportExcel {
    private ExportExcel() {
    }

    /***
     * 工作簿
     */
    private static HSSFWorkbook workbook;

    /***
     * sheet
     */
    private static HSSFSheet sheet;
    /***
     * 标题行开始位置
     */
    private static final int TITLE_START_POSITION = 0;

    /***
     * 时间行开始位置
     */
    private static final int DATEHEAD_START_POSITION = 1;

    /***
     * 表头行开始位置
     */
    private static final int HEAD_START_POSITION = 0;

    /***
     * 文本行开始位置
     */
    private static final int CONTENT_START_POSITION = 1;


    /***
     *
     * @param sheetName
     *        sheetName
     */
    private static void initHSSFWorkbook(String sheetName) {
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet(sheetName);
        sheet.setDefaultColumnWidth(15);
    }

    /**
     * 生成标题(第零行创建)
     *
     * @param titleMap  对象属性名称->表头显示名称
     * @param sheetName sheet名称
     */
    private static void createTitleRow(Map<String, String> titleMap, String sheetName) {
        CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);
        sheet.addMergedRegion(titleRange);
        HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(sheetName);
    }

    /**
     * 创建时间行(第一行创建)
     *
     * @param titleMap 对象属性名称->表头显示名称
     */
    private static void createDateHeadRow(Map<String, String> titleMap) {
        CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);
        sheet.addMergedRegion(dateRange);
        HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);
        HSSFCell dateCell = dateRow.createCell(0);
        dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
    }

    /**
     * 创建表头行(第二行创建)
     *
     * @param titleMap 对象属性名称->表头显示名称
     */
    private static void createHeadRow(Map<String, String> titleMap) {
        // 第1行创建
        HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);
        headRow.setHeight((short) 900);
        int i = 0;
        for (String entry : titleMap.keySet()) {
            // 生成一个样式
            HSSFCellStyle style = workbook.createCellStyle();
            // 设置这些样式
            style.setAlignment(HorizontalAlignment.CENTER);//水平居中
            style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

            // 设置边框
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            // 自动换行
            style.setWrapText(true);

            // 生成一个字体
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 10);
            font.setColor(IndexedColors.WHITE.index);
            font.setBold(false);
            font.setFontName("宋体");

            // 把字体 应用到当前样式
            style.setFont(font);
            //style设置好后,为cell设置样式

            HSSFCell headCell = headRow.createCell(i);
            headCell.setCellValue(titleMap.get(entry));
            if (i > 14) {
                // 背景色
                style.setFillForegroundColor(IndexedColors.BLUE.index);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillBackgroundColor(IndexedColors.BLUE.index);
            } else if (i > 10) {
                style.setFillForegroundColor(IndexedColors.BLACK.index);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillBackgroundColor(IndexedColors.BLACK.index);
            } else if (i > 7) {
                style.setFillForegroundColor(IndexedColors.BLUE.index);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillBackgroundColor(IndexedColors.BLUE.index);
            } else if (i >4) {
                style.setFillForegroundColor(IndexedColors.RED.index);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillBackgroundColor(IndexedColors.RED.index);
            } else {
                style.setFillForegroundColor(IndexedColors.GREEN.index);
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillBackgroundColor(IndexedColors.GREEN.index);
            }
            headCell.setCellStyle(style);
            i++;
        }
    }

    /**
     * @param dataList 对象数据集合
     * @param titleMap 表头   信息
     */
    private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {
        try {
            int i = 0;
            // 生成一个样式
            HSSFCellStyle style = workbook.createCellStyle();
            // 设置这些样式
            style.setAlignment(HorizontalAlignment.CENTER);//水平居中
            style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中

            // 设置边框
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            // 自动换行
            style.setWrapText(true);

            // 生成一个字体
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 10);
            font.setColor(IndexedColors.BLACK.index);
            font.setBold(false);
            font.setFontName("宋体");

            // 把字体 应用到当前样式
            style.setFont(font);
            //style设置好后,为cell设置样式

            for (Object obj : dataList) {
                HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);
                int j = 0;
                for (String entry : titleMap.keySet()) {
                    //属性名驼峰式
                    String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1);
//                    System.out.println("调用" + method + "方法");
                    //反射调用
                    Method m = obj.getClass().getMethod(method, null);
                    Object value = m.invoke(obj, null);
                    HSSFCell textcell = textRow.createCell(j);
                    if (ObjectUtils.isNotEmpty(value)) {
                        textcell.setCellValue(value.toString());
                    } else {
                        textcell.setCellValue("");
                    }
                    textcell.setCellStyle(style);
                    j++;
                }
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自动伸缩列(如非必要,请勿打开此方法,耗内存)
     *
     * @param size 列数
     */
    private static void autoSizeColumn(Integer size) {
        for (int j = 0; j < size; j++) {
            sheet.autoSizeColumn(j);
        }
    }



    public static void excelExport( HttpServletResponse response, List<Perform> list, Map<String, String> titleMap, String sheetName) throws IOException {
        //生成表格的不可重复名
        Date date = new Date();

        // 初始化workbook
        initHSSFWorkbook(sheetName);
        // 表头行
        createHeadRow(titleMap);
        // 文本行
        createContentRow(list, titleMap);

        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        //设置响应头,
        response.setHeader("Content-disposition", "attachment; filename=teacher.xls");
        response.setContentType("application/msexcel");
        workbook.write(output);
        output.close();
    }
}

因为自己淋过雨,所以想为别人撑把伞

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言CRC-16 IBM格式校验函数

C语言CRC-16 IBM格式校验函数 CRC-16校验产生2个字节长度的数据校验码&#xff0c;通过计算得到的校验码和获得的校验码比较&#xff0c;用于验证获得的数据的正确性。基本的CRC-16校验算法实现&#xff0c;参考&#xff1a; C语言标准CRC-16校验函数。 不同厂家通过对输入数…

鸿鹄工程项目管理系统源码 Spring Cloud+Spring Boot+Mybatis+Vue+ElementUI+前后端分离构建工程项目管理系统

鸿鹄工程项目管理系统 Spring CloudSpring BootMybatisVueElementUI前后端分离构建工程项目管理系统 1. 项目背景 一、随着公司的快速发展&#xff0c;企业人员和经营规模不断壮大。为了提高工程管理效率、减轻劳动强度、提高信息处理速度和准确性&#xff0c;公司对内部工程管…

这家年销售额309亿的Tier 1,要谈一场千亿新生意

跨入2023年&#xff0c;智能汽车软件赛道更热闹了。 相较于传统汽车开发模式&#xff0c;软件属于分布式ECU工程开发的一部分&#xff0c;由一级供应商作为黑盒提供&#xff0c;软件开发成本等被认为是硬件系统成本的一部分&#xff0c;没有实现单独定价。 如今&#xff0c;“…

Redis 如何使用 RedisCluster 构建高可用集群架构?

文章目录Redis 如何使用 RedisCluster 构建高可用集群架构&#xff1f;什么是 Redis Cluster&#xff1f;哈希槽&#xff08;hash slot&#xff09;一致性保证&#xff08;consistency guarantees&#xff09;如何构建 Redis Cluster&#xff1f;配置环境构建 A&#xff0c;A1 …

int(1) 和 int(10)区别

有个表的要加个user_id字段&#xff0c;user_id字段可能很大&#xff0c; alter table xxx ADD user_id int(1)。 int(1)怕是不够用吧&#xff0c;接下来是一通解释。 我们知道在mysql中 int占4个字节&#xff0c;那么对于无符号的int&#xff0c;最大值是2^32-1 4294967295&a…

一文弄懂Python中的sort和sorted函数

1. 引言 Python中的 sort()和sorted()函数主要用于按升序或降序对数据进行排序。在本文中比较用于列表时&#xff0c;两个函数在编程和语法上的差异。 闲话少说&#xff0c;我们直接开始吧&#xff01; 2. Sort()函数基本用法 用于列表排序的sort函数的语法如下&#xff1a…

java equals和==的区别

目录一、equals1.前言2.重写equals方法二、三、equals和的区别一、equals 1.前言 **当用equals来比较两个引用数据类型时默认比较的是它们的地址值&#xff0c;比如创建两个成员变量完全相同对象A和对象B两个进行比较&#xff0c;比较的是两个对象的地址值是否相等&#xff0c…

从spring boot泄露到接管云服务器平台

0x1前言 在打野的时候意外发现了一个站点存在spring boot信息泄露&#xff0c;之前就有看到一些文章可以直接rce啥的&#xff0c;今天刚好试试。通过敏感信息发现存在accesskey泄露&#xff0c;就想直接通过解密&#xff0c;获取敏感信息&#xff0c;接管云平台。 首先说下这个…

Linux服务器如何清除dns缓存

Linux服务器如何清除dns缓存 DNS缓存是一个临时数据库&#xff0c;用于存储已解释的DNS查询信息。换句话说&#xff0c;每当你访问网站时&#xff0c;你的操作系统和网络浏览器都会保留域名和相应IP地址的记录。 这消除对远程DNS服务器重复查询&#xff0c;并允许你的操作系统…

【实验报告】实验三、图像复原

1. 实验目的 (1) 理解退化模型。 (2) 掌握常用的图像复原方法。 2. 实验内容 (1) 模拟噪声的行为和影响的能力是图像复原的核心。 (2) 空域滤波 实验一 1. 1 产生至少 2 种不同类型的噪声&#xff0c;并绘制原图像、加噪后图像及对应直方图于 一个图形窗口中[subplot(m…

用GPT-4写代码不用翻墙了?Cursor告诉你:可以~~

目录 一、介绍 二、使用方法 三、其他实例 1.正则表达式 2.自动化测试脚本 3.聊聊技术 一、介绍 Cursor主要功能是根据用户的描述写代码或者进行对话&#xff0c;对话的范围仅限技术方面。优点是不用翻墙、不需要账号。Cursor基于GPT模型&#xff0c;具体什么版本不祥&#…

ChatGPT文本框再次升级,打造出新型操作系统

在ChatGPT到来之前&#xff0c;没有谁能够预见。但是&#xff0c;它最终还是来了&#xff0c;并引起了不小的轰动&#xff0c;甚至有可能颠覆整个行业。 从某种程度上说&#xff0c;ChatGPT可能是历史上增长最快的应用程序&#xff0c;仅在两个多月就拥有了1亿多活跃用户&…

2023年4月企业内部定制课程简章

2023年4月企业内部定制课程简章 》》数据治理内训 数据管理基础 数据处理伦理 数据治理 数据架构 数据建模和设计 数据安全 数据集成和互操作 文件和内容管理 参考数据和主数据 数据仓库和商务智能 元数据管理 数据质量 大数据和数据科学 数据管理成熟度评估 数据管理组织与…

js基础之Promise(全面+手写实现)

1. 是什么 Promise是一种异步编程的解决方案&#xff0c;用于处理异步操作并返回结果。 主要作用是解决回调函数嵌套&#xff08;回调地狱&#xff09;的问题&#xff0c;使异步操作更加清晰、易于理解和维护。 2. 怎么用 Promise有三种状态&#xff1a;pending&#xff08;…

(大数据开发随笔8)Hadoop 3.3.x分布式环境部署——补充知识

索引克隆虚拟机SSH免密登录ssh简介免密登录scp命令时间同步克隆虚拟机 克隆&#xff1a;注意要分开放置三个虚拟机的位置 修改克隆机的ip地址 vi /etc/sysconfig/network-scripts/ifcfg-ens33——IPADDR重启网络 systemctl restart networkip addr 查看ip地址 修改克隆机的主…

【STM32学习】直接存储器访问——DMA

【STM32学习】直接存储器访问——DMA零、参考一、对DMA的理解二、DMA通道优先级三、DMA通道x传输数量寄存器(DMA_CNDTRx)四、DMA缓冲区设计零、参考 一个严谨的STM32串口DMA发送&接收&#xff08;1.5Mbps波特率&#xff09;机制 【组件】通用环形缓冲区模块 上述是我的参考…

ServletContext 对象

1.共享数据 ServletContext 对象 先调用对象&#xff0c;获取对象&#xff0c;往里面存数据 package com.kuang.servlet;import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.…

Pandas.read_excel详解

文章目录基础知识语法参数详解-index_col参数详解-header参数详解-usecols参数详解-dtype其他参数多表读取顺带提一句如何用pandas写数据到excel基础知识 pandas 可以读取多种的数据格式&#xff0c;针对excel来说&#xff0c;可以使用read_excel()读取数据&#xff0c;如下&a…

实现在SpringBoot项目中使用腾讯云发送短信

在一些项目中总会不可避免的要用到短信服务&#xff0c;比如发送验证码等&#xff0c;那么如何进行短信的发送呢&#xff0c;我们这就来捋一捋&#xff0c;我这里采用的是腾讯云的短信服务。其他的云服务也大致一样。 第一步、申请腾讯云的短信服务并配置基本信息 首先进入腾讯…

2023年Q1京东大家电销售数据分析(京东行业大盘销量查询)

2023年第一季度&#xff0c;大家电线上市场的涨势有点放缓&#xff0c;相较于去年的涨幅&#xff0c;今年有收敛不少。下面&#xff0c;我们以京东平台的数据作为线上市场表现的参考。 根据鲸参谋数据显示&#xff0c;今年Q1季度大家电在京东的累计销量超过1600万件&#xff0c…