代码生成新增导入

This commit is contained in:
不做码农 2023-07-28 17:37:36 +08:00
parent 84ae9b0a92
commit 2ad3ea1fd8
12 changed files with 160 additions and 26 deletions

View File

@ -58,9 +58,11 @@ namespace ZR.Admin.WebApi.Controllers
/// <returns></returns>
protected IActionResult ExportExcel(string path, string fileName)
{
//IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
//string fileDir = Path.Combine(webHostEnvironment.WebRootPath, path, fileName);
//var webHostEnvironment = App.WebHostEnvironment;
if (!Path.Exists(path))
{
throw new CustomException(fileName + "文件不存在");
}
var stream = Io.File.OpenRead(path); //创建文件流
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
@ -169,23 +171,23 @@ namespace ZR.Admin.WebApi.Controllers
/// <summary>
/// 下载导入模板
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="stream"></param>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">空数据类型集合</param>
/// <param name="fileName">下载文件名</param>
/// <returns></returns>
protected string DownloadImportTemplate<T>(List<T> list, Stream stream, string fileName)
protected (string, string) DownloadImportTemplate<T>(List<T> list, string fileName)
{
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
string sFileName = $"{fileName}模板.xlsx";
string newFileName = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName);
IWebHostEnvironment webHostEnvironment = App.WebHostEnvironment;
string sFileName = $"{fileName}.xlsx";
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName);
if (!Directory.Exists(newFileName))
//不存在模板创建模板
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(Path.GetDirectoryName(newFileName));
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
MiniExcel.SaveAs(fullPath, list, overwriteFile: true);
}
MiniExcel.SaveAs(newFileName, list);
return sFileName;
return (sFileName, fullPath);
}
/// <summary>

View File

@ -280,7 +280,7 @@ namespace ZR.Admin.WebApi.Controllers
CodeGeneratorTool.Generate(dto);
if (genTableInfo.Options.GenerateMenu)
{
SysMenuService.AddSysMenu(genTableInfo, dto.ReplaceDto.PermissionPrefix, dto.ReplaceDto.ShowBtnEdit, dto.ReplaceDto.ShowBtnExport);
SysMenuService.AddSysMenu(genTableInfo, dto.ReplaceDto.PermissionPrefix, dto.ReplaceDto.ShowBtnEdit, dto.ReplaceDto.ShowBtnExport, dto.ReplaceDto.ShowBtnImport);
}
foreach (var item in dto.GenCodes)

View File

@ -0,0 +1,7 @@
global using ZR.Common;
global using Microsoft.AspNetCore.Authorization;
global using Infrastructure;
global using Infrastructure.Attribute;
global using Infrastructure.Enums;
global using Infrastructure.Model;
global using Mapster;

View File

@ -1,15 +1,12 @@
using Infrastructure;
using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Model;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using ${options.DtosNamespace};
using ${options.ModelsNamespace}.${options.SubNamespace};
using ${options.IServicsNamespace}.${options.SubNamespace}.I${options.SubNamespace}Service;
using ${options.ApiControllerNamespace}.Extensions;
using ${options.ApiControllerNamespace}.Filters;
using ${options.BaseNamespace}Common;
$if(replaceDto.ShowBtnImport)
using MiniExcelLibs;
$end
//创建时间:${replaceDto.AddTime}
namespace ${options.ApiControllerNamespace}.Controllers
@ -168,6 +165,40 @@ $if(replaceDto.ShowBtnTruncate)
}
$end
$if(replaceDto.ShowBtnImport)
/// <summary>
/// 导入
/// </summary>
/// <param name="formFile"></param>
/// <returns></returns>
[HttpPost("importData")]
[Log(Title = "${genTable.FunctionName}导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false, IsSaveResponseData = true)]
[ActionPermissionFilter(Permission = "${replaceDto.PermissionPrefix}:import")]
public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
{
List<${replaceDto.ModelTypeName}> list = new();
using (var stream = formFile.OpenReadStream())
{
list = stream.Query<${replaceDto.ModelTypeName}>(startCell: "A1").ToList();
}
return SUCCESS(_${replaceDto.ModelTypeName}Service.Import${replaceDto.ModelTypeName}(list));
}
/// <summary>
/// ${genTable.FunctionName}导入模板下载
/// </summary>
/// <returns></returns>
[HttpGet("importTemplate")]
[Log(Title = "${genTable.FunctionName}模板", BusinessType = BusinessType.EXPORT, IsSaveRequestData = true, IsSaveResponseData = false)]
[AllowAnonymous]
public IActionResult ImportTemplateExcel()
{
var result = DownloadImportTemplate(new List<${replaceDto.ModelTypeName}>() { }, "${replaceDto.ModelTypeName}");
return ExportExcel(result.Item2, result.Item1);
}
$end
$if(showCustomInput)
/// <summary>
/// 保存排序

View File

@ -24,5 +24,9 @@ $end
$if(replaceDto.ShowBtnTruncate)
bool Truncate${replaceDto.ModelTypeName}();
$end
$if(replaceDto.ShowBtnImport)
(string, object, object) Import${replaceDto.ModelTypeName}(List<${replaceDto.ModelTypeName}> list);
$end
}
}

