代码生成器增加导入功能

This commit is contained in:
数据小王子 2024-04-12 21:33:42 +08:00
parent 4224ffdc64
commit 3d7fd649fd
10 changed files with 522 additions and 15 deletions

Binary file not shown.

View File

@ -36,7 +36,7 @@
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/info.%d{yyyy-MM-dd}.log</FileNamePattern>
<FileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>60</MaxHistory>
</rollingPolicy>
<encoder>
@ -52,7 +52,7 @@
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/error.%d{yyyy-MM-dd}.log
<FileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log
</FileNamePattern>
<MaxHistory>60</MaxHistory>
</rollingPolicy>

View File

@ -136,11 +136,13 @@ public class VelocityUtils {
List<String> templates = new ArrayList<>();
templates.add("vm/java/domain.java.vm");
templates.add("vm/java/vo.java.vm");
templates.add("vm/java/vo-import.java.vm");
templates.add("vm/java/bo.java.vm");
templates.add("vm/java/mapper.java.vm");
templates.add("vm/java/service.java.vm");
templates.add("vm/java/serviceImpl.java.vm");
templates.add("vm/java/controller.java.vm");
templates.add("vm/java/listener.java.vm");
templates.add("vm/xml/mapper.xml.vm");
if (DataBaseHelper.isPostgreSql()) {
templates.add("vm/sql/postgresql/sql.vm");
@ -225,6 +227,7 @@ public class VelocityUtils {
case "vm/java/sub-domain.java.vm" ->
fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName());
case "vm/java/vo.java.vm" -> fileName = StringUtils.format("{}/domain/vo/{}Vo.java", javaPath, className);
case "vm/java/vo-import.java.vm" -> fileName = StringUtils.format("{}/domain/vo/{}ImportVo.java", javaPath, className);
case "vm/java/bo.java.vm" -> fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className);
case "vm/java/mapper.java.vm" ->
fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
@ -236,6 +239,8 @@ public class VelocityUtils {
fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
case "vm/java/controller.java.vm" ->
fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
case "vm/java/listener.java.vm" ->
fileName = StringUtils.format("{}/listener/{}ImportListener.java", javaPath, className);
case "vm/xml/mapper.xml.vm" -> fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
case "vm/xml/sub-mapper.xml.vm" ->
fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, genTable.getSubTable().getClassName());

View File

@ -1,5 +1,6 @@
package ${packageName}.controller;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
@ -7,6 +8,7 @@ import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.excel.core.ExcelResult;
import com.ruoyi.common.core.core.domain.R;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
@ -15,8 +17,11 @@ import com.ruoyi.common.web.annotation.RepeatSubmit;
import com.ruoyi.common.web.core.BaseController;
import jakarta.annotation.Resource;
import ${packageName}.domain.vo.${ClassName}Vo;
import ${packageName}.domain.vo.${ClassName}ImportVo;
import ${packageName}.domain.bo.${ClassName}Bo;
import ${packageName}.listener.${ClassName}ImportListener;
import ${packageName}.service.I${ClassName}Service;
import org.springframework.web.multipart.MultipartFile;
#if($table.crud || $table.sub)
import com.ruoyi.common.orm.core.page.TableDataInfo;
@ -68,6 +73,26 @@ public class ${ClassName}Controller extends BaseController
ExcelUtil.exportExcel(list, "${functionName}", ${ClassName}Vo.class, response);
}
/**
* 导入数据
*
* @param file 导入文件
* @param updateSupport 是否更新已存在数据
*/
@Log(title = "${functionName}", businessType = BusinessType.IMPORT)
@SaCheckPermission("${permissionPrefix}:import")
@PostMapping("/importData")
public R<Void> importData(MultipartFile file, boolean updateSupport) throws Exception {
ExcelResult<${ClassName}ImportVo> result = ExcelUtil.importExcel(file.getInputStream(), ${ClassName}ImportVo.class, new ${ClassName}ImportListener(updateSupport));
return R.ok(result.getAnalysis());
}
@SaCheckPermission("${permissionPrefix}:import")
@PostMapping("/importTemplate")
public void importTemplate(HttpServletResponse response) {
ExcelUtil.exportExcel(new ArrayList<>(), "${functionName}", ${ClassName}ImportVo.class, response);
}
/**
* 获取${functionName}详细信息
*/

