using BLL; using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; using System.Linq; using System.Web.UI; namespace FineUIPro.Web.ZHGL.Person { public partial class BranchPersonIn : PageBase { #region 定义变量 /// /// 上传预设的虚拟路径 /// private string initPath = Const.ExcelUrl; /// /// 错误集合 /// public static List errorInfos = new List(); #endregion #region 加载页面 /// /// 加载页面 /// /// /// protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (errorInfos != null) { errorInfos.Clear(); } } } #endregion #region 审核 /// /// 审核 /// /// /// protected void btnAudit_Click(object sender, EventArgs e) { try { if (this.FileExcel.HasFile == false) { Alert.ShowInTop("请您选择Excel文件!", MessageBoxIcon.Warning); return; } string IsXls = Path.GetExtension(FileExcel.FileName).ToString().Trim().ToLower(); if (IsXls != ".xls") { Alert.ShowInTop("只可以选择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; FileExcel.PostedFile.SaveAs(filePath); ImportXlsToData(filePath); } catch (Exception ex) { Alert.ShowInTop(ex.Message); } } #region 读Excel提取数据 /// /// 从Excel提取数据--》Dataset /// /// Excel文件路径名 private void ImportXlsToData(string fileName) { try { 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.SelectCommand.CommandTimeout = 1200; oleAdMaster.Fill(ds, "m_tableName"); oleAdMaster.Dispose(); oleDBConn.Close(); oleDBConn.Dispose(); AddDatasetToSQL(ds.Tables[0]); } catch (Exception ex) { throw ex; } } #endregion #endregion /// /// 将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 units = from x in Funs.DB.Base_Unit select x; var workPosts = from x in Funs.DB.Base_WorkPost select x; for (int i = 0; i < ir; i++) { string col0 = pds.Rows[i][0].ToString().Trim(); if (!string.IsNullOrEmpty(col0)) { var unit = units.FirstOrDefault(e => e.UnitName == col0); if (unit == null) { result += (i + 2).ToString() + "," + "单位" + "," + "[" + col0 + "]错误!" + "|"; } } else { result += (i + 2).ToString() + "," + "单位" + "," + "此项为必填项!" + "|"; } if (string.IsNullOrEmpty(pds.Rows[i][1].ToString())) { result += (i + 2).ToString() + "," + "姓名" + "," + "此项为必填项!" + "|"; } if (string.IsNullOrEmpty(pds.Rows[i][2].ToString())) { result += (i + 2).ToString() + "," + "性别" + "," + "此项为必填项!" + "|"; } else { if (pds.Rows[i][2].ToString() != "男" && pds.Rows[i][2].ToString() != "女") { result += (i + 2).ToString() + "," + "性别" + "," + "性别只能为男或女!" + "|"; } } string col3 = pds.Rows[i][3].ToString().Trim(); if (!string.IsNullOrEmpty(col3)) { if (col3.Length > 50) { result += (i + 2).ToString() + "," + "身份证号码" + "," + "[" + col3 + "]错误!" + "|"; } if (CompanyBranchPersonService.GetPersonCountByIdentityCard(col3) != null) { result += (i + 2).ToString() + "," + "身份证号码" + "," + "[" + col3 + "]已存在!" + "|"; } if (!IDCardValid.CheckIDCard(col3)) { result += (i + 2).ToString() + "," + "身份证号码" + "," + "[" + col3 + "]非法!" + "|"; } } else { result += (i + 2).ToString() + "," + "身份证号码" + "," + "此项为必填项!" + "|"; } string col4 = pds.Rows[i][4].ToString().Trim(); if (!string.IsNullOrEmpty(col4)) { var workPost = workPosts.FirstOrDefault(e => e.WorkPostName == col4); if (workPost == null) { result += (i + 2).ToString() + "," + "岗位" + "," + "[" + col4 + "]错误!" + "|"; } } else { result += (i + 2).ToString() + "," + "岗位" + "," + "此项为必填项!" + "|"; } string col5 = pds.Rows[i][5].ToString().Trim(); if (!string.IsNullOrEmpty(col5)) { if (col5.Length > 50) { result += (i + 2).ToString() + "," + "电话" + "," + "[" + col5 + "]错误!" + "|"; } } string col7 = pds.Rows[i][7].ToString().Trim(); if (!string.IsNullOrEmpty(col7)) { if (col7 != "是" && col7 != "否") { result += (i + 2).ToString() + "," + "在职" + "," + "[" + col7 + "]错误!" + "|"; } } else { result += (i + 2).ToString() + "," + "在职" + "," + "此项为必填项!" + "|"; } } if (!string.IsNullOrEmpty(result)) { result = result.Substring(0, result.LastIndexOf("|")); } errorInfos.Clear(); if (!string.IsNullOrEmpty(result)) { string results = result; List errorInfoList = results.Split('|').ToList(); foreach (var item in errorInfoList) { string[] errors = item.Split(','); Model.ErrorInfo errorInfo = new Model.ErrorInfo(); errorInfo.Row = errors[0]; errorInfo.Column = errors[1]; errorInfo.Reason = errors[2]; errorInfos.Add(errorInfo); } if (errorInfos.Count > 0) { Grid1.DataSource = errorInfos; Grid1.DataBind(); } } else { ShowNotify("审核完成,请点击保存!", MessageBoxIcon.Success); } } else { throw new Exception("导入数据为空!"); } return true; } #region 导入 /// /// 导入 /// /// /// protected void btnSave_Click(object sender, EventArgs e) { if (errorInfos.Count <= 0) { string rootPath = Server.MapPath("~/"); string initFullPath = rootPath + initPath; if (!Directory.Exists(initFullPath)) { Directory.CreateDirectory(initFullPath); } string filePath = initFullPath + this.hdfileName.Text; ImportXlsToData2(filePath); } else { Alert.ShowInTop("请先将错误数据修正,再重新导入保存!", MessageBoxIcon.Warning); } } #region 读Excel提取数据 /// /// 从Excel提取数据--》Dataset /// /// Excel文件路径名 private void ImportXlsToData2(string fileName) { try { 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.SelectCommand.CommandTimeout = 1200; oleAdMaster.Fill(ds, "m_tableName"); oleAdMaster.Dispose(); oleDBConn.Close(); oleDBConn.Dispose(); AddDatasetToSQL2(ds.Tables[0]); } catch (Exception ex) { throw ex; } } #endregion /// /// 将Dataset的数据导入数据库 /// /// 数据集 /// 数据集列数 /// private bool AddDatasetToSQL2(DataTable pds) { string result = string.Empty; var units = from x in Funs.DB.Base_Unit select x; var workPosts = from x in Funs.DB.Base_WorkPost select x; foreach (DataRow row in pds.Rows) { Model.Person_CompanyBranchPerson companyBranchPerson = new Model.Person_CompanyBranchPerson(); companyBranchPerson.CompanyBranchPersonId = Guid.NewGuid().ToString(); string col0 = row[0].ToString().Trim(); var unit = units.FirstOrDefault(e => e.UnitName == col0); if (unit != null) { companyBranchPerson.UnitId = unit.UnitId; } companyBranchPerson.PersonName = row[1].ToString().Trim(); companyBranchPerson.Sex = row[2].ToString().Trim() == "男" ? "1" : "2"; companyBranchPerson.IdentityCard = row[3].ToString(); var workPost = workPosts.FirstOrDefault(e => e.WorkPostName == row[4].ToString().Trim()); if (workPost != null) { companyBranchPerson.WorkPostId = workPost.WorkPostId; } companyBranchPerson.Telephone = row[5].ToString().Trim(); companyBranchPerson.Address = row[6].ToString().Trim(); string isOnJob = row[7].ToString().Trim(); if (isOnJob == "是") { companyBranchPerson.IsOnJob = true; } else { companyBranchPerson.IsOnJob = false; } companyBranchPerson.Remark = row[8].ToString(); Funs.DB.Person_CompanyBranchPerson.InsertOnSubmit(companyBranchPerson); } Funs.DB.SubmitChanges(); ShowNotify("导入成功!", MessageBoxIcon.Success); PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference()); return true; } #endregion #region 导出错误提示 /// /// 导出错误提示 /// /// /// protected void btnOut_Click(object sender, EventArgs e) { //string strFileName = DateTime.Now.ToString("yyyyMMdd-hhmmss"); //System.Web.HttpContext HC = System.Web.HttpContext.Current; //HC.Response.Clear(); //HC.Response.Buffer = true; //HC.Response.ContentEncoding = System.Text.Encoding.UTF8;//设置输出流为简体中文 ////---导出为Excel文件 //HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls"); //HC.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 //System.IO.StringWriter sw = new System.IO.StringWriter(); //System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); //this.gvErrorInfo.RenderControl(htw); //HC.Response.Write(sw.ToString()); //HC.Response.End(); } /// /// 重载VerifyRenderingInServerForm方法,否则运行的时候会出现如下错误提示:“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内” /// /// public override void VerifyRenderingInServerForm(Control control) { } #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 uploadfilepath = rootPath + Const.BranchPersonTemplateUrl; string filePath = Const.BranchPersonTemplateUrl; 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 } }