• 通过easyexcel导出数据到excel表格


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

    前端页面完整代码

    1. let editingId;
    2. let requestUrl;
    3. let base = "http://localhost:8083";
    4. let pageList = [20, 50, 100, 500, 1000];
    5. // 定义一个json对象保存歌曲数据
    6. let data = {};
    7. function addHandler() {
    8. requestUrl = "/song/insert";
    9. $.post(base + requestUrl, {
    10. name: "*****",
    11. singer: "*****",
    12. note: "*****"
    13. }, function () {
    14. $("#song_list").datagrid("reload");
    15. }, "json");
    16. }
    17. function editHandler() {
    18. let datagrid = $("#song_list");
    19. let row = datagrid.datagrid("getSelected");
    20. if (editingId != null && editingId != "") {
    21. datagrid.datagrid("selectRow", editingId);
    22. } else {
    23. if (row) {
    24. // 获取行索引,这个索引从0开始
    25. let rowIndex = datagrid.datagrid("getRowIndex", row);
    26. editingId = rowIndex;
    27. requestUrl = "/song/updateById";
    28. datagrid.datagrid("beginEdit", rowIndex);
    29. }
    30. }
    31. }
    32. function saveHandler() {
    33. if (editingId) {
    34. // 只有结束编辑才能获取到最新的值
    35. $("#song_list").datagrid("endEdit", editingId);
    36. $.post(base + requestUrl, data, function (res) {
    37. $.messager.show({
    38. title: '系统消息',
    39. timeout: 5000,
    40. showType: 'slide',
    41. msg: res.message,
    42. });
    43. editingId = "";
    44. }, "json");
    45. }
    46. }
    47. function cancelHandler() {
    48. // editingId != null条件防止刷新页面带来的问题
    49. if (editingId != null && editingId !== "") {
    50. $("#song_list").datagrid("cancelEdit", editingId);
    51. editingId = "";
    52. }
    53. }
    54. function exportHandler() {
    55. location.href = base + "/song/export";
    56. }
    57. function deleteHandler() {
    58. let rowData = $("#song_list").datagrid("getSelected");
    59. if (rowData) {
    60. $.messager.confirm("提示", "删除后数据无法恢复,是否确认删除?", function(bool) {
    61. if (bool) {
    62. $.get(base + "/song/deleteById/" + rowData.id, {}, function(res) {
    63. $.messager.show({
    64. title: '系统消息',
    65. timeout: 5000,
    66. showType: 'slide',
    67. msg: res.message,
    68. });
    69. $("#song_list").datagrid("reload");
    70. }, "json");
    71. }
    72. });
    73. } else {
    74. $.messager.alert("请选择要删除的数据!", "warning");
    75. }
    76. }
    77. $(document).ready(function() {
    78. let datagrid = $("#song_list").datagrid({
    79. url: base + "/song/selectByPage",
    80. title: "歌曲列表",
    81. height: 810,
    82. striped: true,
    83. fitColumns: true,
    84. singleSelect: true,
    85. pagination: true,
    86. remoteFilter: true,
    87. clientPaging: false,
    88. pageSize: pageList[0],
    89. pageList: pageList,
    90. loadFilter: function(res) {
    91. if (res.code == 200) {
    92. return res.data;
    93. } else {
    94. return null;
    95. }
    96. },
    97. onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件
    98. data = {
    99. id: rowData.id,
    100. name: changes.name ? changes.name : rowData.name,
    101. note: changes.note ? changes.note : rowData.note,
    102. singer: changes.singer ? changes.singer : rowData.singer
    103. };
    104. },
    105. toolbar: [{
    106. iconCls: 'icon-add',
    107. text: '添加',
    108. handler: function() {
    109. addHandler();
    110. }
    111. }, '-', {
    112. iconCls: 'icon-edit',
    113. text: '修改',
    114. handler: function() {
    115. editHandler();
    116. },
    117. }, "-", {
    118. iconCls: "icon-save",
    119. text: "保存",
    120. handler: function() {
    121. saveHandler();
    122. }
    123. }, "-", {
    124. iconCls: "icon-cancel",
    125. text: "取消",
    126. handler: function() {
    127. cancelHandler();
    128. }
    129. }, '-', {
    130. iconCls: 'icon-ok',
    131. text: '导出',
    132. handler: function() {
    133. exportHandler();
    134. }
    135. }, '-', {
    136. iconCls: 'icon-delete',
    137. text: '删除',
    138. handler: function() {
    139. deleteHandler();
    140. },
    141. }],
    142. columns: [[
    143. {field: 'id', title: 'id', width: 200},
    144. {field: 'name', title: 'name', width: 200, editor: "textbox"},
    145. {field: 'singer', title: 'singer', width: 200, editor: "textbox"},
    146. {field: 'note', title: 'note', width: 200, editor: "textbox"},
    147. {field: 'lastUpdateTime', title: 'lastUpdateTime', width: 200},
    148. ]]
    149. });
    150. datagrid.datagrid('enableFilter', [{
    151. field: 'name',
    152. type: 'textbox',
    153. op: ['equal', 'contains']
    154. }, {
    155. field: 'singer',
    156. type: 'textbox',
    157. op: ['equal', 'contains'],
    158. }, {
    159. field: 'note',
    160. type: 'textbox',
    161. op: ['equal', 'contains']
    162. }]);
    163. });

    添加依赖

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>easyexcelartifactId>
    4. <version>3.3.2version>
    5. dependency>

    修改实体类,添加列注解

    1. package com.example.springboot.entity;
    2. import com.alibaba.excel.annotation.ExcelIgnore;
    3. import com.alibaba.excel.annotation.ExcelProperty;
    4. import com.baomidou.mybatisplus.annotation.IdType;
    5. import com.baomidou.mybatisplus.annotation.TableField;
    6. import com.baomidou.mybatisplus.annotation.TableId;
    7. import com.baomidou.mybatisplus.annotation.TableName;
    8. import com.fasterxml.jackson.annotation.JsonFormat;
    9. import lombok.Data;
    10. import java.io.Serializable;
    11. import java.time.LocalDateTime;
    12. /**
    13. * 歌曲
    14. * @author heyunlin
    15. * @version 1.0
    16. */
    17. @Data
    18. @TableName("song")
    19. public class Song implements Serializable {
    20. private static final long serialVersionUID = 18L;
    21. @ExcelIgnore
    22. @TableId(type = IdType.INPUT)
    23. private String id;
    24. /**
    25. * 歌曲名
    26. */
    27. @ExcelProperty("歌曲名")
    28. private String name;
    29. /**
    30. * 歌手
    31. */
    32. @ExcelProperty("歌手")
    33. private String singer;
    34. /**
    35. * 描述信息
    36. */
    37. @ExcelProperty("描述信息")
    38. private String note;
    39. /**
    40. * 最后一次修改时间
    41. */
    42. @TableField("last_update_time")
    43. @ExcelProperty("最后一次修改时间")
    44. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    45. private LocalDateTime lastUpdateTime;
    46. }

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

    1. package com.example.springboot.service.impl;
    2. import com.alibaba.excel.EasyExcel;
    3. import com.example.springboot.entity.Song;
    4. import com.example.springboot.mapper.SongMapper;
    5. import com.example.springboot.restful.JsonResult;
    6. import com.example.springboot.service.SongService;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Service;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. import java.util.List;
    12. /**
    13. * @author heyunlin
    14. * @version 1.0
    15. */
    16. @Service
    17. public class SongServiceImpl implements SongService {
    18. private final SongMapper songMapper;
    19. @Autowired
    20. public SongServiceImpl(SongMapper songMapper) {
    21. this.songMapper = songMapper;
    22. }
    23. // 其他代码...
    24. @Override
    25. public void export(HttpServletResponse response) {
    26. String fileName = "song.xlsx";
    27. response.setCharacterEncoding("utf-8");
    28. response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    29. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    30. try {
    31. List songs = songMapper.selectList(null);
    32. EasyExcel.write(response.getOutputStream(), Song.class).sheet("歌曲列表").doWrite(songs);
    33. } catch (Exception e) {
    34. e.printStackTrace();
    35. response.reset();
    36. response.setContentType("application/json;charset=utf-8");
    37. JsonResult jsonResult = JsonResult.success("数据导出异常");
    38. try {
    39. response.getWriter().write(jsonResult.toString());
    40. } catch (IOException ioException) {
    41. ioException.printStackTrace();
    42. }
    43. }
    44. }
    45. }
  • 相关阅读:
    编译原理--基本块的划分
    关于你STM32F407片内FLASH擦除失败的问题
    PMP考生,请查收7月PMP考试注意事项
    DTK Barcode Recognition SDK Crack
    【JS高级】ES5标准规范之数组高阶函数的应用_11
    HAproxy
    Hadoop MapReduce + Hadoop YARN
    【AI】机器学习——朴素贝叶斯
    ImgPlus:基于CodeFormer的图片增强
    LeetCode 2656. K 个元素的最大和【数学】简单
  • 原文地址:https://blog.csdn.net/heyl163_/article/details/134349851