首页 > 其他分享 >前端VUE+后端springboot实现导入返回excel校验结果demo

前端VUE+后端springboot实现导入返回excel校验结果demo

时间:2023-01-31 11:45:28浏览次数:41  
标签:VUE return springboot demo param public import response String

vue代码

<!-- 菜单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :on-change="changeUpload"
        :file-list="fileUploadList"
        :on-exceed="fileUploadExceed"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处,或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
          <el-link type="info" style="font-size:12px" @click="importTemplate" v-hasPermi="['system:menu:export']">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="submitFileBtnDisabled">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


    // 提交上传文件
    submitFileForm() {
      let files = this.$refs.upload.uploadFiles
      if(files.length == 0) {
        this.msgError('请选择文件')
        return
      }
      // this.$refs.upload.submit();
      this.submitFileBtnDisabled = true;
      let formData = new FormData()
        formData.append('file', this.$refs.upload.uploadFiles[0].raw)
        exportExcel(formData).then((res)=>{
        this.submitFileBtnDisabled = false;
          if (res.type == 'application/json') {
            console.log(res)
            const reader = new FileReader();
            reader.readAsText(res, 'utf-8');
            reader.onload = () => {
              let msg = JSON.parse(reader.result).message;
              let status = JSON.parse(reader.result).status;
              if(status == '200') {
                // 导入成功
                this.msgSuccess(msg);
                this.handleFileSuccess();
              }else{
              //处理报错信息 JSON.parse(reader.result)拿到报错信息
                this.msgError(msg);
              }
            };
            return;
          }else{
            // 导入信息有错误
            //创建一个隐藏的a连接,
            const link = document.createElement('a');
            let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
            link.style.display = 'none';
            //设置连接
            link.href = URL.createObjectURL(blob);
            link.download =  `menu_${new Date().getTime()}.xlsx`; //你文件定义的名称
            document.body.appendChild(link);
            //模拟点击事件
            link.click();
          }
        }).catch(() => {
          this.submitFileBtnDisabled = false;
        })
    }

引入的js


// 导入提交
export function exportExcel(formData) {
  return request({
    url: '/system/menu/import',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    method: 'post',
    responseType: 'blob',
    data: formData,
    timeout: 300000

  })
}

