Springboot + Vue project implements selected data export based on poi

I. Introduction

The back-end integrates POI based on Springboot, and the front-end implements exporting the selected table data based on Vue. The effect is as shown in the figure:

2. Backend

1. Introduce poi-related dependencies. The specific version can be selected according to the version of your own project.

 <!--POI-TL-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>

<!-- AutoPoi Excel tool class-->
<dependency>
<groupId>org.jeecgframework</groupId>
<artifactId>autopoi-web</artifactId>
<version>1.3.5</version>
<exclusions>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>

2. Entity class. Which fields should be exported depends on each person’s own needs, and then create entity classes based on the fields that need to be exported.

@Data
public class NucleinExportDto {
    @Excel(name = "Application Date",width = 15)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private String registerDate;

    @Excel(name = "Sample encoding",width = 15)
    private String samplesCode;

    @Excel(name = "name",width = 15)
    private String fdName;

    @Excel(name = "Application code",width = 15)
    private String applyCode;

    @Excel(name = "DNA concentration",width = 15)
    private String concentrationD;

    @Excel(name = "DNA260/280",width = 15)
    private String D280;

    @Excel(name = "DNA260/230",width = 15)
    private String D230;

    @Excel(name = "DNA Volume",width = 15)
    private String volumeD;

    @Excel(name = "Total amount of DNA",width = 15)
    private String totalD;

    @Excel(name = "RNA concentration",width = 15)
    private String concentrationR;

    @Excel(name = "RNA260/280",width = 15)
    private String R280;

    @Excel(name = "RNA260/230",width = 15)
    private String R230;

    @Excel(name = "RNA Volume",width = 15)
    private String volumeR;

    @Excel(name = "Total RNA",width = 15)
    private String totalR;
}

3. Export tool class

package org.jeecg.common.util;

import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Export excel tool class
 * @Auther WuCheng
 * @Date 2020/12/4
 */
public class ExcelUtils {
    /**
     *Export excel
     *
     * @param title file title
     * @param clazz entity type
     * @param exportList export data
     * @param <T>
     * @return
     */
    public static <T> ModelAndView export(String title,String exportName, Class<T> clazz, List<T> exportList) {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title, exportName,""));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }
    /**
     * Single data export
     * @param title
     * @param exportName
     * @paramclazz
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> ModelAndView exportOne(String title,String exportName, Class<T> clazz, T obj) {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title, exportName,""));
        mv.addObject(NormalExcelConstants.DATA_LIST, obj);
        return mv;
    }
}

4. Controller layer interface

 @GetMapping("/nucleinExportList")
public ModelAndView nucleinExport(@RequestParam String edIdsVo,HttpServletRequest request,HttpServletResponse response){
EdIdsVo idsVo = JSONObject.toJavaObject(JSONObject.parseObject(edIdsVo), EdIdsVo.class);
String[] ids = idsVo.getIds();
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
List<NucleinExportDto> nucleinExportList = new ArrayList<>();
for (String id : ids) {
NucleinExportDto nucleinExport = pcr11NucleinControlService.nucleinExport(id);
if (null == nucleinExport)continue;
nucleinExportList.add(nucleinExport);
}
return ExcelUtils.export("PCR11 gene nucleic acid export","Exporter:" + sysUser.getRealname(), NucleinExportDto.class,nucleinExportList);
}

Since the use process involves JSON related operations, it is also necessary to introduce json dependencies.

 <!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>

As for the code of the Service layer and Mapper layer, it is a simple interface query. As for the code that handles the logic part, it is recommended to write it in the implementation class of the service layer, not in the controller. I wrote it directly in the controller layer for convenience.

3. Front-end

The component used by the vue front-end is ant-design-vue, and the component address is: Ant Design Vue (antdv.com)icon-default.png?t=N7T8https://2x .antdv.com/components/overview-cn/

The version used can be selected according to your own vue version. If the front-end project uses Vue2, it is best to choose the v1 version.

1. Define a variable in data

data() {
    return {
      sysUserExportXlsVoList: {
        ids: [],
      },
   }
}

2. Assign the variables defined above in events related to whether the list items of the table table are selectable.

onSelect event:

 onSelect(record, selected, selectedRows, nativeEvent) {
      console.log("selectedRows",selectedRows)
     
      if (selectedRows.length !== 0) {
        this.sysUserExportXlsVoList.ids = [];
        selectedRows.forEach((item, index) => {
          this.sysUserExportXlsVoList.ids.push(item.fdPcrApply);
      }
    },

onSelectAll event:

 onSelectAll(selected, selectedRows, changeRows) {
        this.sysUserExportXlsVoList.ids = [];
        selectedRows.forEach((item, index) => {
          this.sysUserExportXlsVoList.ids.push(item.fdPcrApply);
         
      }
    },

3. Define js for front-end request back-end interface: pcr11ProcessControl.js

import axios from "axios";


export const nucleinExportList = (edIdsVo) => {
  return axios.request({
    url: "/jeecg-boot/qualitycenter/processControl/pcr/pcr11/nucleinExportList",
    method: "get",
    responseType: "blob",
    params: {edIdsVo}
  });
};

Then import it into the page

import { nucleinExportList,} from "../../../../../api/pcr11ProcessControl.js";

4. Add a button button and set a click event for the button

<a-button size="large" @click="exportData">Export button</a-button>

5. Implement data export function in click event

exportData(){
    if (this.sysUserExportXlsVoList.ids.length > 0) {
        nucleinExportList(this.sysUserExportXlsVoList).then((res) => {
              let fileName = this.$route.query.title;
              let xls = res.data;
              if (!xls) {
                this.$message.warning("File download failed");
                return;
              }
              if (typeof window.navigator.msSaveBlob !== "undefined") {
                window.navigator.msSaveBlob(
                    new Blob([xls], { type: "application/vnd.ms-excel" }),
                    fileName + ".xls"
                );
              } else {
                let url = window.URL.createObjectURL(
                    new Blob([xls], { type: "application/vnd.ms-excel" })
                );
                console.log("ssd", xls);
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", fileName + ".xls");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); //Remove element after download is complete
                window.URL.revokeObjectURL(url); //Release the blob object
                this.$message.success(
                    `Successfully exported ${this.selectedRowKeys.length}`
                );
              }
            });
          } else {
            this.$message.warning("Please select the content to be exported");
          }

}

The above is the entire content of springboot + vue exporting the selected list data based on poi.