View File

@ -159,5 +159,40 @@ $if(replaceDto.ShowBtnTruncate)
return Truncate();
}
$end
$if(replaceDto.ShowBtnImport)
/// <summary>
/// 导入${genTable.FunctionName}
/// </summary>
/// <returns></returns>
public (string, object, object) Import${replaceDto.ModelTypeName}(List<${replaceDto.ModelTypeName}> list)
{
var x = Context.Storageable(list)
.SplitInsert(it => !it.Any())
$foreach(column in genTable.Columns)
$if(column.IsRequired && column.IsIncrement == false)
.SplitError(x => x.Item.${column.CsharpField}.IsEmpty(), "${column.ColumnComment}不能为空")
$end
$end
//.WhereColumns(it => it.UserName)//如果不是主键可以这样实现多字段it=>new{it.x1,it.x2}
.ToStorage();
var result = x.AsInsertable.ExecuteCommand();//插入可插入部分;
string msg = $"插入{x.InsertList.Count} 更新{x.UpdateList.Count} 错误数据{x.ErrorList.Count} 不计算数据{x.IgnoreList.Count} 删除数据{x.DeleteList.Count} 总共{x.TotalList.Count}";
Console.WriteLine(msg);
//输出错误信息
foreach (var item in x.ErrorList)
{
Console.WriteLine("错误" + item.StorageMessage);
}
foreach (var item in x.IgnoreList)
{
Console.WriteLine("忽略" + item.StorageMessage);
}
return (msg, x.ErrorList, x.IgnoreList);
}
$end
}
}

View File

