通过easyexcel导出数据到表格

这篇文章简单介绍一下怎么通过easyexcel做数据的导出,使用之前easyui构建的歌曲列表crud应用,添加一个导出按钮,点击的时候直接连接后端接口地址,在后端的接口完成数据的导出功能。

 

前端页面完整代码

let editingId;
let requestUrl;
let base = "http://localhost:8083";
let pageList = [20, 50, 100, 500, 1000];// 定义一个json对象保存歌曲数据
let data = {};function addHandler() {requestUrl = "/song/insert";$.post(base + requestUrl, {name: "*****",singer: "*****",note: "*****"}, function () {$("#song_list").datagrid("reload");}, "json");
}function editHandler() {let datagrid = $("#song_list");let row = datagrid.datagrid("getSelected");if (editingId != null && editingId != "") {datagrid.datagrid("selectRow", editingId);} else {if (row) {// 获取行索引,这个索引从0开始let rowIndex = datagrid.datagrid("getRowIndex", row);editingId = rowIndex;requestUrl = "/song/updateById";datagrid.datagrid("beginEdit", rowIndex);}}
}function saveHandler() {if (editingId) {// 只有结束编辑才能获取到最新的值$("#song_list").datagrid("endEdit", editingId);$.post(base + requestUrl, data, function (res) {$.messager.show({title: '系统消息',timeout: 5000,showType: 'slide',msg: res.message,});editingId = "";}, "json");}
}function cancelHandler() {// editingId != null条件防止刷新页面带来的问题if (editingId != null && editingId !== "") {$("#song_list").datagrid("cancelEdit", editingId);editingId = "";}
}function exportHandler() {location.href = base + "/song/export";
}function deleteHandler() {let rowData = $("#song_list").datagrid("getSelected");if (rowData) {$.messager.confirm("提示", "删除后数据无法恢复,是否确认删除?", function(bool) {if (bool) {$.get(base + "/song/deleteById/" + rowData.id, {}, function(res) {$.messager.show({title: '系统消息',timeout: 5000,showType: 'slide',msg: res.message,});$("#song_list").datagrid("reload");}, "json");}});} else {$.messager.alert("请选择要删除的数据!", "warning");}
}$(document).ready(function() {let datagrid = $("#song_list").datagrid({url: base + "/song/selectByPage",title: "歌曲列表",height: 810,striped: true,fitColumns: true,singleSelect: true,pagination: true,remoteFilter: true,clientPaging: false,pageSize: pageList[0],pageList: pageList,loadFilter: function(res) {if (res.code == 200) {return res.data;} else {return null;}},onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件data = {id: rowData.id,name: changes.name ? changes.name : rowData.name,note: changes.note ? changes.note : rowData.note,singer: changes.singer ? changes.singer : rowData.singer};},toolbar: [{iconCls: 'icon-add',text: '添加',handler: function() {addHandler();}}, '-', {iconCls: 'icon-edit',text: '修改',handler: function() {editHandler();},}, "-", {iconCls: "icon-save",text: "保存",handler: function() {saveHandler();}}, "-", {iconCls: "icon-cancel",text: "取消",handler: function() {cancelHandler();}}, '-', {iconCls: 'icon-ok',text: '导出',handler: function() {exportHandler();}}, '-', {iconCls: 'icon-delete',text: '删除',handler: function() {deleteHandler();},}],columns: [[{field: 'id', title: 'id', width: 200},{field: 'name', title: 'name', width: 200, editor: "textbox"},{field: 'singer', title: 'singer', width: 200, editor: "textbox"},{field: 'note', title: 'note', width: 200, editor: "textbox"},{field: 'lastUpdateTime', title: 'lastUpdateTime', width: 200},]]});datagrid.datagrid('enableFilter', [{field: 'name',type: 'textbox',op: ['equal', 'contains']}, {field: 'singer',type: 'textbox',op: ['equal', 'contains'],}, {field: 'note',type: 'textbox',op: ['equal', 'contains']}]);});

添加依赖

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.2</version>
</dependency>

修改实体类,添加列注解

package com.example.springboot.entity;import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;import java.io.Serializable;
import java.time.LocalDateTime;/*** 歌曲* @author heyunlin* @version 1.0*/
@Data
@TableName("song")
public class Song implements Serializable {private static final long serialVersionUID = 18L;@ExcelIgnore@TableId(type = IdType.INPUT)private String id;/*** 歌曲名*/@ExcelProperty("歌曲名")private String name;/*** 歌手*/@ExcelProperty("歌手")private String singer;/*** 描述信息*/@ExcelProperty("描述信息")private String note;/*** 最后一次修改时间*/@TableField("last_update_time")@ExcelProperty("最后一次修改时间")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private LocalDateTime lastUpdateTime;
}

参考官网的案例代码,完成后端controller接口具体代码实现

package com.example.springboot.service.impl;import com.alibaba.excel.EasyExcel;
import com.example.springboot.entity.Song;
import com.example.springboot.mapper.SongMapper;
import com.example.springboot.restful.JsonResult;
import com.example.springboot.service.SongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;/*** @author heyunlin* @version 1.0*/
@Service
public class SongServiceImpl implements SongService {private final SongMapper songMapper;@Autowiredpublic SongServiceImpl(SongMapper songMapper) {this.songMapper = songMapper;}// 其他代码...@Overridepublic void export(HttpServletResponse response) {String fileName = "song.xlsx";response.setCharacterEncoding("utf-8");response.setHeader("Content-disposition", "attachment;filename=" + fileName);response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");try {List<Song> songs = songMapper.selectList(null);EasyExcel.write(response.getOutputStream(), Song.class).sheet("歌曲列表").doWrite(songs);} catch (Exception e) {e.printStackTrace();response.reset();response.setContentType("application/json;charset=utf-8");JsonResult<Void> jsonResult = JsonResult.success("数据导出异常");try {response.getWriter().write(jsonResult.toString());} catch (IOException ioException) {ioException.printStackTrace();}}}}

代码已经同步到后端项目的springbooot-crud1.0分支,可按需获取~

springboot+mybatis实现简单的增删查改案例项目 icon-default.png?t=N7T8https://gitee.com/he-yunlin/springboot-crud.git

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何正确使用GPT工具

引言 在快速发展的数字时代&#xff0c;人工智能&#xff08;AI&#xff09;已成为科研领域的一个不可或缺的工具。特别是像ChatGPT这样的AI聊天机器人&#xff0c;它通过高效的语言模型和深度学习算法&#xff0c;为科研工作者提供了前所未有的辅助。从文献搜索到数据分析&…

关于el-table+el-input+el-propover的封装

一、先放图片便于理解 需求&#xff1a; 1、el-input触发focus事件&#xff0c;弹出el-table(当然也可以为其添加搜索功能、分页) 2、el-table中的复选共能转化成单选共能 3、选择或取消的数据在el-input中动态显示 4、勾选数据后&#xff0c;因为分页过多&#xff0c;原先选好…

跨链知识指南

跨链知识指南 什么是跨链 跨链就是能够让两个不同的链产生某种关联的技术&#xff0c;或者说能把链A的东西搬到链B&#xff0c;跨链是一个复杂的过程&#xff0c;需要链对链外的信息的获取与验证&#xff0c;需要节点有单独的验证能力等等 什么是跨链桥&#xff1f; 跨链桥…

计算机网络——物理层-传输方式(串行传输、并行传输,同步传输、异步传输,单工、半双工和全双工通信)

目录 串行传输和并行传输 同步传输和异步传输 单工、半双工和全双工通信 串行传输和并行传输 串行传输是指数据是一个比特一个比特依次发送的。因此在发送端和接收端之间&#xff0c;只需要一条数据传输线路即可。 并行传输是指一次发送n个比特&#xff0c;而不是一个比特&…

【C/C++笔试练习】内联函数、函数重载、调用构造函数的次数、赋值运算符重载、静态成员函数、析构函数、模板定义、最近公共祖先、求最大连续bit数

文章目录 C/C笔试练习选择部分&#xff08;1&#xff09;内联函数&#xff08;2&#xff09;函数重载&#xff08;3&#xff09;调用构造函数的次数&#xff08;4&#xff09;赋值运算符重载&#xff08;5&#xff09;静态成员函数&#xff08;6&#xff09;调用构造函数的次数…

基于GPTs个性化定制SCI论文专业翻译器

1. 什么是GPTs GPTs是OpenAI在2023年11月6日开发者大会上发布的重要功能更新&#xff0c;允许用户根据特定需求定制自己的ChatGPT模型。 Introducing GPTs 官方介绍页面https://openai.com/blog/introducing-gpts 在原有自定义ChatGPT的流程中&#xff0c;首先需要自己编制p…

跨域:利用JSONP、WebSocket实现跨域访问

跨域基础知识点&#xff1a;跨域知识点 iframe实现跨域的四种方式&#xff1a;http://t.csdnimg.cn/emgFr 注&#xff1a;本篇中使用到的虚拟主机也是上面iframe中配置的 目录 JSONP跨域 JSONP介绍 跨域实验&#xff1a; WebSocket跨域 websocket介绍 跨域实验 JSONP跨域…

CSS的初步学习

CSS 层叠样式表 (Cascading Style Sheets). CSS 能够对网页中元素位置的排版进行像素级精确控制, 实现美化页面的效果. 能够做到页面的样式和结 构分离. CSS 就是 “东方四大邪术” 之化妆术 CSS 基本语法规范: 选择器 若干属性声明 选择器决定针对谁修改 (找谁) 声明决定修…

配置cuda和cudnn出现 libcudnn.so.8 is not a symbolic link问题

cuda版本为11.2 问题如图所示&#xff1a; 解决办法&#xff1a; sudo ln -sf /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_adv_train.so.8 sudo ln -sf /usr/local/cuda-11.2/targ…

LabVIEW中NIGPIB设备与驱动程序不相关的MAX报错

LabVIEW中NIGPIB设备与驱动程序不相关的MAX报错 当插入GPIB-USB设备时&#xff0c;看到了NI MAX中列出该设备&#xff0c;但却显示了黄色警告指示&#xff0c;并且指出Windows没有与您的设备相关的驱动程序。 解决方案 需要安装能兼容的NI-488.2驱动程序。 通过交叉参考以下有…

[量化投资-学习笔记009]Python+TDengine从零开始搭建量化分析平台-KDJ

技术分析有点像烹饪&#xff0c;收盘价、最值、成交量等是食材&#xff1b;均值&#xff0c;移动平均&#xff0c;方差等是烹饪方法。随意组合一下就是一个技术指标。 KDJ又称随机指标&#xff08;随机这个名字起的很好&#xff09;。KDJ的计算依据是最高价、最低价和收盘价。…

Jenkins 部署.net core 项目 - NU1301错误

/root/.jenkins/workspace/householdess/services/host/fdbatt.monitor.HttpApi.Host/fdbatt.monitor.HttpApi.Host.csproj : error NU1301: 本地源“/root/.jenkins/workspace/householdess/​http:/x.x.x.x:9081/repository/nuget.org-proxy/index.json”不存在。 [/root/.je…