springboot后端代码

        // controller
        @PreAuthorize("@ss.hasPermi('system:menu:import')")
	@Log(title = "菜单管理", businessType = BusinessType.IMPORT)
	@PostMapping("/import")
	public void importMenu(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {

		// 导入处理
		R<List<MenuExcelData>> handlerResult = menuImportService.handlerData(file);
		logger.info("handlerResult:{}--{}", handlerResult.getCode(), handlerResult.getMsg());
		if (handlerResult.getCode() != R.SUCCESS) {
			if (null != handlerResult.getData()) {
				ResponseUtil.excel(response, ModuleTypeEnum.MENU.getName(), MenuExcelData.class, handlerResult.getData());
			} else {
				String msg = StringUtils.isNotEmpty(handlerResult.getMsg()) ? handlerResult.getMsg() : "导入异常";
				ResponseUtil.print(response, "500", msg);
			}
		} else {
			ResponseUtil.print(response, "200", "导入完成");
		}
	}

回复工具类
package com.ruoyi.system.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.ServletUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @description :请求返回工具类
 */
public class ResponseUtil {

    /**
     * description 打印返回json
     *
     * @param response	返回
     * @param status	状态
     * @param message	消息
     **/
    public static void print(HttpServletResponse response, String status, String message) {
        Map<String, String> map = MapUtils.newHashMap();
        map.put("status", status);
        map.put("message", message);
        ServletUtils.renderString(response, JSON.toJSONString(map));
    }

    /**
     * description 返回excel
     *
     * @param response	 返回请求
     * @param moduleName 模块名称
     * @param clazz	     类参数
     * @param errorList	 错误列表
     **/
    public static <T> void excel(HttpServletResponse response, String moduleName, Class<?> clazz, List<T> errorList) throws Exception {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode(moduleName + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(moduleName).doWrite(errorList);
        response.flushBuffer();
    }

    /**
     * description 多个sheet返回
     *
     * @param response	 返回请求
     * @param sheetNames sheet名称
     * @param clazz	     类参数
     * @param errorList	 错误列表
     **/
    public static void excel(HttpServletResponse response, String[] sheetNames, Class<?>[] clazz, Map<String, List<?>> errorList) throws Exception {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("Error_" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build()) {
            for (int i = 0; i < clazz.length; i++) {
                Class<?> aClass = clazz[i];
                WriteSheet writeMenuSheet = EasyExcel.writerSheet(sheetNames[i]).head(aClass).build();
                excelWriter.write(errorList.get(aClass.getName()), writeMenuSheet);
            }
        }
        response.flushBuffer();
    }

    /**
     * description 返回模板
     *
     * @param response 返回
     * @param tempPathName 模板路径名	
     * @param sheetName 返回模板修改
     * @param clazz	数据类型
     * @param dataList 数据
     **/
    public static <T> void tempFile(HttpServletResponse response, String tempPathName, String sheetName, Class<?> clazz, List<T> dataList) throws Exception {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("temp" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).withTemplate(EasyExcelUtil.readFileInputStream(tempPathName)).sheet(sheetName).doWrite(dataList);
        response.flushBuffer();
    }

    /**
     * description 返回模板
     *
     * @param response 返回
     * @param tempPathName 模板路径名
     **/
    public static <T> void tempFile(HttpServletResponse response, String tempPathName) throws Exception {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("temp" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter build = EasyExcel.write(response.getOutputStream()).withTemplate(EasyExcelUtil.readFileInputStream(tempPathName)).build();
        build.finish();
        response.flushBuffer();
    }
}

// easyexcel工具类
package com.ruoyi.system.utils;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.domain.imports.UserAuthorityExcelData;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @description :导入导出工具类
 */
public class EasyExcelUtil {

    /**
     * description 获取代码路径
     *
     * @return java.lang.String
     **/
    public static String getPath() {
        return Objects.requireNonNull(EasyExcelUtil.class.getResource("/")).getPath();
    }

    /**
     * description 获取文件
     *
     * @param pathName	文件名称
     * @return java.io.File
     **/
    public static File readFile(String pathName) {
        return new File(getPath() + pathName);
    }

    /**
     * description 返回文件流
     *
     * @param resourceFile
     * @return java.io.InputStream
     **/
    public static InputStream readFileInputStream(String resourceFile) {
        return EasyExcelUtil.class.getResourceAsStream(resourceFile);
    }

    /**
     * description 登录账号重复统一处理
     *
     * @param e 异常
     * @return com.ruoyi.common.core.domain.R<java.util.List<?>>
     **/
    public static <T> R<List<T>> illegalStateExceptionHandler(Exception e) {
        if (e instanceof IllegalStateException) {
            String exceptionMessage = e.getMessage();
            if (!StringUtils.isEmpty(exceptionMessage)) {
                int duplicateUserId = exceptionMessage.indexOf("userName:");
                if (duplicateUserId >= 0) {
                    return R.fail("登录账号:" + exceptionMessage.substring(duplicateUserId + "userName:".length()) + " 数据库重复请核查!");
                }
            }
        }
        return R.fail("导入异常");
    }
}

标签:VUE,return,springboot,demo,param,public,import,response,String
From: https://www.cnblogs.com/stubborn-dude/p/17078456.html

相关文章

  • vue3 之 ref
    vue3之ref vue2中的ref获取一个dom元素和实例对象 vue3中ref是用来定义数据响应式特别注意:ref可以接收基本数据类型,也可以是对象类型1、基本数据类型......
  • nginx部署vue history模式项目页面刷新报404问题
    nginx部署vuehistory模式项目页面刷新报404问题解决方案:在nginx配置种添加以下代码:try_files$uri$uri//index.html示例:location/{rootdist;......
  • 解决webstorm不能识别vue的@路径引用
    方式1: webstorm无法识别@符号问题[ctrl+左键无法跳转]解决:创建vue项目,打开项目后,再进入webstorm配置页面[否则没有webpack选项]ctrl+alt+s[进入设置页面]->langua......
  • springboot 统一日志记录 - AOP日志
    参考学习:https://www.bilibili.com/video/BV1bf4y187KX/三步:1.使用日志注解。2.编写日志注解类。3.编写日志注解类的AOP实现。1.在需要记日志处,使用自定义的注解。pac......
  • 使用 vue-pdf 踩坑记录
    嵌入小程序里的h5里有一个查看pdf的功能,在h5里可以正常打开pdf,但是在小程序的webview里却打不开。为了解决这个问题踩了好多坑......
  • VUEX 使用学习六 : modules
    转载请注明出处:当Store中存放了非常多非常大的共享数据对象时,应用会变的非常的复杂,Store对象也会非常臃肿,所以Vuex提供了一个Module模块来分隔Store。通过对Vuex中的S......
  • VUEX 使用学习五 : getter
    转载请注明出处:Getter对Store中的数据进行加工处理形成新的数据。他不会修改state中的原始数据,起到的是包装数据的作用;有时我们需要从store中的state中派生......
  • 为什么vue3要使用ref
    vue3中使用ref来创建响应式数据,让习惯了选项式API的我很不习惯。因为得使用xxx.value来读写响应式数据,没有vue2中直接使用this.xxx来读写简洁。vue3这样设计的原因是原生J......
  • Vue2 和 Vue3 的不同之处
    1、双向绑定的更新 vue2是采用的ES5的⼀个API叫做object.definePropert 对数据进⾏劫持结合发布订阅模式vue3是采用的ES6的一个API叫做Proxy......
  • 基于JAVA springboot+mybatis智慧生活分享平台设计和实现
    基于JAVAspringboot+mybatis智慧生活分享平台设计和实现文章目录​​基于JAVAspringboot+mybatis智慧生活分享平台设计和实现​​​​主要功能模块设计:​​​​系统前端......