@ -108,6 +108,25 @@ $if(replaceDto.ShowBtnTruncate)
</el-button>
</el-col>
$end
$if(replaceDto.ShowBtnImport)
<el-col :span="1.5">
<el-dropdown trigger="click" v-hasPermi="['${replaceDto.PermissionPrefix}:import']">
<el-button type="primary" plain icon="Upload">
{{ ${t}t('btn.import') }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="upload">
<importData
templateUrl="${genTable.ModuleName}/${genTable.BusinessName}/importTemplate"
importUrl="/${genTable.ModuleName}/${genTable.BusinessName}/importData"
@success="handleFileSuccess"></importData>
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</el-col>
$end
$if(replaceDto.ShowBtnExport)
<el-col :span="1.5">
<el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['${replaceDto.PermissionPrefix}:export']">
@ -136,7 +155,7 @@ $end
$if(sub)
<el-table-column align="center" width="90">
<template #default="scope">
<el-button text @click="rowClick(scope.row)">详情</el-button>
<el-button text @click="rowClick(scope.row)">{{ ${t}t('btn.details') }}</el-button>
</template>
</el-table-column>
$end
@ -194,7 +213,7 @@ $end
</el-button-group>
$else
$if(replaceDto.ShowBtnView)
<el-button type="primary" icon="view" @click="handlePreview(scope.row)"></el-button>
<el-button type="primary" icon="view" title="详情" @click="handlePreview(scope.row)"></el-button>
$end
$if(replaceDto.ShowBtnEdit)
<el-button v-hasPermi="['${replaceDto.PermissionPrefix}:edit']" type="success" icon="edit" title="编辑" @click="handleUpdate(scope.row)"></el-button>
@ -426,7 +445,9 @@ from '@/api/${tool.FirstLowerCase(genTable.ModuleName)}/${genTable.BusinessName.
$if(replaceDto.ShowEditor == 1)
import Editor from '@/components/Editor'
$end
$if(replaceDto.ShowBtnImport)
import importData from '@/components/ImportData'
$end
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
@ -746,6 +767,20 @@ function handlePreview(row) {
}
$end
$if(replaceDto.ShowBtnImport)
// 导入数据成功处理
const handleFileSuccess = (response) => {
const { item1, item2 } = response.data
var error = ''
item2.forEach((item) => {
error += item.storageMessage + ','
})
proxy.${alert}alert(item1 + '<p>' + error + '</p>', '导入结果', {
dangerouslyUseHTMLString: true
})
}
$end
$if(replaceDto.ShowBtnExport)
// 导出按钮操作
function handleExport() {

View File

@ -50,6 +50,7 @@ namespace ZR.CodeGenerator
ShowBtnView = dto.GenTable.Options.CheckedBtn.Any(f => f == 5),
ShowBtnTruncate = dto.GenTable.Options.CheckedBtn.Any(f => f == 6),
ShowBtnMultiDel = dto.GenTable.Options.CheckedBtn.Any(f => f == 7),
ShowBtnImport = dto.GenTable.Options.CheckedBtn.Any(f => f == 8),
ViewFileName = dto.GenTable.BusinessName.FirstUpperCase(),
OperBtnStyle = dto.GenTable.Options.OperBtnStyle
};
@ -586,6 +587,7 @@ namespace ZR.CodeGenerator
options.Data.Set("refs", "$");//特殊标签替换
options.Data.Set("t", "$");//特殊标签替换
options.Data.Set("modal", "$");//特殊标签替换
options.Data.Set("alert", "$");//特殊标签替换
options.Data.Set("index", "$");//特殊标签替换
options.Data.Set("confirm", "$");//特殊标签替换
options.Data.Set("nextTick", "$");

View File

@ -50,6 +50,7 @@ namespace ZR.CodeGenerator.Model
public bool ShowBtnView { get; set; }
public bool ShowBtnTruncate { get; set; }
public bool ShowBtnMultiDel { get; set; }
public bool ShowBtnImport { get; set; }
/// <summary>
/// 上传URL data
/// </summary>

View File

@ -0,0 +1 @@
global using System.Collections.Generic;

View File

@ -39,7 +39,7 @@ namespace ZR.Service.System.IService
List<TreeSelectVo> BuildMenuTreeSelect(List<SysMenu> menus);
void AddSysMenu(GenTable genTableInfo, string permPrefix, bool showEdit, bool showExport);
void AddSysMenu(GenTable genTableInfo, string permPrefix, bool showEdit, bool showExport, bool showImport);
List<SysMenu> SelectTreeMenuListByRoles(MenuQueryDto menu, List<long> roles);
List<RoleMenuExportDto> SelectRoleMenuListByRole(MenuQueryDto menu, int roleId);
}

View File

@ -588,7 +588,7 @@ namespace ZR.Service
#endregion
public void AddSysMenu(GenTable genTableInfo, string permPrefix, bool showEdit, bool showExport)
public void AddSysMenu(GenTable genTableInfo, string permPrefix, bool showEdit, bool showExport, bool showImport)
{
var menu = GetFirst(f => f.MenuName == genTableInfo.FunctionName);
if (menu is null)
@ -671,6 +671,18 @@ namespace ZR.Service
Icon = "",
};
SysMenu menuImport = new()
{
MenuName = "导入",
ParentId = menu.MenuId,
OrderNum = 5,
Perms = $"{permPrefix}:import",
MenuType = "F",
Visible = "0",
Status = "0",
Icon = "",
};
menuList.Add(menuQuery);
menuList.Add(menuAdd);
menuList.Add(menuDel);
@ -682,6 +694,10 @@ namespace ZR.Service
{
menuList.Add(menuExport);
}
if (showImport)
{
menuList.Add(menuImport);
}
//Insert(menuList);
var x = Storageable(menuList)