diff --git a/Tiobon.Core.Services/Ghrh/Ghrh_YearHumanSettingsServices.cs b/Tiobon.Core.Services/Ghrh/Ghrh_YearHumanSettingsServices.cs index 4cfbe1d3..15377073 100644 --- a/Tiobon.Core.Services/Ghrh/Ghrh_YearHumanSettingsServices.cs +++ b/Tiobon.Core.Services/Ghrh/Ghrh_YearHumanSettingsServices.cs @@ -1,4 +1,9 @@ -namespace Tiobon.Core.Services; +using NPOI.HSSF.UserModel; +using NPOI.SS.UserModel; +using NPOI.SS.Util; +using NPOI.XSSF.UserModel; + +namespace Tiobon.Core.Services; /// /// 年度人力配置 (服务) @@ -213,4 +218,292 @@ public class Ghrh_YearHumanSettingsServices : BaseServices>.OprateSuccess("查询成功!", flowReturn.result.JM_TableColumnT1.TableColumn); ; } + + + + #region Excel导入 + public override async Task> ImportExcel(IFormFile file) + { + 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 = 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; + //string sql = @"select 'Course' field, Id id, CourseNo no, CourseName name from Ghre_Course where IsEnable=1 and Status='Released'"; + //var dataSourceLists = await Db.Ado.SqlQueryAsync(sql); + //if (dataSourceLists.Any()) + //{ + // var types = new List + // { + // "学习记录" + // }; + + // types.ForEach(sheetName => + // { + // int sheetIndex = hssfworkbook.GetSheetIndex(sheetName); + // if (sheetIndex >= 0) + // { + // sheet = hssfworkbook.GetSheetAt(sheetIndex); + + // SetCellDropdownList(sheet, 0, 0, dataSourceLists.Select(x => x.name).ToArray()); + // } + + // }); + // MemoryStream ms; + // using (ms = new MemoryStream()) + // { + // hssfworkbook.Write(ms); + // ms.Flush(); + // hssfworkbook.Dispose(); + // //ms.Position = 0; + // //return ms; + // } + // using (FileStream fs = new FileStream(physicsPath + path + newFileName, FileMode.Create, FileAccess.Write)) + // { + // byte[] data = ms.ToArray(); + // fs.Write(data, 0, data.Length); + // fs.Flush(); + // } + + //} + + var physicsPath1 = physicsPath + path + fileName; + //if (dataSourceLists.Any()) + // physicsPath1 = physicsPath + path + newFileName; + var result = ServiceResult.OprateSuccess("年度人力配置_" + DateTimeHelper.ConvertToSecondString1(DateTime.Now) + ".xlsx", physicsPath1); + return result; + } + + public static void SetCellDropdownList(ISheet sheet, int firstcol, int lastcol, string[] vals) + { + + //設置生成下拉框的行和列 + var cellRegions = new CellRangeAddressList(1, 65535, firstcol, lastcol); + IDataValidation validation = null; + + if (sheet.GetType().Name.Contains("XSSF")) // .xlsx + { + XSSFDataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet)sheet);//获得一个数据验证Helper + //IDataValidation + validation = helper.CreateValidation( + helper.CreateExplicitListConstraint(vals), cellRegions);//创建约束 + } + else // HSSF .xls + { + //設置 下拉框內容 + DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(vals); + validation = new HSSFDataValidation(cellRegions, constraint); + + + /*綁定下拉框和作用區域,並設置錯誤提示信息 + HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); + dataValidate.CreateErrorBox("輸入不合法", "請輸入或選擇下拉列表中的值。"); + dataValidate.ShowPromptBox = true; +*/ + } + + validation.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。"); + validation.ShowPromptBox = true; + + sheet.AddValidationData(validation); + } + + #endregion } \ No newline at end of file