From fa2508b79018ae808fa584180274a69c178cc44e Mon Sep 17 00:00:00 2001 From: xiaochanghai Date: Fri, 10 Jan 2025 15:04:20 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=9A=E7=94=A8Excel=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Tiobon.Core.Common/Attribute/QueryFilter.cs | 7 +- Tiobon.Core.Common/Helper/FileHelper.cs | 747 +++++++++--------- Tiobon.Core.Common/Helper/UtilHelper.cs | 531 ++++++------- Tiobon.Core.DataAccess/ReportHelper.cs | 295 ++++++- Tiobon.Core.Services/BASE/BaseServices.cs | 36 +- .../Ghrh/Ghrh_HumanRequestServices.cs | 281 ++----- Tiobon.Core/Tiobon.Core.xml | 7 - 7 files changed, 1041 insertions(+), 863 deletions(-) diff --git a/Tiobon.Core.Common/Attribute/QueryFilter.cs b/Tiobon.Core.Common/Attribute/QueryFilter.cs index f19c53c6..9e77159f 100644 --- a/Tiobon.Core.Common/Attribute/QueryFilter.cs +++ b/Tiobon.Core.Common/Attribute/QueryFilter.cs @@ -148,9 +148,9 @@ public class QueryForm1 public string token { get; set; } public string procName { get; set; } public string timestamp { get; set; } - public string userId { get; set; } + public string userId { get; set; } public object jsonParam { get; set; } - + } @@ -205,8 +205,9 @@ public class QueryExportColumn public string elementType { get; set; } public string commentText { get; set; } + public string dataSourceType { get; set; } - + public int? dataSourceId { get; set; } } public class QueryExportReturn diff --git a/Tiobon.Core.Common/Helper/FileHelper.cs b/Tiobon.Core.Common/Helper/FileHelper.cs index 6b2c3e2d..74cd72bc 100644 --- a/Tiobon.Core.Common/Helper/FileHelper.cs +++ b/Tiobon.Core.Common/Helper/FileHelper.cs @@ -1,411 +1,430 @@ -using System; -using System.IO; -using System.Linq; +using System.IO; using System.Text; -namespace Tiobon.Core.Common.Helper +namespace Tiobon.Core.Common.Helper; + +public class FileHelper : IDisposable { - public class FileHelper : IDisposable + + private bool _alreadyDispose = false; + + #region 构造函数 + public FileHelper() { + // + // TODO: 在此处添加构造函数逻辑 + // + } + ~FileHelper() + { + Dispose(); ; + } - private bool _alreadyDispose = false; + protected virtual void Dispose(bool isDisposing) + { + if (_alreadyDispose) return; + _alreadyDispose = true; + } + #endregion - #region 构造函数 - public FileHelper() - { - // - // TODO: 在此处添加构造函数逻辑 - // - } - ~FileHelper() - { - Dispose(); ; - } + #region IDisposable 成员 - protected virtual void Dispose(bool isDisposing) + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + #endregion + + #region 取得文件后缀名 + /**************************************** + * 函数名称:GetPostfixStr + * 功能说明:取得文件后缀名 + * 参 数:filename:文件名称 + * 调用示列: + * string filename = "aaa.aspx"; + * string s = EC.FileObj.GetPostfixStr(filename); + *****************************************/ + /// + /// 取后缀名 + /// + /// 文件名 + /// .gif|.html格式 + public static string GetPostfixStr(string filename) + { + int start = filename.LastIndexOf("."); + int length = filename.Length; + string postfix = filename.Substring(start, length - start); + return postfix; + } + #endregion + + #region 根据文件大小获取指定前缀的可用文件名 + /// + /// 根据文件大小获取指定前缀的可用文件名 + /// + /// 文件夹 + /// 文件前缀 + /// 文件大小(1m) + /// 文件后缀(.log) + /// 可用文件名 + public static string GetAvailableFileWithPrefixOrderSize(string folderPath, string prefix, int size = 1 * 1024 * 1024, string ext = ".log") + { + //var allFiles = new DirectoryInfo(folderPath); + //var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList(); + + //if (selectFiles.Count > 0) + //{ + // return selectFiles.FirstOrDefault().FullName; + //} + return Path.Combine(folderPath, $@"{prefix}.log"); + } + public static string GetAvailableFileNameWithPrefixOrderSize(string _contentRoot, string prefix, int size = 1 * 1024 * 1024, string ext = ".log") + { + var folderPath = Path.Combine(_contentRoot, "Log"); + if (!Directory.Exists(folderPath)) { - if (_alreadyDispose) return; - _alreadyDispose = true; + Directory.CreateDirectory(folderPath); } - #endregion - #region IDisposable 成员 + var allFiles = new DirectoryInfo(folderPath); + var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList(); - public void Dispose() + if (selectFiles.Count > 0) { - Dispose(true); - GC.SuppressFinalize(this); + return selectFiles.FirstOrDefault().Name.Replace(".log", ""); } - #endregion - - #region 取得文件后缀名 - /**************************************** - * 函数名称:GetPostfixStr - * 功能说明:取得文件后缀名 - * 参 数:filename:文件名称 - * 调用示列: - * string filename = "aaa.aspx"; - * string s = EC.FileObj.GetPostfixStr(filename); - *****************************************/ - /// - /// 取后缀名 - /// - /// 文件名 - /// .gif|.html格式 - public static string GetPostfixStr(string filename) + return $@"{prefix}_{DateTime.Now.DateToTimeStamp()}"; + } + #endregion + + #region 写文件 + /**************************************** + * 函数名称:WriteFile + * 功能说明:写文件,会覆盖掉以前的内容 + * 参 数:Path:文件路径,Strings:文本内容 + * 调用示列: + * string Path = Server.MapPath("Default2.aspx"); + * string Strings = "这是我写的内容啊"; + * EC.FileObj.WriteFile(Path,Strings); + *****************************************/ + /// + /// 写文件 + /// + /// 文件路径 + /// 文件内容 + public static void WriteFile(string Path, string Strings) + { + if (!File.Exists(Path)) { - int start = filename.LastIndexOf("."); - int length = filename.Length; - string postfix = filename.Substring(start, length - start); - return postfix; + FileStream f = File.Create(Path); + f.Close(); } - #endregion - - #region 根据文件大小获取指定前缀的可用文件名 - /// - /// 根据文件大小获取指定前缀的可用文件名 - /// - /// 文件夹 - /// 文件前缀 - /// 文件大小(1m) - /// 文件后缀(.log) - /// 可用文件名 - public static string GetAvailableFileWithPrefixOrderSize(string folderPath, string prefix, int size = 1 * 1024 * 1024, string ext = ".log") + StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312")); + f2.Write(Strings); + f2.Close(); + f2.Dispose(); + } + /// + /// 写文件 + /// + /// 文件路径 + /// 文件内容 + public static void WriteFile(string Path, byte[] buf) + { + if (!File.Exists(Path)) { - //var allFiles = new DirectoryInfo(folderPath); - //var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList(); - - //if (selectFiles.Count > 0) - //{ - // return selectFiles.FirstOrDefault().FullName; - //} - return Path.Combine(folderPath, $@"{prefix}.log"); + FileStream f = File.Create(Path); + f.Close(); } - public static string GetAvailableFileNameWithPrefixOrderSize(string _contentRoot, string prefix, int size = 1 * 1024 * 1024, string ext = ".log") - { - var folderPath = Path.Combine(_contentRoot, "Log"); - if (!Directory.Exists(folderPath)) - { - Directory.CreateDirectory(folderPath); - } - - var allFiles = new DirectoryInfo(folderPath); - var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList(); - - if (selectFiles.Count > 0) - { - return selectFiles.FirstOrDefault().Name.Replace(".log", ""); - } + FileStream f2 = new FileStream(Path, FileMode.Create, FileAccess.Write); + f2.Write(buf, 0, buf.Length); + f2.Close(); + f2.Dispose(); + } - return $@"{prefix}_{DateTime.Now.DateToTimeStamp()}"; - } - #endregion - - #region 写文件 - /**************************************** - * 函数名称:WriteFile - * 功能说明:写文件,会覆盖掉以前的内容 - * 参 数:Path:文件路径,Strings:文本内容 - * 调用示列: - * string Path = Server.MapPath("Default2.aspx"); - * string Strings = "这是我写的内容啊"; - * EC.FileObj.WriteFile(Path,Strings); - *****************************************/ - /// - /// 写文件 - /// - /// 文件路径 - /// 文件内容 - public static void WriteFile(string Path, string Strings) + /// + /// 写文件 + /// + /// 文件路径 + /// 文件内容 + /// 编码格式 + public static void WriteFile(string Path, string Strings, Encoding encode) + { + if (!File.Exists(Path)) { - if (!File.Exists(Path)) - { - FileStream f = File.Create(Path); - f.Close(); - } - StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312")); - f2.Write(Strings); - f2.Close(); - f2.Dispose(); + FileStream f = File.Create(Path); + f.Close(); } - /// - /// 写文件 - /// - /// 文件路径 - /// 文件内容 - public static void WriteFile(string Path, byte[] buf) + StreamWriter f2 = new StreamWriter(Path, false, encode); + f2.Write(Strings); + f2.Close(); + f2.Dispose(); + } + #endregion + + #region 读文件 + /**************************************** + * 函数名称:ReadFile + * 功能说明:读取文本内容 + * 参 数:Path:文件路径 + * 调用示列: + * string Path = Server.MapPath("Default2.aspx"); + * string s = EC.FileObj.ReadFile(Path); + *****************************************/ + /// + /// 读文件 + /// + /// 文件路径 + /// + public static string ReadFile(string Path) + { + string s = ""; + if (!File.Exists(Path)) + s = "不存在相应的目录"; + else { - if (!File.Exists(Path)) - { - FileStream f = File.Create(Path); - f.Close(); - } - FileStream f2 = new FileStream(Path, FileMode.Create, FileAccess.Write); - f2.Write(buf, 0, buf.Length); + StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312")); + s = f2.ReadToEnd(); f2.Close(); f2.Dispose(); } - /// - /// 写文件 - /// - /// 文件路径 - /// 文件内容 - /// 编码格式 - public static void WriteFile(string Path, string Strings, Encoding encode) + return s; + } + + /// + /// 读文件 + /// + /// 文件路径 + /// 编码格式 + /// + public static string ReadFile(string Path, Encoding encode) + { + string s = ""; + if (!File.Exists(Path)) + s = "不存在相应的目录"; + else { - if (!File.Exists(Path)) - { - FileStream f = File.Create(Path); - f.Close(); - } - StreamWriter f2 = new StreamWriter(Path, false, encode); - f2.Write(Strings); + StreamReader f2 = new StreamReader(Path, encode); + s = f2.ReadToEnd(); f2.Close(); f2.Dispose(); } - #endregion - - #region 读文件 - /**************************************** - * 函数名称:ReadFile - * 功能说明:读取文本内容 - * 参 数:Path:文件路径 - * 调用示列: - * string Path = Server.MapPath("Default2.aspx"); - * string s = EC.FileObj.ReadFile(Path); - *****************************************/ - /// - /// 读文件 - /// - /// 文件路径 - /// - public static string ReadFile(string Path) + + return s; + } + #endregion + + #region 追加文件 + /**************************************** + * 函数名称:FileAdd + * 功能说明:追加文件内容 + * 参 数:Path:文件路径,strings:内容 + * 调用示列: + * string Path = Server.MapPath("Default2.aspx"); + * string Strings = "新追加内容"; + * EC.FileObj.FileAdd(Path, Strings); + *****************************************/ + /// + /// 追加文件 + /// + /// 文件路径 + /// 内容 + public static void FileAdd(string Path, string strings) + { + StreamWriter sw = File.AppendText(Path); + sw.Write(strings); + sw.Flush(); + sw.Close(); + } + #endregion + + #region 拷贝文件 + /**************************************** + * 函数名称:FileCoppy + * 功能说明:拷贝文件 + * 参 数:OrignFile:原始文件,NewFile:新文件路径 + * 调用示列: + * string orignFile = Server.MapPath("Default2.aspx"); + * string NewFile = Server.MapPath("Default3.aspx"); + * EC.FileObj.FileCoppy(OrignFile, NewFile); + *****************************************/ + /// + /// 拷贝文件 + /// + /// 原始文件 + /// 新文件路径 + public static void FileCoppy(string orignFile, string NewFile) + { + File.Copy(orignFile, NewFile, true); + } + + #endregion + + #region 删除文件 + /**************************************** + * 函数名称:FileDel + * 功能说明:删除文件 + * 参 数:Path:文件路径 + * 调用示列: + * string Path = Server.MapPath("Default3.aspx"); + * EC.FileObj.FileDel(Path); + *****************************************/ + /// + /// 删除文件 + /// + /// 路径 + public static void FileDel(string Path) + { + File.Delete(Path); + } + #endregion + + #region 移动文件 + /**************************************** + * 函数名称:FileMove + * 功能说明:移动文件 + * 参 数:OrignFile:原始路径,NewFile:新文件路径 + * 调用示列: + * string orignFile = Server.MapPath("../说明.txt"); + * string NewFile = Server.MapPath("http://www.cnTiobons.com/说明.txt"); + * EC.FileObj.FileMove(OrignFile, NewFile); + *****************************************/ + /// + /// 移动文件 + /// + /// 原始路径 + /// 新路径 + public static void FileMove(string orignFile, string NewFile) + { + File.Move(orignFile, NewFile); + } + #endregion + + #region 在当前目录下创建目录 + /**************************************** + * 函数名称:FolderCreate + * 功能说明:在当前目录下创建目录 + * 参 数:OrignFolder:当前目录,NewFloder:新目录 + * 调用示列: + * string orignFolder = Server.MapPath("test/"); + * string NewFloder = "new"; + * EC.FileObj.FolderCreate(OrignFolder, NewFloder); + *****************************************/ + /// + /// 在当前目录下创建目录 + /// + /// 当前目录 + /// 新目录 + public static void FolderCreate(string orignFolder, string NewFloder) + { + Directory.SetCurrentDirectory(orignFolder); + Directory.CreateDirectory(NewFloder); + } + #endregion + + #region 递归删除文件夹目录及文件 + /**************************************** + * 函数名称:DeleteFolder + * 功能说明:递归删除文件夹目录及文件 + * 参 数:dir:文件夹路径 + * 调用示列: + * string dir = Server.MapPath("test/"); + * EC.FileObj.DeleteFolder(dir); + *****************************************/ + /// + /// 递归删除文件夹目录及文件 + /// + /// + /// + public static void DeleteFolder(string dir) + { + if (Directory.Exists(dir)) //如果存在这个文件夹删除之 { - string s = ""; - if (!File.Exists(Path)) - s = "不存在相应的目录"; - else + foreach (string d in Directory.GetFileSystemEntries(dir)) { - StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312")); - s = f2.ReadToEnd(); - f2.Close(); - f2.Dispose(); + if (File.Exists(d)) + File.Delete(d); //直接删除其中的文件 + else + DeleteFolder(d); //递归删除子文件夹 } - - return s; + Directory.Delete(dir); //删除已空文件夹 } - /// - /// 读文件 - /// - /// 文件路径 - /// 编码格式 - /// - public static string ReadFile(string Path, Encoding encode) + } + #endregion + + #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 + /**************************************** + * 函数名称:CopyDir + * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 + * 参 数:srcPath:原始路径,aimPath:目标文件夹 + * 调用示列: + * string srcPath = Server.MapPath("test/"); + * string aimPath = Server.MapPath("test1/"); + * EC.FileObj.CopyDir(srcPath,aimPath); + *****************************************/ + /// + /// 指定文件夹下面的所有内容copy到目标文件夹下面 + /// + /// 原始路径 + /// 目标文件夹 + public static void CopyDir(string srcPath, string aimPath) + { + try { - string s = ""; - if (!File.Exists(Path)) - s = "不存在相应的目录"; - else + // 检查目标目录是否以目录分割字符结束如果不是则添加之 + if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) + aimPath += Path.DirectorySeparatorChar; + // 判断目标目录是否存在如果不存在则新建之 + if (!Directory.Exists(aimPath)) + Directory.CreateDirectory(aimPath); + // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 + //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 + //string[] fileList = Directory.GetFiles(srcPath); + string[] fileList = Directory.GetFileSystemEntries(srcPath); + //遍历所有的文件和目录 + foreach (string file in fileList) { - StreamReader f2 = new StreamReader(Path, encode); - s = f2.ReadToEnd(); - f2.Close(); - f2.Dispose(); + //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 + + if (Directory.Exists(file)) + CopyDir(file, aimPath + Path.GetFileName(file)); + //否则直接Copy文件 + else + File.Copy(file, aimPath + Path.GetFileName(file), true); } - return s; - } - #endregion - - #region 追加文件 - /**************************************** - * 函数名称:FileAdd - * 功能说明:追加文件内容 - * 参 数:Path:文件路径,strings:内容 - * 调用示列: - * string Path = Server.MapPath("Default2.aspx"); - * string Strings = "新追加内容"; - * EC.FileObj.FileAdd(Path, Strings); - *****************************************/ - /// - /// 追加文件 - /// - /// 文件路径 - /// 内容 - public static void FileAdd(string Path, string strings) - { - StreamWriter sw = File.AppendText(Path); - sw.Write(strings); - sw.Flush(); - sw.Close(); } - #endregion - - #region 拷贝文件 - /**************************************** - * 函数名称:FileCoppy - * 功能说明:拷贝文件 - * 参 数:OrignFile:原始文件,NewFile:新文件路径 - * 调用示列: - * string orignFile = Server.MapPath("Default2.aspx"); - * string NewFile = Server.MapPath("Default3.aspx"); - * EC.FileObj.FileCoppy(OrignFile, NewFile); - *****************************************/ - /// - /// 拷贝文件 - /// - /// 原始文件 - /// 新文件路径 - public static void FileCoppy(string orignFile, string NewFile) + catch (Exception ee) { - File.Copy(orignFile, NewFile, true); + throw new Exception(ee.ToString()); } + } + #endregion - #endregion - - #region 删除文件 - /**************************************** - * 函数名称:FileDel - * 功能说明:删除文件 - * 参 数:Path:文件路径 - * 调用示列: - * string Path = Server.MapPath("Default3.aspx"); - * EC.FileObj.FileDel(Path); - *****************************************/ - /// - /// 删除文件 - /// - /// 路径 - public static void FileDel(string Path) - { - File.Delete(Path); - } - #endregion - - #region 移动文件 - /**************************************** - * 函数名称:FileMove - * 功能说明:移动文件 - * 参 数:OrignFile:原始路径,NewFile:新文件路径 - * 调用示列: - * string orignFile = Server.MapPath("../说明.txt"); - * string NewFile = Server.MapPath("http://www.cnTiobons.com/说明.txt"); - * EC.FileObj.FileMove(OrignFile, NewFile); - *****************************************/ - /// - /// 移动文件 - /// - /// 原始路径 - /// 新路径 - public static void FileMove(string orignFile, string NewFile) - { - File.Move(orignFile, NewFile); - } - #endregion - - #region 在当前目录下创建目录 - /**************************************** - * 函数名称:FolderCreate - * 功能说明:在当前目录下创建目录 - * 参 数:OrignFolder:当前目录,NewFloder:新目录 - * 调用示列: - * string orignFolder = Server.MapPath("test/"); - * string NewFloder = "new"; - * EC.FileObj.FolderCreate(OrignFolder, NewFloder); - *****************************************/ - /// - /// 在当前目录下创建目录 - /// - /// 当前目录 - /// 新目录 - public static void FolderCreate(string orignFolder, string NewFloder) - { - Directory.SetCurrentDirectory(orignFolder); - Directory.CreateDirectory(NewFloder); - } - #endregion - - #region 递归删除文件夹目录及文件 - /**************************************** - * 函数名称:DeleteFolder - * 功能说明:递归删除文件夹目录及文件 - * 参 数:dir:文件夹路径 - * 调用示列: - * string dir = Server.MapPath("test/"); - * EC.FileObj.DeleteFolder(dir); - *****************************************/ - /// - /// 递归删除文件夹目录及文件 - /// - /// - /// - public static void DeleteFolder(string dir) - { - if (Directory.Exists(dir)) //如果存在这个文件夹删除之 - { - foreach (string d in Directory.GetFileSystemEntries(dir)) - { - if (File.Exists(d)) - File.Delete(d); //直接删除其中的文件 - else - DeleteFolder(d); //递归删除子文件夹 - } - Directory.Delete(dir); //删除已空文件夹 - } + #region 获取文件根目录 + /// + /// 获取文件根目录 + /// + /// + public static string GetPhysicsPath() => $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot"; - } - #endregion - - #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 - /**************************************** - * 函数名称:CopyDir - * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 - * 参 数:srcPath:原始路径,aimPath:目标文件夹 - * 调用示列: - * string srcPath = Server.MapPath("test/"); - * string aimPath = Server.MapPath("test1/"); - * EC.FileObj.CopyDir(srcPath,aimPath); - *****************************************/ - /// - /// 指定文件夹下面的所有内容copy到目标文件夹下面 - /// - /// 原始路径 - /// 目标文件夹 - public static void CopyDir(string srcPath, string aimPath) - { - try - { - // 检查目标目录是否以目录分割字符结束如果不是则添加之 - if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) - aimPath += Path.DirectorySeparatorChar; - // 判断目标目录是否存在如果不存在则新建之 - if (!Directory.Exists(aimPath)) - Directory.CreateDirectory(aimPath); - // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 - //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 - //string[] fileList = Directory.GetFiles(srcPath); - string[] fileList = Directory.GetFileSystemEntries(srcPath); - //遍历所有的文件和目录 - foreach (string file in fileList) - { - //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 - - if (Directory.Exists(file)) - CopyDir(file, aimPath + Path.GetFileName(file)); - //否则直接Copy文件 - else - File.Copy(file, aimPath + Path.GetFileName(file), true); - } + #endregion - } - catch (Exception ee) - { - throw new Exception(ee.ToString()); - } - } - #endregion + #region 创建文件夹 + /// + /// 创建文件夹 + /// + /// + public static void CreateDirectory(string path) + { + var physicsPath = GetPhysicsPath(); + if (!Directory.Exists(physicsPath + path)) + Directory.CreateDirectory(physicsPath + path); } + #endregion } diff --git a/Tiobon.Core.Common/Helper/UtilHelper.cs b/Tiobon.Core.Common/Helper/UtilHelper.cs index 9cde33e2..61d4b46e 100644 --- a/Tiobon.Core.Common/Helper/UtilHelper.cs +++ b/Tiobon.Core.Common/Helper/UtilHelper.cs @@ -1,334 +1,337 @@ using Newtonsoft.Json; +using SqlSugar; -namespace Tiobon.Core +namespace Tiobon.Core; + +/// +/// +/// +public static class UtilHelper { /// /// /// - public static class UtilHelper + /// + /// + public static int ObjToInt(this object thisValue) { - /// - /// - /// - /// - /// - public static int ObjToInt(this object thisValue) + int reval = 0; + if (thisValue == null) return 0; + if (thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) { - int reval = 0; - if (thisValue == null) return 0; - if (thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - return reval; } - /// - /// - /// - /// - /// - /// - public static int ObjToInt(this object thisValue, int errorValue) - { - int reval = 0; - if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - - return errorValue; - } + return reval; + } - public static long ObjToLong(this object thisValue) + /// + /// + /// + /// + /// + /// + public static int ObjToInt(this object thisValue, int errorValue) + { + int reval = 0; + if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) { - long reval = 0; - if (thisValue == null) return 0; - if (thisValue != DBNull.Value && long.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - return reval; } - /// - /// - /// - /// - /// - public static double ObjToMoney(this object thisValue) - { - double reval = 0; - if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } + return errorValue; + } - return 0; + public static long ObjToLong(this object thisValue) + { + long reval = 0; + if (thisValue == null) return 0; + if (thisValue != DBNull.Value && long.TryParse(thisValue.ToString(), out reval)) + { + return reval; } - /// - /// - /// - /// - /// - /// - public static double ObjToMoney(this object thisValue, double errorValue) - { - double reval = 0; - if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } + return reval; + } - return errorValue; + /// + /// + /// + /// + /// + public static double ObjToMoney(this object thisValue) + { + double reval = 0; + if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) + { + return reval; } - /// - /// - /// - /// - /// - public static string ObjToString(this object thisValue) + return 0; + } + + /// + /// + /// + /// + /// + /// + public static double ObjToMoney(this object thisValue, double errorValue) + { + double reval = 0; + if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval)) { - if (thisValue != null) return thisValue.ToString().Trim(); - return ""; + return reval; } - /// - /// - /// - /// - /// - public static bool IsNotEmptyOrNull(this object thisValue) + return errorValue; + } + + /// + /// + /// + /// + /// + public static string ObjToString(this object thisValue) + { + if (thisValue != null) return thisValue.ToString().Trim(); + return ""; + } + + /// + /// + /// + /// + /// + public static bool IsNotEmptyOrNull(this object thisValue) + { + return ObjToString(thisValue) != "" && ObjToString(thisValue) != "undefined" && + ObjToString(thisValue) != "null"; + } + + /// + /// + /// + /// + /// + /// + public static string ObjToString(this object thisValue, string errorValue) + { + if (thisValue != null) return thisValue.ToString().Trim(); + return errorValue; + } + + public static bool IsNullOrEmpty(this object thisValue) => thisValue == null || thisValue == DBNull.Value || + string.IsNullOrWhiteSpace(thisValue.ToString()); + + /// + /// + /// + /// + /// + public static Decimal ObjToDecimal(this object thisValue) + { + Decimal reval = 0; + if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) { - return ObjToString(thisValue) != "" && ObjToString(thisValue) != "undefined" && - ObjToString(thisValue) != "null"; + return reval; } - /// - /// - /// - /// - /// - /// - public static string ObjToString(this object thisValue, string errorValue) + return 0; + } + + /// + /// + /// + /// + /// + /// + public static Decimal ObjToDecimal(this object thisValue, decimal errorValue) + { + Decimal reval = 0; + if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) { - if (thisValue != null) return thisValue.ToString().Trim(); - return errorValue; + return reval; } - public static bool IsNullOrEmpty(this object thisValue) => thisValue == null || thisValue == DBNull.Value || - string.IsNullOrWhiteSpace(thisValue.ToString()); + return errorValue; + } - /// - /// - /// - /// - /// - public static Decimal ObjToDecimal(this object thisValue) + /// + /// + /// + /// + /// + public static DateTime ObjToDate(this object thisValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) { - Decimal reval = 0; - if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - - return 0; + reval = Convert.ToDateTime(thisValue); } - - /// - /// - /// - /// - /// - /// - public static Decimal ObjToDecimal(this object thisValue, decimal errorValue) + else { - Decimal reval = 0; - if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval)) + //时间戳转为时间 + var seconds = ObjToLong(thisValue); + if (seconds > 0) { - return reval; + var startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local); + reval = startTime.AddSeconds(Convert.ToDouble(thisValue)); } - - return errorValue; } - /// - /// - /// - /// - /// - public static DateTime ObjToDate(this object thisValue) - { - DateTime reval = DateTime.MinValue; - if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) - { - reval = Convert.ToDateTime(thisValue); - } - else - { - //时间戳转为时间 - var seconds = ObjToLong(thisValue); - if (seconds > 0) - { - var startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local); - reval = startTime.AddSeconds(Convert.ToDouble(thisValue)); - } - } + return reval; + } + /// + /// + /// + /// + /// + /// + public static DateTime ObjToDate(this object thisValue, DateTime errorValue) + { + DateTime reval = DateTime.MinValue; + if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) + { return reval; } - /// - /// - /// - /// - /// - /// - public static DateTime ObjToDate(this object thisValue, DateTime errorValue) - { - DateTime reval = DateTime.MinValue; - if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - - return errorValue; - } + return errorValue; + } - /// - /// - /// - /// - /// - public static bool ObjToBool(this object thisValue) + /// + /// + /// + /// + /// + public static bool ObjToBool(this object thisValue) + { + bool reval = false; + if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) { - bool reval = false; - if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) - { - return reval; - } - return reval; } + return reval; + } + - /// - /// 获取当前时间的时间戳 - /// - /// - /// - public static string DateToTimeStamp(this DateTime thisValue) + /// + /// 获取当前时间的时间戳 + /// + /// + /// + public static string DateToTimeStamp(this DateTime thisValue) + { + TimeSpan ts = thisValue - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalSeconds).ToString(); + } + + public static object ChangeType(this object value, Type type) + { + if (value == null && type.IsGenericType) return Activator.CreateInstance(type); + if (value == null) return null; + if (type == value.GetType()) return value; + if (type.IsEnum) { - TimeSpan ts = thisValue - new DateTime(1970, 1, 1, 0, 0, 0, 0); - return Convert.ToInt64(ts.TotalSeconds).ToString(); + if (value is string) + return Enum.Parse(type, value as string); + else + return Enum.ToObject(type, value); } - public static object ChangeType(this object value, Type type) + if (!type.IsInterface && type.IsGenericType) { - if (value == null && type.IsGenericType) return Activator.CreateInstance(type); - if (value == null) return null; - if (type == value.GetType()) return value; - if (type.IsEnum) - { - if (value is string) - return Enum.Parse(type, value as string); - else - return Enum.ToObject(type, value); - } + Type innerType = type.GetGenericArguments()[0]; + object innerValue = ChangeType(value, innerType); + return Activator.CreateInstance(type, new object[] { innerValue }); + } - if (!type.IsInterface && type.IsGenericType) - { - Type innerType = type.GetGenericArguments()[0]; - object innerValue = ChangeType(value, innerType); - return Activator.CreateInstance(type, new object[] { innerValue }); - } + if (value is string && type == typeof(Guid)) return new Guid(value as string); + if (value is string && type == typeof(Version)) return new Version(value as string); + if (!(value is IConvertible)) return value; + return Convert.ChangeType(value, type); + } - if (value is string && type == typeof(Guid)) return new Guid(value as string); - if (value is string && type == typeof(Version)) return new Version(value as string); - if (!(value is IConvertible)) return value; - return Convert.ChangeType(value, type); - } + public static object ChangeTypeList(this object value, Type type) + { + if (value == null) return default; - public static object ChangeTypeList(this object value, Type type) - { - if (value == null) return default; + var gt = typeof(List<>).MakeGenericType(type); + dynamic lis = Activator.CreateInstance(gt); - var gt = typeof(List<>).MakeGenericType(type); - dynamic lis = Activator.CreateInstance(gt); + var addMethod = gt.GetMethod("Add"); + string values = value.ToString(); + if (values != null && values.StartsWith("(") && values.EndsWith(")")) + { + string[] splits; + if (values.Contains("\",\"")) + { + splits = values.Remove(values.Length - 2, 2) + .Remove(0, 2) + .Split("\",\""); + } + else + { + splits = values.Remove(0, 1) + .Remove(values.Length - 2, 1) + .Split(","); + } - var addMethod = gt.GetMethod("Add"); - string values = value.ToString(); - if (values != null && values.StartsWith("(") && values.EndsWith(")")) + foreach (var split in splits) { - string[] splits; - if (values.Contains("\",\"")) + var str = split; + if (split.StartsWith("\"") && split.EndsWith("\"")) { - splits = values.Remove(values.Length - 2, 2) - .Remove(0, 2) - .Split("\",\""); - } - else - { - splits = values.Remove(0, 1) - .Remove(values.Length - 2, 1) - .Split(","); + str = split.Remove(0, 1) + .Remove(split.Length - 2, 1); } - foreach (var split in splits) - { - var str = split; - if (split.StartsWith("\"") && split.EndsWith("\"")) - { - str = split.Remove(0, 1) - .Remove(split.Length - 2, 1); - } - - addMethod.Invoke(lis, new object[] { ChangeType(str, type) }); - } + addMethod.Invoke(lis, new object[] { ChangeType(str, type) }); } - - return lis; } - public static string ToJson(this object value) - { - return JsonConvert.SerializeObject(value); - } + return lis; + } - public static bool AnyNoException(this ICollection source) - { - if (source == null) return false; + public static string ToJson(this object value) + { + return JsonConvert.SerializeObject(value); + } - return source.Any() && source.All(s => s != null); - } + public static bool AnyNoException(this ICollection source) + { + if (source == null) return false; - public static bool IsNull(this long? thisValue) - { - return thisValue is null; - } - public static bool IsNull(this int? thisValue) - { - return thisValue is null; - } - public static bool IsNull(this decimal? thisValue) - { - return thisValue is null; - } - public static bool IsNull(this string thisValue) - { - return string.IsNullOrWhiteSpace(thisValue); - } - public static bool IsNull(this DateTime? thisValue) - { - return thisValue is null; - } - public static bool IsNull(this T entity) where T : class - { - return entity == null; - } + return source.Any() && source.All(s => s != null); + } + + public static bool IsNull(this long? thisValue) + { + return thisValue is null; + } + public static bool IsNull(this int? thisValue) + { + return thisValue is null; } + public static bool IsNull(this decimal? thisValue) + { + return thisValue is null; + } + public static bool IsNull(this string thisValue) + { + return string.IsNullOrWhiteSpace(thisValue); + } + public static bool IsNull(this DateTime? thisValue) + { + return thisValue is null; + } + public static bool IsNull(this T entity) where T : class + { + return entity == null; + } + + public static long GetSysId() => SnowFlakeSingle.instance.getID(); + } \ No newline at end of file diff --git a/Tiobon.Core.DataAccess/ReportHelper.cs b/Tiobon.Core.DataAccess/ReportHelper.cs index 79c3080d..b1e0ed4d 100644 --- a/Tiobon.Core.DataAccess/ReportHelper.cs +++ b/Tiobon.Core.DataAccess/ReportHelper.cs @@ -1,6 +1,8 @@  +using Microsoft.AspNetCore.Http; using NPOI.HSSF.UserModel; using NPOI.OpenXmlFormats.Spreadsheet; +using NPOI.POIFS.NIO; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; @@ -107,6 +109,7 @@ public static class ReportHelper } #endregion + #region 生成导入模板 public static string ImportTemplate(ISqlSugarClient Db, List tableColumn, DataTable dt, string menuName) { @@ -389,7 +392,6 @@ public static class ReportHelper return default(string); } - public static async Task ImportTemplate1(ISqlSugarClient Db, List tableColumn, DataTable dt, string menuName) { @@ -649,6 +651,297 @@ public static class ReportHelper } return default(string); } + #endregion + + #region Excel导入 + + #region 获取Excel导入文件地址 + /// + /// 获取Excel导入文件地址 + /// + /// Excel文件流 + /// 菜单名称 + /// 文件地址 + public static async Task<(string, string)> GetImportFilePath(IFormFile file, string menuName) + { + var id = DateTimeHelper.ConvertToSecondString1(DateTime.Now); + var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{menuName}{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}"; + FileHelper.CreateDirectory(path); + + var filepath = path + file.FileName; + using (var stream = File.Create(FileHelper.GetPhysicsPath() + filepath)) + { + await file.CopyToAsync(stream); + } + return (path, filepath); + } + #endregion + + #region 读取 excel,默认第一行为标头 + /// + /// 读取 excel,默认第一行为标头 + /// + /// excel 文档路径 + /// + public static DataTable ReadImportExcel(string strFileName, string sheetName = "导入数据") + { + DataTable dt = new(); + //HSSFWorkbook hssfworkbook; + IWorkbook hssfworkbook; + ISheet sheet; + using (FileStream file = new FileStream(FileHelper.GetPhysicsPath() + strFileName, FileMode.Open, FileAccess.Read)) + { + //hssfworkbook = new HSSFWorkbook(file); + //hssfworkbook = new XSSFWorkbook(file); + hssfworkbook = NPOI.SS.UserModel.WorkbookFactory.Create(file); + } + if (hssfworkbook == null) throw new Exception("未能加载excel"); + int sheetCount = hssfworkbook.NumberOfSheets; + if (sheetCount == 0) throw new Exception("未能加载excel"); + if (string.IsNullOrEmpty(sheetName)) + sheet = hssfworkbook.GetSheetAt(0); + else + { + int sheetIndex = hssfworkbook.GetSheetIndex(sheetName); + if (sheetIndex >= 0) + sheet = hssfworkbook.GetSheetAt(sheetIndex); + else + throw new Exception($"未能找到{sheetName}这个sheet页"); + } + var rows = sheet.GetRowEnumerator(); + var headerRow = sheet.GetRow(0); + int cellCount = headerRow.LastCellNum; + for (int j = 0; j < cellCount; j++) + { + var cell = headerRow.GetCell(j); + if (!string.IsNullOrWhiteSpace(cell.ToString())) + dt.Columns.Add(cell.ToString()); + } + for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) + { + var row = sheet.GetRow(i); + + if (row is null) + continue; + var dataRow = dt.NewRow(); + for (int j = row.FirstCellNum; j < cellCount; j++) + { + if (j < 0) + continue; + if (row.GetCell(j) != null) + { + DateTime dateV = DateTime.MinValue; + try + { + dataRow[j] = GetCellValue(row.GetCell(j)); + //if (row.GetCell(j).IsDate()) + //{ + // dateV = row.GetCell(j).DateCellValue; + // dataRow[j] = DateTimeHelper.ConvertToSecondString(dateV); + //} + //else + //{ + // dataRow[j] = row.GetCell(j).ToString(); + //} + } + catch { } + //if (dateV == DateTime.MinValue) + //{ + // dataRow[j] = row.GetCell(j).ToString(); + //} + //else + //{ + // dataRow[j] = DateTimeHelper.ConvertToSecondString(dateV); + //} + + } + } + dt.Rows.Add(dataRow); + } + if (dt.Columns["Comments"] == null) + dt.Columns.Add("Comments", typeof(string)); + return dt; + } + #endregion + + #region 获取单元格类型 + /// + /// 获取单元格类型 + /// + /// + /// + private static string GetCellValue(ICell cell) + { + if (cell == null) + return null; + switch (cell.CellType) + { + case CellType.Blank: //BLANK: + return null; + case CellType.Boolean: //BOOLEAN: + return Convert.ToString(cell.BooleanCellValue); + case CellType.Numeric: //NUMERIC: + if (DateUtil.IsCellDateFormatted(cell)) + { + return DateTimeHelper.ConvertToSecondString(cell.DateCellValue); + } + else + { + return Convert.ToString(cell); + } + case CellType.String: //STRING: + return cell.StringCellValue; + case CellType.Error: //ERROR: + return Convert.ToString(cell.ErrorCellValue); + case CellType.Formula: //FORMULA: + default: + return "=" + cell.CellFormula; + } + } + #endregion + + #region 获取excel导入初始化Dcit + /// + /// 获取excel导入初始化Dcit + /// + /// + public static Dictionary GetDefaultDict() + { + var dict = new Dictionary + { + { "Id", UtilHelper.GetSysId() }, + { "CreateBy", App.User.ID }, + { "CreateTime", DateTime.Now } + }; + + return dict; + } + + #endregion + + #region 数据验证 + /// + /// 数据验证 + /// + /// + /// + /// + public static async Task<(List>, int)> ValidImportExcel(ISqlSugarClient Db, List columns, DataTable dt) + { + bool result = false; + int ErrorCount = 0; + var dictList = new List>(); + for (int i = 0; i < dt.Rows.Count; i++) + { + var dict = GetDefaultDict(); + var comments = new List(); + for (int j = 0; j < columns.Count; j++) + { + var x = columns[j]; + if (!dt.Columns.Contains(x.label)) + comments.Add("未查询到【" + x.label + "】列!"); + else + { + var value = dt.Rows[i][x.label].ToString(); + if (x.required == "true" && value.IsNullOrEmpty()) + { + comments.Add(x.label + "不能为空!"); + dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); + } + + if (x.dataSourceType.IsNullOrEmpty() && value.IsNotEmptyOrNull()) + { + if (x.dataType == "int" || x.dataType == "decimal") + { + try + { + Convert.ToDecimal(value); + } + catch (Exception) + { + comments.Add(x.label + "无效的数字类型!"); + } + } + else if (x.dataType == "date") + { + try + { + Convert.ToDateTime(value); + } + catch (Exception) + { + comments.Add(x.label + "无效的日期类型!"); + } + } + } + + if (value.IsNotEmptyOrNull()) + { + if (x.elementType == "Switch") + value = value == "是" ? "true" : "false"; + if (x.dataSourceId.IsNotEmptyOrNull() && x.dataSourceType.IsNotEmptyOrNull() && !x.dataSource.StartsWith("OrgTreeWith") + && !x.dataSource.StartsWith("StaffWith")) + { + + if (x.dataSourceType == "CommonList") + { + var commonSql = await Db.Queryable().Where(o => o.ListCommonSqlId == x.dataSourceId).FirstAsync(); + + if (commonSql != null) + { + string sql = @$"SELECT [value] + FROM ({commonSql.SelectSql}) A + WHERE label = '{value}'"; + sql = sql.Replace("{@LangID}", "1"); + sql = sql.Replace("{@UserID}", App.User.ID.ObjToString()); + sql = sql.Replace("{@KeyWords}", null); + var id2 = await Db.Ado.GetLongAsync(sql); + + dict.Add(x.field, id2); + } + } + else if (x.dataSourceType == "ParaDetailNo") + { + var sql = @$"SELECT ParaDetailNo + FROM Ghrs_ParaDetail + WHERE ParaMasterId IN (SELECT ParaMasterId + FROM Ghrs_ParaMaster + WHERE ParaMasterId = {x.dataSourceId.ObjToInt()}) + AND IsEnable = 1 + AND ParaDetailName = '{value}'"; + var id2 = await Db.Ado.GetStringAsync(sql); + + dict.Add(x.field, id2); + } + } + else if (x.dataSource == "OrgTreeWithoutPriv") + { + string sql = @$"SELECT DeptID FROM Ghro_Dept WHERE DeptName = '{value}' OR DeptNo = '{value}' OR DeptEname = '{value}'"; + var id2 = await Db.Ado.GetLongAsync(sql); + dict.Add(x.field, id2); + } + else + dict.Add(x.field, value); + } + } + } + if (comments.Any()) + { + dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); + ErrorCount++; + result = true; + continue; + } + else + dictList.Add(dict); + } + + return (dictList, ErrorCount); + } + #endregion + + #endregion + /// /// Excel字段下拉 /// diff --git a/Tiobon.Core.Services/BASE/BaseServices.cs b/Tiobon.Core.Services/BASE/BaseServices.cs index 2f41b0e6..546f5d81 100644 --- a/Tiobon.Core.Services/BASE/BaseServices.cs +++ b/Tiobon.Core.Services/BASE/BaseServices.cs @@ -1,4 +1,6 @@ -namespace Tiobon.Core.Services.BASE; +using System.IO; + +namespace Tiobon.Core.Services.BASE; /// /// 增删改查基础服务 @@ -952,14 +954,30 @@ public class BaseServices : IBaseServ } public async virtual Task> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null) { - //long id = SnowFlakeSingle.instance.getID(); - //var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot"; - //var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}"; - //if (!Directory.Exists(physicsPath + path)) - // Directory.CreateDirectory(physicsPath + path); + var data = new ExcelData(); + var (path, filepath) = await ReportHelper.GetImportFilePath(file, menuName); + var id1 = SnowFlakeSingle.instance.getID(); + string errorFileName = path + SnowFlakeSingle.instance.getID() + FileHelper.GetPostfixStr(filepath); + + var dt = ReportHelper.ReadImportExcel(filepath); + var columns = await QueryExportColumn(menuName); + var (dictList, errorCount) = await ReportHelper.ValidImportExcel(Db, columns, dt); + + if (errorCount > 0) + { + NPOIHelper.ExportExcel(dt, null, "导入数据", FileHelper.GetPhysicsPath() + errorFileName); + data.filePath = "/Advanced" + errorFileName; + data.ErrorCount = errorCount; + } + else + { + Type entityType = typeof(TEntity); + await Db.Insertable(dictList).AS(entityType.GetEntityTableName()).ExecuteCommandAsync(); + data.SuccessCount = dictList.Count; + } - return ServiceResult.OprateSuccess("导入成功!"); + return ServiceResult.OprateSuccess("导入成功!", data); } public async Task> QueryExportColumn(string menuName) { @@ -972,6 +990,8 @@ public class BaseServices : IBaseServ dbo.FS_GetdataSourceBySet (dataSource, APIDataSourceType, Ghrs_PageSettingEdit.APIDataSourceID) dataSource, + APIDataSourceType + dataSourceType, required, dataType, CONVERT (NVARCHAR (1000), '') @@ -979,7 +999,7 @@ public class BaseServices : IBaseServ , elementType + CASE WHEN multipleSelect = 'true' THEN '_multiple' ELSE '' END - elementType -- 增加多选判断 + elementType, APIDataSourceID dataSourceId -- 增加多选判断 FROM Ghrs_PageSettingEdit WHERE IsEnable = 1 AND elementType NOT IN ('FnKey', 'PageGroup') diff --git a/Tiobon.Core.Services/Ghrh/Ghrh_HumanRequestServices.cs b/Tiobon.Core.Services/Ghrh/Ghrh_HumanRequestServices.cs index 81f10a86..01c1d8c3 100644 --- a/Tiobon.Core.Services/Ghrh/Ghrh_HumanRequestServices.cs +++ b/Tiobon.Core.Services/Ghrh/Ghrh_HumanRequestServices.cs @@ -1,5 +1,4 @@ -using NPOI.SS.UserModel; -using static Tiobon.Core.Model.Consts; +using static Tiobon.Core.Model.Consts; namespace Tiobon.Core.Services; @@ -532,218 +531,68 @@ WHERE A.IsEnable = 1 AND A.Id = {entitys[i].YearHumanId}"); #endregion - //#region Excel导入 - //public override async Task> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null) - //{ - // var data = new ExcelData(); - // long id = SnowFlakeSingle.instance.getID(); - // var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot"; - // var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}"; - // if (!Directory.Exists(physicsPath + path)) - // Directory.CreateDirectory(physicsPath + path); - - // var filepath = physicsPath + path + file.FileName; - // using (var stream = File.Create(filepath)) - // { - // await file.CopyToAsync(stream); - // } - // string extension = Path.GetExtension(filepath); - - // bool isExistError = false; - // var id1 = SnowFlakeSingle.instance.getID(); - // string errorFileName = path + SnowFlakeSingle.instance.getID() + extension; - // try - // { - // DataTable dt = NPOIHelper.ImportExcel(filepath, "年度人力配置"); - // if (dt.Columns["Comments"] == null) - // dt.Columns.Add("Comments", typeof(string)); - - // for (int i = 0; i < dt.Rows.Count; i++) - // { - // var comments = new List(); - - // if (!dt.Columns.Contains("年度")) - // { - // comments.Add("未查询到【年度】列!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - // if (!dt.Columns.Contains("部门")) - // { - // comments.Add("未查询到【部门】列!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - - // if (!dt.Columns.Contains("岗位")) - // { - // comments.Add("未查询到【岗位】列!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - - - // if (!dt.Columns.Contains("职称")) - // { - // comments.Add("未查询到【职称】列!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - // if (!dt.Columns.Contains("职等")) - // { - // comments.Add("未查询到【职等】列!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - - // for (int j = 1; j <= 12; j++) - // { - // if (!dt.Columns.Contains(j + "月")) - // { - // comments.Add($"未查询到【{j}月】列!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - // } - - // var year = dt.Rows[i]["年度"].ToString(); - // var deptName = dt.Rows[i]["部门"].ToString(); - // var titleName = dt.Rows[i]["岗位"].ToString(); - // var jobName = dt.Rows[i]["职称"].ToString(); - // var gradeName = dt.Rows[i]["职等"].ToString(); - - // var dept = await Db.Queryable().Where(x => x.DeptName == deptName).FirstAsync(); - // if (dept == null) - // { - // comments.Add($"无效的部门名称!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - // var title = await Db.Queryable().Where(x => x.TitleName == titleName).FirstAsync(); - // if (title == null) - // { - // comments.Add($"无效的岗位名称!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - - // var job = await Db.Queryable().Where(x => x.JobName == jobName).FirstAsync(); - // if (job == null) - // { - // comments.Add($"无效的职称名称!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - - // var grade = await Db.Queryable().Where(x => x.GradeName == gradeName).FirstAsync(); - // if (grade == null) - // { - // comments.Add($"无效的职等名称!"); - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - - // if (1 == 1) - // { - // var dict = new Dictionary - // { - // { "Id", SnowFlakeSingle.Instance.NextId() }, - // { "CreateBy", App.User.ID }, - // { "CreateTime", DateTime.Now }, - // { "WorkState", 1 }, - // { "Year", year }, - // { "DeptId", dept.DeptID }, - // { "TitleId", title.TitleID }, - // { "GradeId", grade.GradeID }, - // { "JobId", job.JobID } - // }; - // for (int j = 1; j <= 12; j++) - // dict.Add("M" + j, dt.Rows[i][j + "月"].ToString()); - // await Db.Insertable(dict).AS("Ghrh_YearHumanSettings").ExecuteCommandAsync(); - // if (comments.Any()) - // { - // data.ErrorCount++; - // dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a)); - // isExistError = true; - // continue; - // } - // else - // { - // data.SuccessCount++; - // } - // } - // else - // { - // dt.Rows[i]["Comments"] = "试题在系统中已存在!"; - // data.ErrorCount++; - // isExistError = true; - // continue; - // } - - // } - - // if (isExistError) - // { - // NPOIHelper.ExportExcel(dt, null, "年度人力配置", physicsPath + errorFileName); - // data.filePath = "/Advanced" + errorFileName; - // } - // } - // catch (Exception) - // { - // } - // return ServiceResult.OprateSuccess("导入成功!", data); - //} - - //public override async Task> DownloadExcel(string menuName) - //{ - // var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot"; - // var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}ExcelTemplate{Path.DirectorySeparatorChar}"}"; - // if (!Directory.Exists(physicsPath + path)) - // Directory.CreateDirectory(physicsPath + path); - - // Type entityType = typeof(Ghrh_YearHumanSettings); - // var fileName = entityType.GetEntityTableName() + ".xlsx"; - // //physicsPath = physicsPath + path + fileName; - - // IWorkbook hssfworkbook; - // ISheet sheet; - // using (FileStream file = new FileStream(physicsPath + path + fileName, FileMode.Open, FileAccess.Read)) - // { - // //hssfworkbook = new HSSFWorkbook(file); - // //hssfworkbook = new XSSFWorkbook(file); - // hssfworkbook = WorkbookFactory.Create(file); - // } - // //ISheet sheet2 = hssfworkbook.CreateSheet("下拉数据"); - - // var newFileName = Guid.NewGuid() + ".xlsx"; - // int listColIndex = 0; - - - // var physicsPath1 = physicsPath + path + fileName; - // //if (dataSourceLists.Any()) - // // physicsPath1 = physicsPath + path + newFileName; - // var result = ServiceResult.OprateSuccess("人力需求维护_" + DateTimeHelper.ConvertToSecondString1(DateTime.Now) + ".xlsx", physicsPath1); - // return result; - //} - //#endregion + #region Excel导入 + public override async Task> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null) + { + var data = new ExcelData(); + var (path, filepath) = await ReportHelper.GetImportFilePath(file, menuName); + string errorFileName = path + SnowFlakeSingle.instance.getID() + FileHelper.GetPostfixStr(filepath); + + var dt = ReportHelper.ReadImportExcel(filepath); + var columns = await QueryExportColumn(menuName); + + var (dictList, errorCount) = await ReportHelper.ValidImportExcel(Db, columns, dt); + + if (errorCount > 0) + { + NPOIHelper.ExportExcel(dt, null, "导入数据", FileHelper.GetPhysicsPath() + errorFileName); + data.filePath = "/Advanced" + errorFileName; + data.ErrorCount = errorCount; + } + else + { + for (int i = 0; i < dictList.Count; i++) + { + var dict = dictList[i]; + if (menuName == "F_ManReqMainten") + dict.Add("Status", "Wait"); + else + if (menuName == "F_ManReqMaintenTemporary") + dict.Add("Status", "Temporary"); + + if (dict.ContainsKey("Quality")) + { + await _ghrh_HumanRequestDetailServices.Add(new InsertGhrh_HumanRequestDetailInput() + { + RequestId = dict["Id"].ObjToLong(), + DetailName = dict["Quality"].ObjToString(), + Source = "Quality" + }); + dict.Remove("Quality"); + } + if (dict.ContainsKey("Experience")) + { + await _ghrh_HumanRequestDetailServices.Add(new InsertGhrh_HumanRequestDetailInput() + { + RequestId = dict["Id"].ObjToLong(), + DetailName = dict["Experience"].ObjToString(), + Source = "Experience" + }); + dict.Remove("Experience"); + } + await Db.Insertable(dict).AS("Ghrh_HumanRequest").ExecuteCommandAsync(); + + var sql = $"SELECT ISNULL(MAX(id)+1,1) FROM Ghrh_HumanRequest WHERE Id !='{dict["Id"]}'"; + var id1 = await Db.Ado.GetLongAsync(sql); + sql = $"UPDATE Ghrh_HumanRequest SET Id={id1} WHERE Id ='{dict["Id"]}';" + + $"UPDATE Ghrh_HumanRequestDetail SET RequestId={id1} WHERE RequestId ='{dict["Id"]}';"; + await Db.Ado.ExecuteCommandAsync(sql); + } + + data.SuccessCount = dictList.Count; + } + + return ServiceResult.OprateSuccess("导入成功!", data); + } + #endregion } \ No newline at end of file diff --git a/Tiobon.Core/Tiobon.Core.xml b/Tiobon.Core/Tiobon.Core.xml index de62cc2c..4f53e2fc 100644 --- a/Tiobon.Core/Tiobon.Core.xml +++ b/Tiobon.Core/Tiobon.Core.xml @@ -281,13 +281,6 @@ - - - 下载导入模板Excel - - - - Excel导入