若依框架数据导入功能

若依框架添加导入功能

1、前端

1)添加导入按钮

<el-col :span="1.5">
  <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
</el-col>

2)添加导入模态框

<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
    <el-upload
               ref="upload"
               :limit="1"
               accept=".xlsx, .xls"
               :headers="upload.headers"
               :action="upload.url + '?updateSupport=' + upload.updateSupport"
               :disabled="upload.isUploading"
               :on-progress="handleFileUploadProgress"
               :on-success="handleFileSuccess"
               :auto-upload="false"
               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">下载模板</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">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
    </div>
</el-dialog>

3)导入获取token的的方法

import { getToken } from "@/utils/auth";

4)data中导入功能所需参数

路径url后面拼接实际导入方法接口

 //导入功能
 upload:{
    open: false,
    title:"",
    isUploading: false,
    updateSupport: 0,
    headers:{Authorization:"Bearer "+getToken()},
    url:process.env.VUE_APP_BASE_API + "/device/gateway/importData"
 },

5)导入相关方法

/** 导入按钮操作 */
handleImport() {
    this.upload.title = "导入";
    this.upload.open = true;
},
/** 下载模板操作 */
importTemplate() {
    this.download('device/gateway/importTemplate',{
    },`data_template_${new Date().getTime()}.xlsx`)
},
 // 文件上传中处理
handleFileUploadProgress(event, file, fileList) {
    this.upload.isUploading = true;
},
// 文件上传成功处理
handleFileSuccess(response, file, fileList) {
    this.upload.open = false;
    this.upload.isUploading = false;
    this.$refs.upload.clearFiles();
    this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
    this.getList();
},
// 提交上传文件
submitFileForm() {
    this.$refs.upload.submit();
}

2、后端

1)模板下载接口

@PostMapping("/importTemplate")
public void importTemplate(HttpServletResponse response)
{
    ExcelUtil<GatewayData> util = new ExcelUtil<GatewayData>(GatewayData.class);
    util.importTemplateExcel(response,"注册码数据");
}

2)数据导入接口

 @Log(title = "数据导入", businessType = BusinessType.IMPORT)
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
{
    ExcelUtil<T> util = new ExcelUtil<T>(T.class);
    List<T> list = util.importExcel(file.getInputStream());

    String message = gatewayDataService.importData(list, updateSupport);
    return success(message);
}

3)数据导入业务处理

String importData(List<GatewayData> gatewayList, boolean updateSupport);
@Autowired
protected Validator validator;

@Override
public String importData(List<T> list, boolean updateSupport) {
    //TODO:修改T为实际数据对象
    if (CollectionUtils.isEmpty(list)){
        throw new ServiceException("导入数据不能为空!");
    }

    int successNum = 0;
    int failureNum = 0;
    StringBuilder successMsg = new StringBuilder();
    StringBuilder failureMsg = new StringBuilder();
    for (GatewayData data : list) {
        try {
            //检查要添加的数据是否已经在库中存在
            GatewayData mac = gatewayDataMapper.selectGatewayDataByMac(data.getMac());
            if (Objects.isNull(mac)){
                BeanValidators.validateWithException(validator,data);
                data.setCreateBy(operName);
                gatewayDataMapper.insertGatewayData(data);
                successNum++;
                successMsg.append("<br/>" + successNum + "、mac: " + data.getMac() + " 导入成功");
            }else if (updateSupport){
                BeanValidators.validateWithException(validator,data);
                data.setCreateBy(operName);
                gatewayDataMapper.updateGatewayData(data);
                successNum++;
                successMsg.append("<br/>" + successNum + "、mac: " + data.getMac() + " 更新成功");
            }else {
                failureNum++;
                failureMsg.append("<br/>" + successNum + "、mac: " + data.getMac() + " 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + data.getMac() + " 导入失败:";
            failureMsg.append(msg + e.getMessage());
            logger.error(msg,e);
        }
    }

    if (failureNum > 0 ){
        failureMsg.insert(0,"很抱歉,导入失败,共 "+failureNum+" 条数据格式不正确,错误如下:");
        throw new ServiceException(failureMsg.toString());
    }else {
        successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
    }
    //TODO:此处可在导入完成后,做相应处理
    return successMsg.toString();
}
posted @   戒爱学Java  阅读(440)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
历史上的今天:
2023-05-31 MyBatis配置Log4j

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示