Realize the front-end form field function of custom exporting EXCEL in JeecgBoot enterprise-level development

How to implement the function of exporting front-end list fields to Excel in the backend

need

  • According to the list fields displayed in the table, clicking Export will pop up an EXCEL containing the following information, but since the framework comes with the entity class fields that Mybatis-plus needs to provide are the same as those shown in the table, it will not work, because The following fields and database tables cannot be mapped one-to-one, so consider customizing and encapsulating an interface
    insert image description here

Implementation of the front end

1. Provide an exported click function

    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button  type="primary" preIcon="ant-design:export-outlined" @click="exportXlS"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <template #bill_data="{ record }"> 
        <!-- 文字提示 -->
        <a-tooltip>
          <template #title>{
    
    {
    
     record.bill}}</template> 
          <a-button type="primary" shape="round" @click = "showBillDetails(record.id)">查看</a-button> 
        </a-tooltip>
      </template>
     <!--省市区字段回显插槽-->
      <template #pcaSlot="{ text }">
        {
    
    {
    
     getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small"
          @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>

2. Introduce the userMethod in the component

  import {
    
     useMethods } from '/@/hooks/system/useMethods';

3. Add corresponding query parameters to the export in tableProps

const {
    
     prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    
    
  tableProps: {
    
    
    title: '数据报表',
    api: queryList,
    columns,
    canResize: false,
    useSearchForm: false,
    showActionColumn: false,
    summaryData: summaryData,
    pagination:false,
    actionColumn: {
    
    
      width: 120,
      fixed: 'right',
    },
    beforeFetch: (params) => {
    
    
      return Object.assign(params, queryParam.value);
    },afterFetch: (data) =>{
    
    
      
    }
  },
  exportConfig: {
    
    
    name: "数据报表",
    url: getExportUrl,
    params:queryParam.value
  },
  importConfig: {
    
    
    url: getImportUrl,
    success: handleSuccess
  },
});

4. Write the export function

  //导入导出方法
 const {
    
     handleExportXls, handleImportXls } = useMethods();

  /**
   * 导出事件
   */
  function exportXlS() {
    
    
    return handleExportXls("账号数据表", "/count/opReport/exportExcel", queryParam.value);
  }

Implementation of backend logic

1. Controller layer

  • Use ModelAndView to receive, and Dto is the parameters of the front-end query, and the ReportAccountModal entity class allows us to export those fields corresponding to Excel
	/**@param reportAccountDto
	 * @author chenglin
	 * @description 补充导出Excel功能
	 * @date  16:26 2023/5/30
	 **/
	@RequestMapping(value = "/exportExcel")
	public ModelAndView exportExcel(HttpServletRequest request, ReportAccountDto reportAccountDto) {
    
    
		return OpReportAccountService.exportExcel(request,reportAccountDto, ReportAccountModal.class,"账号数据表");
	}

2. Create the Modal class

package org.jeecg.modules.count.modal;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * @description: 账号报表EXCEL模型类
 * @author: chenglin
 * @date: 2023年05月30日 16:28
 */
@Data
public class ReportAccountModal implements Serializable {
    
    
    private static final long serialVersionUID = 1L;
    /**账号昵称*/
    @Excel(name = "账号昵称", width = 15)
    @ApiModelProperty(value = "账号昵称")
    private String nickName;
    /**账号*/
    @Excel(name = "账号", width = 15)
    @ApiModelProperty(value = "账号")
    private String account;
    /**游戏*/
    @Excel(name = "游戏", width = 15)
    @ApiModelProperty(value = "游戏")
    private String subGameIds;
    /**渠道*/
    @Excel(name = "渠道", width = 15)
    @ApiModelProperty(value = "渠道")
    private String channelName;
    /**投放消耗*/
    @Excel(name = "投放消耗", width = 15)
    @ApiModelProperty(value = "投放消耗")
    private BigDecimal outCostMoney;
    /**账号余额*/
    @Excel(name = "账号余额", width = 15)
    @ApiModelProperty(value = "账号余额")
    private BigDecimal surplusAmount;
    /**曝光*/
    @Excel(name = "曝光", width = 15)
    @ApiModelProperty(value = "曝光")
    private BigDecimal exhibition;
    /**下载*/
    @Excel(name = "下载", width = 15)
    @ApiModelProperty(value = "下载")
    private BigDecimal download ;
    /**负责人*/
    @Excel(name = "负责人", width = 15)
    @ApiModelProperty(value = "负责人")
    private String principalUser;
    /**创建时间*/
    @Excel(name = "创建时间", width = 15)
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern="yyyy-MM-dd")
    @ApiModelProperty(value = "创建时间")
    private Date createTime;
    /**更新时间*/
    @Excel(name = "更新时间", width = 15)
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern="yyyy-MM-dd")
    @ApiModelProperty(value = "更新时间")
    private Date updateTime;
}

3. Service layer

  • Among them, our reusltList is the interface that I called the previous query data, and then copied the corresponding data to my Modal class
    ModelAndView exportExcel(HttpServletRequest request, ReportAccountDto reportAccountDto, Class<ReportAccountModal> reportAccountClass, String
        title);

//这是impl
    @Override
    public ModelAndView exportExcel(HttpServletRequest request, ReportAccountDto reportAccountDto,
        Class<ReportAccountModal> reportAccountVoClass, String title) {
    
    
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String  username = JwtUtil.getUserNameByToken(request);
        // Step.2 获取导出数据
        List<ReportAccountVo> resultList = queryAccountList(reportAccountDto,username);
        List<ReportAccountModal>exportList = new ArrayList<>();
        for (ReportAccountVo reportAccountVo : resultList) {
    
    
            ReportAccountModal reportAccountModal = new ReportAccountModal();
            BeanUtils.copyProperties(reportAccountVo,reportAccountModal);
            exportList.add(reportAccountModal);
        }
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, reportAccountVoClass);
        //update-begin--Author:liusq  Date:20210126 for:图片导出报错,ImageBasePath未设置--------------------
        ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for:图片导出报错,ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

Test results

  • function realization
    insert image description here

Summarize

Many of the low codes of JEECG are encapsulated, using Mybatis-plus, and we often need to customize it, because our data does not necessarily correspond to the entity class. This requirement comes from one of my internships to record the learning process

Guess you like

Origin blog.csdn.net/weixin_59823583/article/details/130952860