using BLL; using MiniExcelLibs; using Model; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; namespace FineUIPro.Web.CLGL { public partial class InPlanMasterDetailImport : PageBase { private readonly string initPath = Const.ExcelUrl; public static List ImportDetailList = new List(); public static string errorInfos = string.Empty; public string Id { get { return (string)ViewState["Id"]; } set { ViewState["Id"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { hdFileName.Text = string.Empty; Id = Request.QueryString["Id"]; ImportDetailList.Clear(); errorInfos = string.Empty; } } protected void btnAudit_Click(object sender, EventArgs e) { try { if (fuAttachUrl.HasFile == false) { ShowNotify("请您选择Excel文件!", MessageBoxIcon.Warning); return; } string isXls = Path.GetExtension(fuAttachUrl.FileName).Trim().ToLower(); if (isXls != ".xlsx") { ShowNotify("只可以选择Excel文件!", MessageBoxIcon.Warning); return; } ImportDetailList.Clear(); errorInfos = string.Empty; string rootPath = Server.MapPath("~/"); string initFullPath = rootPath + initPath; if (!Directory.Exists(initFullPath)) { Directory.CreateDirectory(initFullPath); } hdFileName.Text = Funs.GetNewFileName() + isXls; string filePath = initFullPath + hdFileName.Text; fuAttachUrl.PostedFile.SaveAs(filePath); ImportXlsToData(filePath); } catch (Exception ex) { Alert alert = new Alert { Message = "'" + ex.Message + "'", Target = Target.Self }; alert.Show(); } } private void ImportXlsToData(string fileName) { DataTable rows = MiniExcel.QueryAsDataTable(fileName, useHeaderRow: true); ResponeData responeData = AddDataTableToImportList(rows); if (responeData.code == 1) { ShowNotify("审核完成,请点击导入!", MessageBoxIcon.Success); } else { Alert alert = new Alert { Message = responeData.message, Target = Target.Self }; alert.Show(); } } private ResponeData AddDataTableToImportList(DataTable table) { ResponeData responeData = new ResponeData(); List result = new List(); List importItems = new List(); if (table == null || table.Rows.Count == 0) { responeData.code = 0; responeData.message = "导入数据为空!"; return responeData; } if (!table.Columns.Contains("计划入库数量")) { responeData.code = 0; responeData.message = "导入Excel格式错误!模板列必须包含:计划入库数量"; return responeData; } bool hasMaterialCode = table.Columns.Contains("材料主编码"); bool hasCodeInfo = table.Columns.Contains("材料编码") && table.Columns.Contains("炉号") && table.Columns.Contains("批号"); if (!hasMaterialCode && !hasCodeInfo) { responeData.code = 0; responeData.message = "导入Excel格式错误!模板列必须包含材料主编码,或同时包含材料编码、炉号、批号"; return responeData; } Tw_InOutPlanMaster master = TwInOutplanmasterService.GetById(Id); if (master == null) { responeData.code = 0; responeData.message = "请先保存入库申请后再导入明细!"; return responeData; } if (master.InOutType != (int)TwConst.InOutType.入库) { responeData.code = 0; responeData.message = "当前单据不是入库申请,不能导入入库明细!"; return responeData; } List materialList = MaterialCodeLibService.GetMaterialCodeLibList(); for (int i = 0; i < table.Rows.Count; i++) { string materialCode = hasMaterialCode ? GetCellValue(table.Rows[i], "材料主编码") : string.Empty; string code = table.Columns.Contains("材料编码") ? GetCellValue(table.Rows[i], "材料编码") : string.Empty; string heatNo = table.Columns.Contains("炉号") ? GetCellValue(table.Rows[i], "炉号") : string.Empty; string batchNo = table.Columns.Contains("批号") ? GetCellValue(table.Rows[i], "批号") : string.Empty; string planNumText = GetCellValue(table.Rows[i], "计划入库数量"); if (string.IsNullOrEmpty(materialCode) && string.IsNullOrEmpty(code) && string.IsNullOrEmpty(heatNo) && string.IsNullOrEmpty(batchNo) && string.IsNullOrEmpty(planNumText)) { continue; } HJGL_MaterialCodeLib material = null; if (!string.IsNullOrEmpty(materialCode)) { material = materialList.FirstOrDefault(x => x.MaterialCode == materialCode); } else { material = materialList.FirstOrDefault(x => x.Code == code && x.HeatNo == heatNo && x.BatchNo == batchNo); } if (material == null) { result.Add("第" + (i + 2).ToString() + "行,材料信息,材料编码库中不存在此材料!"); continue; } decimal planNum; if (!decimal.TryParse(planNumText, out planNum) || planNum <= 0) { result.Add("第" + (i + 2).ToString() + "行,计划入库数量,请输入大于0的数字!"); continue; } importItems.Add(new InPlanDetailImportItem { MaterialCode = material.MaterialCode, Code = material.Code, HeatNo = material.HeatNo, BatchNo = material.BatchNo, PlanNum = planNum, MaterialName = material.MaterialName, MaterialDef = material.MaterialDef }); } if (result.Count > 0) { ImportDetailList.Clear(); errorInfos = string.Join("|", result.Distinct()); responeData.code = 0; responeData.message = errorInfos; return responeData; } ImportDetailList = importItems.GroupBy(x => x.MaterialCode).Select(x => { InPlanDetailImportItem item = x.First(); item.PlanNum = x.Sum(y => y.PlanNum); return item; }).ToList(); errorInfos = string.Empty; responeData.code = ImportDetailList.Count > 0 ? 1 : 0; responeData.message = ImportDetailList.Count > 0 ? string.Empty : "导入数据为空!"; return responeData; } protected void btnImport_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(errorInfos)) { ShowNotify("请先将错误数据修正,再重新导入提交!", MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(hdFileName.Text)) { ShowNotify("请先审核要导入的文件!", MessageBoxIcon.Warning); return; } Grid1.DataSource = ImportDetailList; Grid1.DataBind(); Grid1.RecordCount = ImportDetailList.Count; } protected void btnSave_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(errorInfos)) { ShowNotify("请先将错误数据修正,再重新导入提交!", MessageBoxIcon.Warning); return; } SaveDetails(); string rootPath = Server.MapPath("~/"); string filePath = rootPath + initPath + hdFileName.Text; if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) { File.Delete(filePath); } ShowNotify("导入成功!", MessageBoxIcon.Success); PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference()); } private void SaveDetails() { foreach (InPlanDetailImportItem item in ImportDetailList) { Tw_InOutDetailOutput queryDetail = new Tw_InOutDetailOutput() { InOutPlanMasterId = Id, MaterialCode = item.MaterialCode }; Tw_InOutDetailOutput detailOutput = TwInOutplandetailService.GetByModle(queryDetail).FirstOrDefault(); if (detailOutput == null) { Tw_InOutPlanDetail newDetail = new Tw_InOutPlanDetail { Id = SQLHelper.GetNewID(), InOutPlanMasterId = Id, MaterialCode = item.MaterialCode, PlanNum = item.PlanNum }; TwInOutplandetailService.Add(newDetail); } else { Tw_InOutPlanDetail detail = TwInOutplandetailService.GetById(detailOutput.Id); detail.PlanNum = item.PlanNum; TwInOutplandetailService.Update(detail); } } } protected void btnDownLoad_Click(object sender, EventArgs e) { string rootPath = Server.MapPath("~/"); string tempDirectory = rootPath + @"File\Excel\Temp\"; if (!Directory.Exists(tempDirectory)) { Directory.CreateDirectory(tempDirectory); } string tempPath = tempDirectory + "入库明细导入模板" + string.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".xlsx"; DataTable template = new DataTable(); template.Columns.Add("材料主编码"); template.Columns.Add("计划入库数量"); MiniExcel.SaveAs(tempPath, template); FileInfo info = new FileInfo(tempPath); long fileSize = info.Length; Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("入库明细导入模板.xlsx", System.Text.Encoding.UTF8)); Response.ContentType = "excel/plain"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AddHeader("Content-Length", fileSize.ToString().Trim()); Response.TransmitFile(tempPath, 0, fileSize); Response.Flush(); Response.Close(); File.Delete(tempPath); } protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e) { Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue); Grid1.DataSource = ImportDetailList; Grid1.DataBind(); Grid1.RecordCount = ImportDetailList.Count; } private string GetCellValue(DataRow row, string columnName) { return Convert.ToString(row[columnName]).Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "").Trim(); } public class InPlanDetailImportItem { public string MaterialCode { get; set; } public string Code { get; set; } public string HeatNo { get; set; } public string BatchNo { get; set; } public decimal PlanNum { get; set; } public string MaterialName { get; set; } public string MaterialDef { get; set; } } } }