百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

《若依ruoyi》第三十七章:Ruoyi利用poi-ooxml导出execl功能拆解

ztj100 2025-07-23 19:27 5 浏览 0 评论

本章节重点介绍每个列表按钮栏都有一个导出功能,今天分析一下这个导出的实现逻辑

1、界面操作

第一步:点击右侧菜单栏的角色管理,系统展示角色列表,找到顶部的导出按钮,然后点击。

第二步:系统自动下载并保存本地目录

第三步:打开下载文件


2、代码实现

第一、导出按钮代码

<el-col :span="1.5">
  <el-button
    type="warning"
    plain
    icon="el-icon-download"
    size="mini"
    @click="handleExport"
    v-hasPermi="['system:role:export']"
  >导出</el-button>
</el-col>

type:按钮类型。

icon:按钮前面的图标。

size:大小,mini是最小。

@click:点击事件,绑定处理函数handleExport。

v-hasPermi:是否拥有权限,权限字符串是system:role:export。

第二、导出按钮操作

/** 导出按钮操作 */
handleExport() {
  this.download('system/role/export', {
    ...this.queryParams
  }, `role_${new Date().getTime()}.xlsx`)
}

导出按钮的处理函数调用download的函数,download的函数是通过main配置统一的全局函数。


如上图,先import down,在做全局挂载Vue.prototype.download = download

第三、通用下载封装

// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误,请联系管理员!')
    downloadLoadingInstance.close();
  })
}

如上述代码,是统一下载封装。

downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })

该代码实现遮罩层的功能,提示用户正在下载。

service.post:该代码实现通过http post请求后端接口,获取下载文件。

3、后端接口代码实现

第一、代码路径如下图:


第二、具体接口入口代码

@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysRole role)
{
    List<SysRole> list = roleService.selectRoleList(role);
    ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
    util.exportExcel(response, list, "角色数据");
}

上述是导出代码,其中生成execl文档使用的是使用第三方jar poi-ooxml,poi-ooxml对excel处理的框架,处理excel2007版本以上的文档,是poi的升级版本,处理的单页数据量也是百万级别的。

maven中的pom文件里面引入。

<!-- excel工具 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
</dependency>

execl的实现逻辑是在实体对象增加@Excel注解

例如上述代码ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);该代码是需要生成SysRole类对象的execl文件,我们可以看看SysRole代码的@Excel配置

private static final long serialVersionUID = 1L;

/** 角色ID */
@Excel(name = "角色序号", cellType = ColumnType.NUMERIC)
private Long roleId;

/** 角色名称 */
@Excel(name = "角色名称")
private String roleName;

/** 角色权限 */
@Excel(name = "角色权限")
private String roleKey;

/** 角色排序 */
@Excel(name = "角色排序")
private Integer roleSort;

其中name是对应execl的头部标题,List<SysRole> list =
roleService.selectRoleList(role); 这个sql查询出来的就是对应的数据。详细参见下图已经下载的execl文件


相关推荐

10条军规:电商API从数据泄露到高可用的全链路防护

电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...

Python 文件处理在实际项目中的困难与应对策略

在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...

The Future of Manufacturing with Custom CNC Parts

ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...

Innovative Solutions in Custom CNC Machining

Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...

C#.NET serilog 详解(c# repository)

简介Serilog是...

Custom CNC Machining for Small Batch Production

Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...

Custom CNC Machining for Customized Solutions

Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...

Revolutionizing Manufacturing with Custom CNC Parts

Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...

Breaking Boundaries with Custom CNC Parts

BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...

Custom CNC Parts for Aerospace Industry

Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...

Cnc machining for custom parts and components

UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...

洞察宇宙(十八):深入理解C语言内存管理

分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...

The Art of Crafting Custom CNC Parts

UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...

Tailored Custom CNC Solutions for Automotive

Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...

关于WEB服务器(.NET)一些经验累积(一)

以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...

取消回复欢迎 发表评论: