using BLL; using Model; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Linq; namespace FineUIPro.Web.ReportManage.HazardFactor { public partial class HazardFactorSafetyIn : PageBase { #region 定义变量 /// /// 上传预设的虚拟路径 /// private string initPath = Const.ExcelUrl; /// /// 错误集合 /// public static List errorInfos = new List(); /// /// 项目id /// public string ProjectId { get { return (string)ViewState["ProjectId"]; } set { ViewState["ProjectId"] = value; } } /// /// 操作人 /// public string CompileMan { get { return (string)ViewState["CompileMan"]; } set { ViewState["CompileMan"] = value; } } public string CompileManName { get { return (string)ViewState["CompileManName"]; } set { ViewState["CompileManName"] = value; } } public static int Cols = 19;//列数 public static List validLevelStrings = new List { "低风险", "一般风险", "较大风险", "重大风险" }; #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.ProjectId = Request.Params["ProjectId"]; this.CompileMan = this.CurrUser.UserId; this.CompileManName = this.CurrUser.UserName; this.hdFileName.Text = string.Empty; if (errorInfos != null) { errorInfos.Clear(); } //if (this.CurrUser.UserId == Const.AdminId) //{ // this.btnFastImport.Hidden = false; //} } } #region 下载模板 /// /// 下载模板按钮 /// /// /// protected void btnDownLoad_Click(object sender, EventArgs e) { //这里要注意了,如果传过来的没有记录 PageContext.RegisterStartupScript(Confirm.GetShowReference("确定下载导入模板吗?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel"))); } /// /// 下载导入模板 /// /// /// protected void PageManager1_CustomEvent(object sender, CustomEventArgs e) { if (e.EventArgument == "Confirm_OK") { string rootPath = Server.MapPath("~/"); string uploadfilepath = rootPath + Const.HazardFactorSafetyDataInTemplateUrl; string filePath = Const.HazardFactorSafetyDataInTemplateUrl; string fileName = Path.GetFileName(filePath); FileInfo info = new FileInfo(uploadfilepath); long fileSize = info.Length; Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.ContentType = "excel/plain"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AddHeader("Content-Length", fileSize.ToString().Trim()); Response.TransmitFile(uploadfilepath, 0, fileSize); Response.End(); } } #endregion #region 审核 /// /// 审核 /// /// /// protected void btnAudit_Click(object sender, EventArgs e) { try { if (this.fuAttachUrl.HasFile == false) { ShowNotify("请您选择Excel文件!", MessageBoxIcon.Warning); return; } string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower(); if (IsXls != ".xls" && IsXls != ".xlsx") { ShowNotify("只可以选择Excel文件!", MessageBoxIcon.Warning); return; } if (errorInfos != null) { errorInfos.Clear(); } string rootPath = Server.MapPath("~/"); string initFullPath = rootPath + initPath; if (!Directory.Exists(initFullPath)) { Directory.CreateDirectory(initFullPath); } this.hdFileName.Text = BLL.Funs.GetNewFileName() + IsXls; string filePath = initFullPath + this.hdFileName.Text; this.fuAttachUrl.PostedFile.SaveAs(filePath); AuditExcelAndShowResult(filePath); } catch (Exception ex) { ShowNotify("'" + ex.Message + "'", MessageBoxIcon.Warning); } } /// /// 审核Excel并展示校验结果 /// private void AuditExcelAndShowResult(string fileName) { try { string msg = string.Empty; var dt = BLL.Common.NPOIHelper.ExcelToDataSet(fileName, out msg, true); if (dt != null) { //string rootPath = Server.MapPath("~/"); //var localPath = ConfigurationManager.AppSettings["localRoot"]; //imgDic = NPOIHelper.ExtractDispimgImagesFromXml(rootPath + initPath + this.hdFileName.Text, localPath + "FileUpload/CheckSpecial"); ValidateExcelData(dt.Tables[0], false); hdCheckResult.Text = "1"; } } catch (Exception exc) { BLL.ErrLogInfo.WriteLog("", exc); Response.Write(exc); } } /// /// 校验Excel数据(仅校验) /// /// /// true:导入;false:审核 /// private bool ValidateExcelData(DataTable pds, bool import) { int ic = pds.Columns.Count; if (ic < Cols) { ShowNotify($"导入Excel格式错误!Excel只有{ic}列", MessageBoxIcon.Warning); return false; } int ir = pds.Rows.Count; if (pds == null || ir <= 0) { ShowNotify("导入数据为空!", MessageBoxIcon.Warning); return false; } var errors = new List(); for (int i = 1; i < ir; i++) { var (error, _) = ValidateRowAndBuildEntity(pds.Rows[i], (i + 2).ToString(), import); if (error.Any()) { errors.AddRange(error); } } errorInfos.Clear(); errorInfos.AddRange(errors); this.gvErrorInfo.DataSource = errorInfos; this.gvErrorInfo.DataBind(); if (errors.Count > 0) { ShowNotify("存在校验错误,请查看错误列表并修正后再次导入。", MessageBoxIcon.Warning); return false; } ShowNotify("审核完成,请点击导入!", MessageBoxIcon.Success); return true; } /// /// 校验单行并生成实体(字段顺序与新模板一致) /// private (List lstError, Model.HazardFactor_Safety entity) ValidateRowAndBuildEntity(DataRow row, string displayRow, bool import) { List lstError = new List(); // 新模板字段顺序 string rData0 = row[0]?.ToString().Trim(); // 上报年月 string rData1 = row[1]?.ToString().Trim(); // 活动区域\场所\设备 string rData2 = row[2]?.ToString().Trim(); // 作业内容/步骤 string rData3 = row[3]?.ToString().Trim(); // 危害因素描述 string rData4 = row[4]?.ToString().Trim(); // 主要后果 string rData5 = row[5]?.ToString().Trim(); // 违法 string rData6 = row[6]?.ToString().Trim(); // 固有风险-严重性 string rData7 = row[7]?.ToString().Trim(); // 固有风险-可能性 string rData8 = row[8]?.ToString().Trim(); // 固有风险-得分 string rData9 = row[9]?.ToString().Trim(); // 固有风险-风险级别 string rData10 = row[10]?.ToString().Trim(); // 固有风险-可接受 string rData11 = row[11]?.ToString().Trim(); // 残留风险-现有控制措施 string rData12 = row[12]?.ToString().Trim(); // 残留风险-严重性 string rData13 = row[13]?.ToString().Trim(); // 残留风险-可能性 string rData14 = row[14]?.ToString().Trim(); // 残留风险-得分 string rData15 = row[15]?.ToString().Trim(); // 残留风险-风险级别 string rData16 = row[16]?.ToString().Trim(); // 残留风险-可接受 string rData17 = row[17]?.ToString().Trim(); // 新增或变更的控制措施 string rData18 = row[18]?.ToString().Trim(); // 责任部门 string Year = string.Empty; string Month = string.Empty; string WorkPlace = string.Empty; string JobStep = string.Empty; string Hazard = string.Empty; string Consequence = string.Empty; bool Illegality = false; int BaseRiskSeverity = 0; int BaseRiskProbability = 0; int BaseRiskScore = 0; string BaseRiskLevel = "低风险"; bool BaseRiskAcceptabity = false; string NetRiskControlMeasures = string.Empty; int NetRiskSeverity = 0; int NetRiskProbability = 0; int NetRiskScore = 0; string NetRiskLevel = "低风险"; bool NetRiskAcceptabity = false; string AdditionalControlMeasures = string.Empty; string ResponsibleDepartment = string.Empty; // 校验并转换 if (!string.IsNullOrEmpty(rData0)) { if (!DateTime.TryParse(rData0, out DateTime ct)) { lstError.Add(new ErrorInfo { Row = displayRow, Column = "上报年月", Reason = "上报年月格式错误[正确格式:yyyy-MM,2026-04]" }); } else { Year = ct.Year.ToString(); Month = ct.Month.ToString(); } } else { lstError.Add(new ErrorInfo { Row = displayRow, Column = "上报年月", Reason = "不能为空" }); } if (!string.IsNullOrEmpty(rData1)) { WorkPlace = rData1; } else { lstError.Add(new ErrorInfo { Row = displayRow, Column = "活动区域", Reason = "不能为空" }); } if (!string.IsNullOrEmpty(rData2)) { JobStep = rData2; } else { lstError.Add(new ErrorInfo { Row = displayRow, Column = "作业内容", Reason = "不能为空" }); } if (!string.IsNullOrEmpty(rData3)) { Hazard = rData3; } else { lstError.Add(new ErrorInfo { Row = displayRow, Column = "危害因素描述", Reason = "不能为空" }); } if (!string.IsNullOrEmpty(rData4)) { Consequence = rData4; } else { lstError.Add(new ErrorInfo { Row = displayRow, Column = "主要后果", Reason = "不能为空" }); } Illegality = !string.IsNullOrEmpty(rData5) && rData5 == "是"; if (!string.IsNullOrEmpty(rData6)) { if (!int.TryParse(rData6, out int ct)) { lstError.Add(new ErrorInfo { Row = displayRow, Column = "固有风险严重性", Reason = "格式错误" }); } else { BaseRiskSeverity = ct; } } if (!string.IsNullOrEmpty(rData7)) { if (!int.TryParse(rData7, out int ct)) { lstError.Add(new ErrorInfo { Row = displayRow, Column = "固有风险可能性", Reason = "格式错误" }); } else { BaseRiskProbability = ct; } } BaseRiskScore = BaseRiskSeverity * BaseRiskProbability; var baseRiskLevel = RiskLevelService.GetRiskLevelByValue(BaseRiskScore); if (baseRiskLevel != null) { BaseRiskLevel = baseRiskLevel.RiskLevelName; } BaseRiskAcceptabity = !string.IsNullOrEmpty(rData10) && rData10 == "否" ? false : true; if (!string.IsNullOrEmpty(rData11)) { NetRiskControlMeasures = rData11; } else { lstError.Add(new ErrorInfo { Row = displayRow, Column = "现有控制措施", Reason = "不能为空" }); } if (!string.IsNullOrEmpty(rData12)) { if (!int.TryParse(rData12, out int ct)) { lstError.Add(new ErrorInfo { Row = displayRow, Column = "残留风险严重性", Reason = "格式错误" }); } else { NetRiskSeverity = ct; } } if (!string.IsNullOrEmpty(rData13)) { if (!int.TryParse(rData13, out int ct)) { lstError.Add(new ErrorInfo { Row = displayRow, Column = "残留风险可能性", Reason = "格式错误" }); } else { NetRiskProbability = ct; } } NetRiskScore = NetRiskSeverity * NetRiskProbability; var netRiskLevel = RiskLevelService.GetRiskLevelByValue(NetRiskScore); if (netRiskLevel != null) { NetRiskLevel = netRiskLevel.RiskLevelName; } NetRiskAcceptabity = !string.IsNullOrEmpty(rData16) && rData16 == "否" ? false : true; if (!string.IsNullOrEmpty(rData17)) { AdditionalControlMeasures = rData17; } if (!string.IsNullOrEmpty(rData18)) { ResponsibleDepartment = rData18; } if (lstError.Any()) { return (lstError, null); } // 其余字段可根据实际业务映射到实体 var entity = new Model.HazardFactor_Safety { ID = SQLHelper.GetNewID(typeof(Model.HazardFactor_Safety)), CompileDate=DateTime.Now, CompileMan = this.CompileMan, CompileManName = this.CompileManName, State = int.Parse(BLL.Const.State_1),//默认已提交 ProjectId =this.ProjectId, Year = Year, Month = Month, WorkPlace = WorkPlace, JobStep = JobStep, Hazard = Hazard, Consequence = Consequence, Illegality = Illegality, BaseRiskSeverity = BaseRiskSeverity, BaseRiskProbability = BaseRiskProbability, BaseRiskScore = BaseRiskScore, BaseRiskLevel = BaseRiskLevel, BaseRiskAcceptabity = BaseRiskAcceptabity, NetRiskControlMeasures = NetRiskControlMeasures, NetRiskSeverity = NetRiskSeverity, NetRiskProbability = NetRiskProbability, NetRiskScore = NetRiskScore, NetRiskLevel = NetRiskLevel, NetRiskAcceptabity = NetRiskAcceptabity, AdditionalControlMeasures = AdditionalControlMeasures, ResponsibleDepartment = ResponsibleDepartment }; return (lstError, entity); } #endregion #region 导入 /// /// 导入 /// /// /// protected void btnImport_Click(object sender, EventArgs e) { if (hdCheckResult.Text == "1") { if (errorInfos.Count <= 0) { string rootPath = Server.MapPath("~/"); var localPath = ConfigurationManager.AppSettings["localRoot"]; //imgDic = NPOIHelper.ExtractDispimgImagesFromXml(rootPath + initPath + this.hdFileName.Text, localPath + "FileUpload/CheckSpecial"); ImportExcelToDatabase(rootPath + initPath + this.hdFileName.Text, true); hdCheckResult.Text = string.Empty; ShowNotify("导入成功!", MessageBoxIcon.Success); PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference()); } else { ShowNotify("请先将错误数据修正,再重新导入提交!", MessageBoxIcon.Warning); } } else { ShowNotify("请先审核要导入的文件!", MessageBoxIcon.Warning); } } /// /// 导入Excel到数据库 /// private void ImportExcelToDatabase(string fileName, bool import) { try { string msg = string.Empty; var dt = BLL.Common.NPOIHelper.ExcelToDataSet(fileName, out msg, true); BLL.ErrLogInfo.WriteLog(msg); SaveExcelDataToDatabase(fileName, dt.Tables[0], import); } catch (Exception ex) { ErrLogInfo.WriteLog("", ex); } } /// /// 校验并保存数据到数据库 /// private bool SaveExcelDataToDatabase(string fileName, DataTable pds, bool import) { int ic = pds.Columns.Count; if (ic < Cols) { ShowNotify($"导入Excel格式错误!Excel只有{ic}列", MessageBoxIcon.Warning); return false; } int ir = pds.Rows.Count; if (pds == null || ir <= 0) { ShowNotify("导入数据为空!", MessageBoxIcon.Warning); return false; } var errors = new List(); var toInsert = new List(); for (int i = 1; i < ir; i++) { var (error, entity) = ValidateRowAndBuildEntity(pds.Rows[i], (i + 2).ToString(), import); if (error.Any()) errors.AddRange(error); else toInsert.Add(entity); } if (errors.Count > 0) { errorInfos.Clear(); errorInfos.AddRange(errors); this.gvErrorInfo.DataSource = errorInfos; this.gvErrorInfo.DataBind(); ShowNotify("存在校验错误,请先审核并修正后再导入。", MessageBoxIcon.Warning); return false; } try { if (toInsert.Any()) { Funs.DB.HazardFactor_Safety.InsertAllOnSubmit(toInsert); Funs.DB.SubmitChanges(); } ShowNotify($"成功导入 {toInsert.Count} 条记录。", MessageBoxIcon.Success); PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference()); return true; } catch (Exception ex) { ErrLogInfo.WriteLog("导入 安全危害因素清单(HazardFactor_Safety) 失败", ex); ShowNotify("导入失败:" + ex.Message, MessageBoxIcon.Error); return false; } } #endregion // 导入 } }