View File

@ -0,0 +1,126 @@
package ${packageName}.listener;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.ValidatorUtils;
import com.ruoyi.common.excel.core.ExcelListener;
import com.ruoyi.common.excel.core.ExcelResult;
import ${packageName}.domain.bo.${ClassName}Bo;
import ${packageName}.domain.vo.*;
import ${packageName}.service.*;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
/**
* ${functionName}自定义导入
*
* @author ${author}
*/
@Slf4j
public class ${ClassName}ImportListener extends AnalysisEventListener<${ClassName}ImportVo> implements ExcelListener<${ClassName}ImportVo> {
private final I${ClassName}Service ${className}Service;
private final Boolean isUpdateSupport;
private int successNum = 0;
private int failureNum = 0;
private final StringBuilder successMsg = new StringBuilder();
private final StringBuilder failureMsg = new StringBuilder();
public ${ClassName}ImportListener(Boolean isUpdateSupport) {
this.${className}Service = SpringUtils.getBean(I${ClassName}Service.class);
this.isUpdateSupport = isUpdateSupport;
}
@Override
public void invoke(${ClassName}ImportVo ${className}Vo, AnalysisContext context) {
try {
${ClassName}Bo ${className}Bo = BeanUtil.toBean(${className}Vo, ${ClassName}Bo.class);
//TODO:根据某个字段,查询数据库表中是否存在记录,不存在就新增,存在就更新
${ClassName}Vo ${className}Vo1 = null;
#if($table.tree)
${className}Vo1 = ${className}Service.selectById(${className}Vo.get${pkColumn.capJavaField}());
#else
//${className}Vo1 = ${className}Service.selectBySomefield(${className}Vo.getSomefield());
#end
if (ObjectUtil.isNull(${className}Vo1)) {
//不存在就新增
${className}Bo.setVersion(0);
ValidatorUtils.validate(${className}Bo);
#if($table.tree)
boolean inserted = ${className}Service.insertWithPk(${className}Bo);//树表需要前台传来主键值
#else
boolean inserted = ${className}Service.insert(${className}Bo);
#end
if (inserted) {
successNum++;
successMsg.append("<br/>").append(successNum).append("、${functionName} 记录导入成功");
return;
} else {
failureNum++;
failureMsg.append("<br/>").append(failureNum).append("、${functionName} 记录导入失败");
return;
}
} else if (isUpdateSupport) {
//存在就更新
${className}Bo.set${pkColumn.capJavaField}(${className}Vo1.get${pkColumn.capJavaField}());//主键
${className}Bo.setVersion(${className}Vo1.getVersion());
boolean updated = ${className}Service.update(${className}Bo);
if (updated) {
successNum++;
successMsg.append("<br/>").append(successNum).append("、${functionName} 记录更新成功");
return;
} else {
failureNum++;
failureMsg.append("<br/>").append(failureNum).append("、${functionName} 记录更新失败");
return;
}
}
} catch (Exception e) {
failureNum++;
String msg = "<br/>" + failureNum + "、${functionName} 记录导入失败:";
failureMsg.append(msg).append(e.getMessage());
log.error(msg, e);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
@Override
public ExcelResult<${ClassName}ImportVo> getExcelResult() {
return new ExcelResult<>() {
@Override
public String getAnalysis() {
if (failureNum > 0) {
failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据没有成功导入,错误如下:");
throw new ServiceException(failureMsg.toString());
} else {
successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
}
return successMsg.toString();
}
@Override
public List<${ClassName}ImportVo> getList() {
return null;
}
@Override
public List<String> getErrorList() {
return null;
}
};
}
}

View File

@ -51,6 +51,14 @@ public interface I${ClassName}Service extends IBaseService<${ClassName}>
*/
boolean insert(${ClassName}Bo ${className}Bo);
/**
* 新增${functionName},前台提供主键值,一般用于导入的场合
*
* @param ${className}Bo ${functionName}Bo
* @return 结果:true 操作成功false 操作失败
*/
boolean insertWithPk(${ClassName}Bo ${className}Bo);
/**
* 修改${functionName}
*

View File

@ -5,7 +5,9 @@ import java.util.List;
import java.util.Map;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.ruoyi.common.core.utils.MapstructUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.orm.core.page.PageQuery;
@ -149,6 +151,21 @@ public class ${ClassName}ServiceImpl extends BaseServiceImpl<${ClassName}Mapper,
{
${ClassName} ${className} = MapstructUtils.convert(${className}Bo, ${ClassName}.class);
#if($table.tree)
//获取祖级列表字段
Long parentId = ${className}.getParentId();
if (parentId == 0) {
${className}.setAncestors("0");
} else {
${ClassName}Vo parent${ClassName} = selectById(${className}Bo.getParentId());
if (ObjectUtil.isNotNull(parent${ClassName})) {
${className}.setAncestors(parent${ClassName}.getAncestors()+"," +parentId);
} else {
${className}.setAncestors("0");
}
}
#end
#if($table.sub)
boolean inserted = this.save(${className});//使用全局配置的雪花算法主键生成器生成ID值
if (inserted && ObjectUtil.isNotNull(${className})) {
@ -160,6 +177,46 @@ public class ${ClassName}ServiceImpl extends BaseServiceImpl<${ClassName}Mapper,
#end
}
/**
* 新增${functionName},前台提供主键值,一般用于导入的场合
*
* @param ${className}Bo ${functionName}Bo
* @return 结果:true 操作成功false 操作失败
*/
#if($table.sub)
@Transactional
#end
@Override
public boolean insertWithPk(${ClassName}Bo ${className}Bo)
{
${ClassName} ${className} = MapstructUtils.convert(${className}Bo, ${ClassName}.class);
#if($table.tree)
//获取祖级列表字段
Long parentId = ${className}.getParentId();
if (parentId == 0) {
${className}.setAncestors("0");
} else {
${ClassName}Vo parent${ClassName} = selectById(${className}Bo.getParentId());
if (ObjectUtil.isNotNull(parent${ClassName})) {
${className}.setAncestors(parent${ClassName}.getAncestors()+"," +parentId);
} else {
${className}.setAncestors("0");
}
}
#end
#if($table.sub)
boolean inserted = ${className}Mapper.insertWithPk(${className}) > 0;//前台传来主键值
if (inserted && ObjectUtil.isNotNull(${className})) {
return insert${subClassName}(${className});
}
return false;
#else
return ${className}Mapper.insertWithPk(${className}) > 0;//前台传来主键值
#end
}
/**
* 修改${functionName}
*
@ -174,6 +231,17 @@ public class ${ClassName}ServiceImpl extends BaseServiceImpl<${ClassName}Mapper,
{
${ClassName} ${className} = MapstructUtils.convert(${className}Bo, ${ClassName}.class);
if(ObjectUtil.isNotNull(${className}) && ObjectUtil.isNotNull(${className}.get${pkColumn.capJavaField}())) {
#if($table.tree)
//更新祖级列表字段
${ClassName}Vo newParent${ClassName} = selectById(${className}.getParentId());
${ClassName}Vo old${ClassName} = selectById(${className}.get${pkColumn.capJavaField}());
if ( ObjectUtil.isNotNull(newParent${ClassName}) && ObjectUtil.isNotNull(old${ClassName}) ) {
String newAncestors = newParent${ClassName}.getAncestors() + "," + newParent${ClassName}.get${pkColumn.capJavaField}();
String oldAncestors = old${ClassName}.getAncestors();
${className}.setAncestors(newAncestors);
update${ClassName}Children(${className}.get${pkColumn.capJavaField}(), newAncestors, oldAncestors);
}
#end
boolean updated = this.updateById(${className});
#if($table.sub)
if (updated) {
@ -188,6 +256,33 @@ public class ${ClassName}ServiceImpl extends BaseServiceImpl<${ClassName}Mapper,
return false;
}
#if($table.tree)
/**
* 修改子元素关系
*
* @param ${pkColumn.javaField} 主键ID
* @param newAncestors 新的父ID集合
* @param oldAncestors 旧的父ID集合
*/
@Transactional
public void update${ClassName}Children(Long ${pkColumn.javaField}, String newAncestors, String oldAncestors) {
QueryWrapper queryWrapper = QueryWrapper.create()
.from(${CapitalUnderScoreClassName})
.where(QueryMethods.findInSet(QueryMethods.number(${pkColumn.javaField}), ${CapitalUnderScoreClassName}.ANCESTORS).gt(0));
List<${ClassName}Vo> children = this.listAs(queryWrapper, ${ClassName}Vo.class);
for (${ClassName}Vo child : children) {
child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
UpdateChain.of(${ClassName}.class)
.set(${ClassName}::getAncestors, child.getAncestors())
.where(${ClassName}::get${pkColumn.capJavaField}).eq(child.get${pkColumn.capJavaField}())
.update();
}
}
#end
/**
* 批量删除${functionName}
*

View File

@ -0,0 +1,70 @@
package ${packageName}.domain.vo;
#foreach ($import in $importList)
import ${import};
#end
import com.alibaba.excel.annotation.ExcelProperty;
import com.ruoyi.common.excel.annotation.ExcelDictFormat;
import com.ruoyi.common.excel.convert.ExcelDictConvert;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import lombok.NoArgsConstructor;
/**
* ${functionName}导入视图对象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
@Data
@NoArgsConstructor
public class ${ClassName}ImportVo implements Serializable
{
@Serial
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
#if($column.isPk=='1')
#if($table.tree)
/** $column.columnComment */
@ExcelProperty(value = "${column.columnComment}")
private $column.javaType $column.javaField;
#end
#end
#end
#foreach ($column in $columns)
#if($column.isPk!='1')
#if(!$table.isSuperColumn($column.javaField) || ($column.javaField.equals("parentId")) || ($column.javaField.equals("orderNum")))
/** $column.columnComment */
#if($column.list)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if(${column.dictType} && ${column.dictType} != '')
@ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "${column.dictType}")
#elseif($parentheseIndex != -1)
@ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class)
@ExcelDictFormat(readConverterExp = "$column.readConverterExp()")
#else
@ExcelProperty(value = "${comment}")
#end
private $column.javaType $column.javaField;
#else
@ExcelProperty(value = "${column.columnComment}")
private $column.javaType $column.javaField;
#end
#end
#end
#end
}

