/****************************** * 说明:下载进度窗口 * 创建人:龚宇超 * 创建日期:2018-02-09 * 修改人: * 修改日期: * 修改备注: * 版本:1.0.0.0 ******************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Threading; using System.Net; using Lskj.Control; using System.Threading.Tasks; using Lskj.Core; using DevExpress.XtraGrid.Columns; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using Lskj.Model; using Lskj.Control.BrowserSetting; using Lskj.Business; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using Lskj.Business.Impl; namespace Lskj.PubBomImport { /// /// 下载进度窗口 /// public partial class FrmProgress : Form { public FrmMain frmMain; public DynamicBomImport Model; public System.Windows.Forms.Timer ImportTimer = new System.Windows.Forms.Timer(); public FrmProgress() { InitializeComponent(); this.ControlBox = false; } /// /// 开始导入 /// /// public void StartImport(string dirPath) { try { Model = frmMain.Model; DirectoryInfo directoryInfo = new DirectoryInfo(dirPath); FileInfo[] fileInfos = directoryInfo.GetFiles(); FileInfo parentInfo = fileInfos.Where(n => n.Name.StartsWith("MX") && n.Extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (parentInfo != null) { DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5); parentTable = parentTable.Rows.Cast().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable(); StringBuilder stringBuilder = new StringBuilder(); foreach (DataRow dataRow in parentTable.Rows) { stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{dataRow["图号"] + ""}')"); stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak) values ('{(dataRow["图号"] + "").Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}') end;"); } if (!string.IsNullOrEmpty(stringBuilder.ToString())) { SqlHelper.ExecuteNonQuery(stringBuilder.ToString()); } FrmBillInfo frmBillInfo = new FrmBillInfo(); frmBillInfo.OnControlSourceBind += (s, args) => { Task task = new Task(() => { try { SetProcessBar(0, 0); SetProcessMsg($"正在导入:{Path.GetFileName(parentInfo.FullName)}"); DataTable childTable = new DataTable(); foreach (GridColumn gridColumn in frmBillInfo.GcMainView.Columns) { if (!childTable.Columns.Contains(gridColumn.FieldName)) { childTable.Columns.Add(gridColumn.FieldName, gridColumn.ColumnType); } } List deleteRows = new List(); foreach (DataRow parentRow in parentTable.Rows) { string code = parentRow["图号"] + ""; FileInfo childInfo = fileInfos.Where(n => n.Name.Contains(code) && n.Extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (childInfo != null) { DataRow childRow = childTable.NewRow(); childRow["ProductId"] = parentRow["图号"] + ""; childRow["appellation"] = parentRow["名称"] + ""; childRow["bak"] = parentRow["备注"] + ""; childRow["tamount"] = parentRow["套数"] + ""; childRow["amount"] = parentRow["套数"] + ""; childTable.Rows.Add(childRow); } else { deleteRows.Add(parentRow); } } foreach (DataRow item in deleteRows) { parentTable.Rows.Remove(item); } SetProcessBar(20, 0); frmBillInfo.GcMainView.GridControl.DataSource = childTable; SetProcessBar(40, 0); string controlSql = "select '' as billdocument_id,'0' affirmer,'0' rtagid,'{材料代码}' as productid"; frmBillInfo.InitializeHeader(Model.MaintabFocusedRow, controlSql); SetProcessBar(60, 0); frmBillInfo.BillSave(); SetProcessBar(80, 0); frmBillInfo.OnBillAdd(); string productId = Model.MaintabFocusedRow["材料代码"] + ""; string billdocumentId = Model.MaintabFocusedRow["单据编号"] + ""; string idValue = BaseImpl.GetResult($"select top 1 billdocument_id from bom_billListTab where ParentProduct = '{productId}'") + ""; string updateParentVerSql = @"update bom_BillListTab set Ver = '{0}' where Billdocument_Id='{1}' and ProductId='{0}'"; SqlHelper.ExecuteNonQuery(string.Format(updateParentVerSql, idValue, billdocumentId)); //上传文件 bool isUpload = UploadFile(parentInfo.FullName, idValue, out string msg); SetProcessBar(100, (1 / (parentTable.Rows.Count + 1)) * 100); SetProcessLabelAllMsg($"总进度:{1}/{parentTable.Rows.Count + 1}"); int.TryParse(Model.FirstRowIndex, out int index); frmMain.FirstRowIndex = index; foreach (DataRow dataRow in parentTable.Rows) { int childIndex = parentTable.Rows.IndexOf(dataRow); int nowCount = 1 + childIndex; int allCount = (int)((decimal)(1 + childIndex) / (parentTable.Rows.Count + 1) * 100); int finishCount = (int)((decimal)(1 + nowCount) / (parentTable.Rows.Count + 1) * 100); int.TryParse(dataRow["套数"] + "", out int tamount); string code = dataRow["图号"] + ""; FileInfo childInfo = fileInfos.Where(n => n.Name.Contains(code) && n.Extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (childInfo != null) { SetProcessBar(0, allCount); SetProcessMsg($"正在导入:{Path.GetFileName(childInfo.FullName)}"); DataTable detailTable = new DataTable(); frmMain.Invoke(new Action(() => { detailTable = frmMain.ToExcelDataTable(childInfo.FullName, out int count, out int errorCount, true); })); foreach (DataRow detailRow in detailTable.Rows) { int.TryParse(detailRow["amount"] + "", out int lastAmount); detailRow["tamount"] = tamount; detailRow["amount"] = tamount > 0 ? (lastAmount * tamount) + "" : lastAmount + ""; } frmBillInfo.GcMainView.GridControl.DataSource = detailTable; SetProcessBar(20, allCount); frmBillInfo.InitializeHeader(dataRow, Model.BillMasterSql); SetProcessBar(40, allCount); frmBillInfo.BillSave(); SetProcessBar(60, allCount); frmBillInfo.OnBillAdd(); string updateChildVerSql = @"update bom_BillListTab set Ver = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{0}') where Billdocument_Id = (select top 1 billdocument_id from bom_billListTab where ParentProduct = '{1}') and ProductId='{0}'"; SqlHelper.ExecuteNonQuery(string.Format(updateChildVerSql, code, productId)); SetProcessBar(80, allCount); //上传文件 isUpload = UploadFile(childInfo.FullName, idValue, out msg); SetProcessBar(100, finishCount); SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}"); } else { SetProcessBar(100, finishCount); SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { this.DialogResult = DialogResult.OK; this.Close(); ImportTimer?.Dispose(); } }); task.Start(); }; frmBillInfo.OnLoad(Model); frmMain.ParentView = frmBillInfo.GcMainView; } else { MessageUtil.Show("未包含结构文件"); Close(); ImportTimer?.Dispose(); } } catch (Exception ex) { MessageUtil.Show(ex.Message); Close(); ImportTimer?.Dispose(); } } /// /// 显示当前文件 /// /// private void SetProcessMsg(string text) { this.labelCurrentItem.Invoke(new Action(() => { this.labelCurrentItem.Text = text; })); } private void SetProcessLabelAllMsg(string text) { this.lblAll.Invoke(new Action(() => { this.lblAll.Text = text; })); } /// /// 显示当前进度 /// /// /// private void SetProcessBar(int current, int total) { this.Invoke(new Action(() => { this.progressBarCurrent.Value = current; this.progressBarTotal.Value = total; })); } /// /// 获取表格数据 /// /// /// /// /// public DataTable ExcelToDatatable(string fileName, DynamicBomImport Model, string sheetName = "", int firstRowIndex = 0) { DataTable data = new DataTable(); FileStream fs; IWorkbook workbook = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 { workbook = new XSSFWorkbook(fs); } else if (fileName.IndexOf(".xls") > 0) // 2003版本 { workbook = new HSSFWorkbook(fs); } ISheet sheet; if (!string.IsNullOrEmpty(sheetName)) { sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据 } else { //也可以根据sheet编号来获取数据 sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表) } if (sheet != null) { int startRow = firstRowIndex + 1; IRow firstRow = sheet.GetRow(firstRowIndex); IRow bandRow = null; int cellCount = firstRow.LastCellNum; for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)//第一行列数循环 { ICell titleCell = firstRow.GetCell(i); ICell bandCell = null; bool isBandTitle = false; if (titleCell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, firstRowIndex, i); startRow = mergrRange.LastRow + 1; if (mergrRange != null) { if (mergrRange.FirstColumn < mergrRange.LastColumn && !Model.CustomerServiceApp) { isBandTitle = true; bandRow = sheet.GetRow(mergrRange.LastRow + 1); titleCell = firstRow.GetCell(mergrRange.FirstColumn); bandCell = bandRow.GetCell(i); CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i); if (bandMergrRange != null) { startRow = bandMergrRange.LastRow + 1; } else { startRow = mergrRange.LastRow + 2; } } else { startRow = mergrRange.LastRow + 1; } } } string fieldName = ""; if (!isBandTitle || bandRow == null) { fieldName = GetCellValue(titleCell); } else { fieldName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}"; } if (string.IsNullOrEmpty(fieldName) && titleCell.IsMergedCell) { cellCount -= 1; continue; } DataColumn column = new DataColumn(fieldName);//获取标题 data.Columns.Add(column);//添加列 } //最后一行的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; i++)//循环遍历所有行 { IRow row = sheet.GetRow(i);//第几行 if (row == null) { continue; //没有数据的行默认是null; } //将excel表每一行的数据添加到datatable的行中 DataRow dataRow = data.NewRow(); int dataRowIndex = 0; for (int j = firstRow.FirstCellNum; j < cellCount; j++) { ICell cell = row.GetCell(j); if (cell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, i, j); if (j == mergrRange.FirstColumn) { dataRow[dataRowIndex] = GetCellValue(row.GetCell(j)); dataRowIndex += 1; } else { continue; } } else { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null { dataRow[dataRowIndex] = GetCellValue(row.GetCell(j)); dataRowIndex += 1; } } } data.Rows.Add(dataRow); } } return data; } catch (IOException ex) { throw new IOException(string.Format("读取模板内容失败,原因:{0}", ex.Message)); } catch (Exception ex) { throw new Exception(string.Format("读取模板内容失败,原因:{0}", ex.Message)); } } /// /// 获取单元格值 /// /// /// public static string GetCellValue(ICell cell) { string cellValue = ""; try { if (cell != null) { // 根据单元格类型获取值 switch (cell.CellType) { case CellType.String: cellValue = cell.StringCellValue; break; case CellType.Numeric: cellValue = cell.NumericCellValue.ToString(); break; case CellType.Boolean: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.Formula://单元格中带有公式,根据类型继续判断 switch (cell.CachedFormulaResultType) { case CellType.String: cellValue = cell.StringCellValue; break; case CellType.Numeric: cellValue = cell.NumericCellValue.ToString(); break; case CellType.Boolean: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.Blank: break; default: cellValue.ToString(); break; } break; default: cellValue = cell.ToString(); break; } } } catch (Exception) { } return cellValue; } /// /// 获取合并区域 /// /// /// /// /// private CellRangeAddress FindMergedRegion(ISheet sheet, int rowIndex, int columnIndex) { int mergedRegionsCount = sheet.NumMergedRegions; for (int i = 0; i < mergedRegionsCount; i++) { CellRangeAddress mergedRegion = sheet.GetMergedRegion(i); if (mergedRegion.IsInRange(rowIndex, columnIndex)) { return mergedRegion; // 返回合并区域 } } return null; // 未找到合并区域 } /// /// 上传文件 /// /// /// /// private bool UploadFile(string filePath, string idValue, out string msg) { bool isUpload = false; string File = filePath; string returnMsg = ""; string postUrl = ""; try { //获取文件信息 FileInfo fileInfo = new FileInfo(File); string suffix = Path.GetExtension(File); string name = fileInfo.Name; DateTime creationTime = fileInfo.CreationTime; byte[] fileBytes = ConvertFileToBytes(File); string fileStream = Convert.ToBase64String(fileBytes); string userId = ERPInfo.Instance.UserId; DateTime uploadTime = DateTime.Now; //上传文件到服务器目录 postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}"; if (!string.IsNullOrEmpty(idValue)) { string token = ""; string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx"; HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8); Dictionary loginPmsDic = new Dictionary(); loginPmsDic.Add("method", "Login"); loginPmsDic.Add("username", ERPInfo.Instance.UserName); loginPmsDic.Add("password", ERPInfo.Instance.InPassWord); HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult); if (loginResponse != null && !string.IsNullOrEmpty(loginResult)) { JObject jObject = JsonConvert.DeserializeObject(loginResult); if (jObject.ContainsKey("success")) { if ((jObject["success"] + "").Equals("True")) { if (jObject.ContainsKey("token")) { token = jObject["token"] + ""; } } } } if (!string.IsNullOrEmpty(token)) { postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, Model.ModuleCode, idValue, "file", fileBytes.Length, 0, name, "DoWebUpload", "010105"); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; Dictionary headerDic = new Dictionary(); headerDic.Add("Authorization", $"Bearer {token}"); HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { isUpload = true; } else { if (jsonObject.ContainsKey("msg")) { returnMsg = jsonObject["msg"] + ""; } isUpload = false; } } else { returnMsg = "上传请求失败"; isUpload = false; } } else { returnMsg = loginResult; isUpload = false; } } else { returnMsg = "上传节点值不能为空"; isUpload = false; } } catch (Exception ex) { returnMsg = ex.Message; isUpload = false;