using BLL; using Model; using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; using System.Linq; using System.Web.Util; namespace FineUIPro.Web.HSSE.EduTrain { public partial class CompanyTrainingItemIn : PageBase { #region 定义变量 /// /// 上传预设的虚拟路径 /// private string initPath = Const.ExcelUrl; /// /// 导入集合 /// public static List viewTrainingItems = new List(); /// /// 错误集合 /// public static List errorInfos = new List(); #endregion #region 加载页面 /// /// 加载页面 /// /// /// protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.hdFileName.Text = string.Empty; this.hdCheckResult.Text = string.Empty; if (viewTrainingItems != null) { viewTrainingItems.Clear(); } if (errorInfos != null) { errorInfos.Clear(); } } } #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") { ShowNotify("只可以选择Excel文件!", MessageBoxIcon.Warning); return; } if (viewTrainingItems != null) { viewTrainingItems.Clear(); } 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); ImportXlsToData(rootPath + initPath + this.hdFileName.Text); } catch (Exception ex) { ShowNotify("'" + ex.Message + "'", MessageBoxIcon.Warning); } } #region 读Excel提取数据 /// /// 从Excel提取数据--》Dataset /// /// Excel文件路径名 private void ImportXlsToData(string fileName) { try { viewTrainingItems.Clear(); string oleDBConnString = String.Empty; oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;"; oleDBConnString += "Data Source="; oleDBConnString += fileName; oleDBConnString += ";Extended Properties=Excel 8.0;"; OleDbConnection oleDBConn = null; OleDbDataAdapter oleAdMaster = null; DataTable m_tableName = new DataTable(); DataSet ds = new DataSet(); oleDBConn = new OleDbConnection(oleDBConnString); oleDBConn.Open(); m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (m_tableName != null && m_tableName.Rows.Count > 0) { m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString().Trim(); } string sqlMaster; sqlMaster = " SELECT * FROM [" + m_tableName.TableName + "]"; oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn); oleAdMaster.Fill(ds, "m_tableName"); oleAdMaster.Dispose(); oleDBConn.Close(); oleDBConn.Dispose(); AddDatasetToSQL(ds.Tables[0]); } catch (Exception ex) { throw ex; } } #endregion #region 将Dataset的数据导入数据库 /// /// 将Dataset的数据导入数据库 /// /// 数据集 /// 数据集行数 /// private bool AddDatasetToSQL(DataTable pds) { string result = string.Empty; int ic, ir; ic = pds.Columns.Count; ir = pds.Rows.Count; if (pds != null && ir > 0) { ///教材库 var companyTrainingItems = from x in Funs.DB.Training_CompanyTrainingItem select x; ///类型 var trainings = from x in Funs.DB.Training_CompanyTraining select x; ///岗位 var workPosts = from x in Funs.DB.Base_WorkPost select x; for (int i = 0; i < ir; i++) { Model.Training_CompanyTrainingItem newViewTrainingItem = new Model.Training_CompanyTrainingItem(); newViewTrainingItem.CompanyTrainingItemId = SQLHelper.GetNewID(typeof(Model.Training_CompanyTrainingItem)); //类型 string col1 = pds.Rows[i][0].ToString().Trim(); if (string.IsNullOrEmpty(col1)) { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "教材类型", Reason = "此项为必填项!" }); } else { var standard = trainings.FirstOrDefault(x => x.CompanyTrainingName == col1); if (standard != null) { newViewTrainingItem.CompanyTrainingId = standard.CompanyTrainingId; } else { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "教材类别", Reason = $"不存在教材类别[{col1}]!" }); } } if (!string.IsNullOrWhiteSpace(newViewTrainingItem.CompanyTrainingId)) { //教材编号 string col2 = pds.Rows[i][1].ToString().Trim(); //教材名称 string col3 = pds.Rows[i][2].ToString().Trim(); if (!string.IsNullOrWhiteSpace(col2)) { var items = companyTrainingItems.FirstOrDefault(x => x.CompanyTrainingItemCode == col2); if (items != null) { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "教材编号", Reason = $"[{col1}]已存在编号[{col2}]!" }); } else { newViewTrainingItem.CompanyTrainingItemCode = col2; } } else { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "教材编号", Reason = "不能为空!" }); } if (!string.IsNullOrWhiteSpace(col3)) { var item = companyTrainingItems.FirstOrDefault(x => x.CompanyTrainingItemName == col3); if (item != null) { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "教材名称", Reason = $"[{col1}]已存在教材名称[{col3}]!" }); } else { newViewTrainingItem.CompanyTrainingItemName = col3; } } else { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "教材名称", Reason = "不能为空!" }); } } //适合岗位 string col4 = pds.Rows[i][3].ToString().Trim(); if (!string.IsNullOrEmpty(col4)) { List WorkPostSels = Funs.GetStrListByStr(col4, ','); if (WorkPostSels.Count() > 0) { string ids = string.Empty; foreach (var item in WorkPostSels) { string workItem = item.Trim(); var wp = workPosts.FirstOrDefault(x => x.WorkPostName == workItem); if (wp != null) { ids += wp.WorkPostId + ","; } else { errorInfos.Add(new ErrorInfo { Row = (i + 2).ToString(), Column = "适合岗位", Reason = $"[{workItem}]不在岗位表中!" }); } } if (!string.IsNullOrEmpty(ids)) { newViewTrainingItem.WorkPostNames = col4; newViewTrainingItem.WorkPostIds = ids.Substring(0, ids.LastIndexOf(",")); } } } //时长(分钟) string col5 = pds.Rows[i][4].ToString().Trim(); if (!string.IsNullOrWhiteSpace(col5)) { newViewTrainingItem.LearningTime = int.Parse(col5) * 60; } //掌握程度 string col6 = pds.Rows[i][5].ToString().Trim(); if (!string.IsNullOrWhiteSpace(col6)) { newViewTrainingItem.Outcome = col6 == "了解" ? 2 : col6 == "熟悉" ? 1 : 0; } else { newViewTrainingItem.Outcome = 0; } newViewTrainingItem.CompileDate = DateTime.Now; newViewTrainingItem.CompileMan = this.CurrUser.UserName; ///加入公司教材库 viewTrainingItems.Add(newViewTrainingItem); } if (errorInfos.Any()) { viewTrainingItems.Clear(); this.gvErrorInfo.DataSource = errorInfos; this.gvErrorInfo.DataBind(); } else { errorInfos.Clear(); if (!viewTrainingItems.Any()) { Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Warning); } else { ShowNotify("审核完成,请点击导入!", MessageBoxIcon.Success); } } } else { Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Warning); } return true; } #endregion #endregion #region 保存 /// /// 保存 /// /// /// protected void btnSave_Click(object sender, EventArgs e) { if (!errorInfos.Any()) { int a = viewTrainingItems.Count(); int insertCount = 0; int updateCount = 0; for (int i = 0; i < a; i++) { Model.Training_CompanyTrainingItem newModel = new Model.Training_CompanyTrainingItem { CompanyTrainingId = viewTrainingItems[i].CompanyTrainingId, CompanyTrainingItemId = viewTrainingItems[i].CompanyTrainingItemId, CompanyTrainingItemCode = viewTrainingItems[i].CompanyTrainingItemCode, CompanyTrainingItemName = viewTrainingItems[i].CompanyTrainingItemName, WorkPostIds = viewTrainingItems[i].WorkPostIds, WorkPostNames = viewTrainingItems[i].WorkPostNames, LearningTime = viewTrainingItems[i].LearningTime, CompileDate = viewTrainingItems[i].CompileDate, CompileMan = viewTrainingItems[i].CompileMan, Outcome = viewTrainingItems[i].Outcome }; BLL.CompanyTrainingItemService.AddCompanyTrainingItem(newModel); } string rootPath = Server.MapPath("~/"); string initFullPath = rootPath + initPath; string filePath = initFullPath + this.hdFileName.Text; if (filePath != string.Empty && File.Exists(filePath)) { File.Delete(filePath);//删除上传的XLS文件 } ShowNotify("导入完成!", MessageBoxIcon.Success); PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference()); } else { Alert.ShowInTop("请先将错误数据修正,再重新导入保存!", MessageBoxIcon.Warning); } } #endregion #region 关闭弹出窗口 /// /// 关闭导入弹出窗口 /// /// /// protected void Window1_Close(object sender, WindowCloseEventArgs e) { if (Session["trainingItem"] != null) { viewTrainingItems = Session["trainingItem"] as List; } if (viewTrainingItems.Count > 0) { this.gvErrorInfo.Hidden = false; this.gvErrorInfo.DataSource = viewTrainingItems; this.gvErrorInfo.DataBind(); } } #endregion #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 filePath = Const.CompanyTrainingTemplateUrl; string uploadfilepath = rootPath + filePath; 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 } }