View File

@ -73,7 +73,10 @@
<el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['${moduleName}:${businessName}:add']">新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="success" plain icon="Download" @click="handleExport()" v-hasPermi="['${moduleName}:${businessName}:export']">导出</el-button>
<el-button type="success" plain icon="Top" @click="handleImport()" v-hasPermi="['${moduleName}:${businessName}:import']">导入</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="warning" plain icon="Download" @click="handleExport()" v-hasPermi="['${moduleName}:${businessName}:export']">导出</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
@ -271,12 +274,50 @@
</div>
</template>
</el-dialog>
<!-- 导入对话框 -->
<el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
<el-upload
ref="uploadRef"
: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
>
<el-icon class="el-icon--upload">
<i-ep-upload-filled />
</el-icon>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<template #tip>
<div class="text-center el-upload__tip">
<div class="el-upload__tip">
<el-checkbox v-model="upload.updateSupport" />
是否更新已经存在的${functionName}数据
</div>
<span>仅允许导入xls、xlsx格式文件。</span>
<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板 </el-link>
</div>
</template>
</el-upload>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="${BusinessName}" lang="ts">
<script setup lang="ts">
import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName} } from "@/api/${moduleName}/${businessName}";
import { ${BusinessName}VO, ${BusinessName}Query, ${BusinessName}Form } from '@/api/${moduleName}/${businessName}/types';
import { globalHeaders } from '@/utils/request';
type ${BusinessName}Option = {
${treeCode}: number;
@ -286,10 +327,10 @@
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
#if(${dicts} != '')
#set($dictsNoSymbol=$dicts.replace("'", ""))
const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
#end
#if(${dicts} != '')
#set($dictsNoSymbol=$dicts.replace("'", ""))
const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
#end
const ${businessName}List = ref<${BusinessName}VO[]>([]);
const ${businessName}Options = ref<${BusinessName}Option[]>([]);
@ -301,18 +342,35 @@
const queryFormRef = ref<ElFormInstance>();
const ${businessName}FormRef = ref<ElFormInstance>();
const ${businessName}TableRef = ref<ElTableInstance>()
const uploadRef = ref<ElUploadInstance>();
/*** 导入参数 */
const upload = reactive<ImportOption>({
// 是否显示弹出层(导入)
open: false,
// 弹出层标题(导入)
title: '',
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 1,
// 设置上传的请求头部
headers: globalHeaders(),
// 上传的地址
url: import.meta.env.VITE_APP_BASE_API + '/${moduleName}/${businessName}/importData'
});
const dialog = reactive<DialogOption>({
visible: false,
title: ''
});
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
const dateRange${AttrName} = ref<[DateModelType, DateModelType]>(['', '']);
#end
#end
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
const dateRange${AttrName} = ref<[DateModelType, DateModelType]>(['', '']);
#end
#end
const initFormData: ${BusinessName}Form = {
#foreach ($column in $columns)
@ -456,6 +514,37 @@
);
};
/** 导入按钮操作 */
const handleImport = () => {
upload.title = '${functionName}导入';
upload.open = true;
};
/** 下载模板操作 */
const importTemplate = () => {
proxy?.download('${moduleName}/${businessName}/importTemplate', {}, `${businessName}_template.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
upload.open = false;
upload.isUploading = false;
uploadRef.value?.handleRemove(file);
ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
dangerouslyUseHTMLString: true
});
getList();
};
/** 提交上传文件 */
function submitFileForm() {
uploadRef.value?.submit();
}
/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
isExpandAll.value = !isExpandAll.value;

View File

@ -78,6 +78,9 @@
<el-col :span="1.5">
<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['${moduleName}:${businessName}:remove']">删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="success" plain icon="Top" @click="handleImport()" v-hasPermi="['${moduleName}:${businessName}:import']">导入</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['${moduleName}:${businessName}:export']">导出</el-button>
</el-col>
@ -332,16 +335,54 @@
</div>
</template>
</el-dialog>
<!-- 导入对话框 -->
<el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
<el-upload
ref="uploadRef"
: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
>
<el-icon class="el-icon--upload">
<i-ep-upload-filled />
</el-icon>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<template #tip>
<div class="text-center el-upload__tip">
<div class="el-upload__tip">
<el-checkbox v-model="upload.updateSupport" />
是否更新已经存在的${functionName}数据
</div>
<span>仅允许导入xls、xlsx格式文件。</span>
<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板 </el-link>
</div>
</template>
</el-upload>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="${BusinessName}" lang="ts">
<script setup lang="ts">
import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName} } from '@/api/${moduleName}/${businessName}';
#if($table.sub)
import { ${BusinessName}VO, ${subClassName}VO, ${BusinessName}Query, ${BusinessName}Form } from '@/api/${moduleName}/${businessName}/types';
#else
import { ${BusinessName}VO, ${BusinessName}Query, ${BusinessName}Form } from '@/api/${moduleName}/${businessName}/types';
#end
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
#if(${dicts} != '')
@ -379,6 +420,23 @@ const dateRange${AttrName} = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const ${businessName}FormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();
/*** 导入参数 */
const upload = reactive<ImportOption>({
// 是否显示弹出层(导入)
open: false,
// 弹出层标题(导入)
title: '',
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 1,
// 设置上传的请求头部
headers: globalHeaders(),
// 上传的地址
url: import.meta.env.VITE_APP_BASE_API + '/${moduleName}/${businessName}/importData'
});
const dialog = reactive<DialogOption>({
visible: false,
@ -611,6 +669,37 @@ const handleExport = () => {
}, `${businessName}_#[[${new Date().getTime()}]]#.xlsx`)
};
/** 导入按钮操作 */
const handleImport = () => {
upload.title = '${functionName}导入';
upload.open = true;
};
/** 下载模板操作 */
const importTemplate = () => {
proxy?.download('${moduleName}/${businessName}/importTemplate', {}, `${businessName}_template.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
upload.open = false;
upload.isUploading = false;
uploadRef.value?.handleRemove(file);
ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
dangerouslyUseHTMLString: true
});
getList();
};
/** 提交上传文件 */
function submitFileForm() {
uploadRef.value?.submit();
}
onMounted(() => {
getList();
});