Files
lserp_cs_6.0/插件库/Lskj.PubBomImport/FrmProgress.cs
T
wyf ffa4627f8f SVN r464
SVN-Revision: r464
2025-04-09 09:46:13 +00:00

1197 lines
67 KiB
C#

/******************************
* 说明:下载进度窗口
* 创建人:龚宇超
* 创建日期: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;
using System.Text.RegularExpressions;
using Lskj.Util;
using System.Web;
using Lskj.Control.Model;
namespace Lskj.PubBomImport
{
/// <summary>
/// 下载进度窗口
/// </summary>
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;
}
/// <summary>
/// 开始导入
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInDir(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)
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
FrmBillInfo frmBillInfo = new FrmBillInfo();
DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary<string, string> childFileDic = new Dictionary<string, string>();
foreach (DataRow parentRow in parentTable.Rows)
{
string fileName = (parentRow["图号"] + "").Trim();
if (fileName.StartsWith("QD") || fileName.StartsWith("ZZQD"))
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(fileName)).FirstOrDefault();
if (childInfo == null)
{
string fileSql = $"select webpath,sName from P_fm_FileTab where sName like '{fileName}%'";
DataRow fileRow = BaseImpl.GetDataRowResult(fileSql);
string webpath = fileRow != null ? fileRow["webpath"] + "" : "";
string sName = fileRow != null ? fileRow["sName"] + "" : "";
if (string.IsNullOrEmpty(webpath))
{
throw new Exception($"Bom明细附件{fileName}不存在\r\nBom导入失败");
}
else
{
using (WebClient webClient = new WebClient())
{
try
{
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
webClient.DownloadFile(url, tempFileName);
childFileDic.Add(fileName, tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{fileName}获取失败\r\nBom导入失败");
}
}
}
}
}
}
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{dataRow["图号"] + ""}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{(dataRow["图号"] + "").Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}','0199') end;");
}
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
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);
}
}
foreach (DataRow parentRow in parentTable.Rows)
{
string code = parentRow["图号"] + "";
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(code)).FirstOrDefault();
if (childInfo == null)
{
string tempFileName = childFileDic[code];
childInfo = new FileInfo(tempFileName);
}
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);
}
}
}
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);
string billNo = "";
frmBillInfo.BillSave(ref billNo);
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["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{code}'");
if (productRow == null)
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(code)).FirstOrDefault();
if (childInfo == null)
{
string tempFileName = childFileDic[code];
childInfo = new FileInfo(tempFileName);
}
if (childInfo != null)
{
if ((code.StartsWith("QD") || code.StartsWith("ZZQD")))
{
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"] = lastAmount;
}
frmBillInfo.GcMainView.GridControl.DataSource = detailTable;
SetProcessBar(20, allCount);
frmBillInfo.InitializeHeader(dataRow, Model.BillMasterSql);
SetProcessBar(40, allCount);
string childBillNo = "";
frmBillInfo.BillSave(ref childBillNo);
SetProcessBar(60, allCount);
frmBillInfo.OnBillAdd();
//记录历史版本号
string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, childBillNo));
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
{
FileInfo childInfo = fileInfos.Where(n => n.Name.StartsWith(code)).FirstOrDefault();
if (childInfo != null)
{
isUpload = UploadFile(childInfo.FullName, idValue, out msg);
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
finally
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
throw new Exception("未包含结构文件");
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.OK;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInMxFile(string dirPath)
{
try
{
Model = frmMain.Model;
FileInfo parentInfo = new FileInfo(dirPath);
if (parentInfo != null && parentInfo.Name.Trim().StartsWith("MX"))
{
if (Directory.Exists("BomImportTemp"))
{
Directory.Delete("BomImportTemp", true);
}
Directory.CreateDirectory("BomImportTemp");
DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary<string, string> childFileDic = new Dictionary<string, string>();
foreach (DataRow parentRow in parentTable.Rows)
{
string fileName = (parentRow["图号"] + "").Trim();
if (fileName.StartsWith("QD") || fileName.StartsWith("ZZQD"))
{
string fileSql = $"select webpath,sName from P_fm_FileTab where sName like '{fileName}%'";
DataRow fileRow = BaseImpl.GetDataRowResult(fileSql);
string webpath = fileRow != null ? fileRow["webpath"] + "" : "";
string sName = fileRow != null ? fileRow["sName"] + "" : "";
if (string.IsNullOrEmpty(webpath))
{
throw new Exception($"Bom明细附件{fileName}不存在\r\nBom导入失败");
}
else
{
using (WebClient webClient = new WebClient())
{
try
{
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
webClient.DownloadFile(url, tempFileName);
childFileDic.Add(fileName, tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{fileName}获取失败\r\nBom导入失败");
}
}
}
}
}
StringBuilder stringBuilder = new StringBuilder();
foreach (DataRow dataRow in parentTable.Rows)
{
string code = (dataRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{dataRow["图号"] + ""}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{(dataRow["图号"] + "").Replace("'", "''")}','{(dataRow["名称"] + "").Replace("'", "''")}','{(dataRow["备注"] + "").Replace("'", "''")}','0199') 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);
}
}
foreach (DataRow parentRow in parentTable.Rows)
{
string code = (parentRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
string tempFileName = childFileDic[code];
FileInfo childInfo = new FileInfo(tempFileName);
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
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
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);
string billNo = "";
frmBillInfo.BillSave(ref billNo);
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["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
DataRow productRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{code}'");
if (productRow == null)
{
string tempFileName = childFileDic[code];
FileInfo childInfo = new FileInfo(tempFileName);
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"] = lastAmount;
}
frmBillInfo.GcMainView.GridControl.DataSource = detailTable;
SetProcessBar(20, allCount);
frmBillInfo.InitializeHeader(dataRow, Model.BillMasterSql);
SetProcessBar(40, allCount);
string childBillNo = "";
frmBillInfo.BillSave(ref childBillNo);
SetProcessBar(60, allCount);
frmBillInfo.OnBillAdd();
//记录历史版本号
string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, childBillNo));
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);
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{nowCount + 1}/{parentTable.Rows.Count + 1}");
}
else
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
finally
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
MessageUtil.Show("不是MX文件");
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入3
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInQDFile(DataTable sourceTable, Dictionary<string, string> filesDic)
{
try
{
foreach (DataRow sourceRow in sourceTable.Rows)
{
if (sourceRow.RowState == DataRowState.Deleted)
{
continue;
}
string fileName = sourceRow[Model.AfterBomFieldName] + "";
string dirPath = filesDic.ContainsKey(fileName) ? filesDic[fileName] : "";
FileInfo parentInfo = null;
if (string.IsNullOrEmpty(dirPath))
{
continue;
}
parentInfo = new FileInfo(dirPath);
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("QD") || parentInfo.Name.Trim().StartsWith("ZZQD")))
{
string code = "";
string name = "";
string namepattern = @"^(.+?)\s+(.+)$";
Match namematch = Regex.Match(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), namepattern);
if (namematch.Success)
{
code = namematch.Groups[1].Value;
name = namematch.Groups[2].Value;
}
StringBuilder stringBuilder = new StringBuilder();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
stringBuilder.AppendLine($"if not exists (select productid from p_ProductTab where productid = '{code}')");
stringBuilder.AppendLine($"begin insert into p_ProductTab (productid,appellation,bak,SpeciesNo) values ('{code.Replace("'", "''")}','{name.Replace("'", "''")}','','0199') end;");
}
if (!string.IsNullOrEmpty(stringBuilder.ToString()))
{
SqlHelper.ExecuteNonQuery(stringBuilder.ToString());
}
}
}
FrmBillInfo frmBillInfo = new FrmBillInfo();
frmBillInfo.OnControlSourceBind += (s, args) =>
{
Task task = new Task(() =>
{
try
{
foreach (DataRow sourceRow in sourceTable.Rows)
{
if (sourceRow.RowState == DataRowState.Deleted)
{
continue;
}
int childIndex = sourceTable.Rows.IndexOf(sourceRow);
int allCount = (int)((decimal)(childIndex) / (sourceTable.Rows.Count) * 100);
int finishCount = (int)((decimal)(1 + childIndex) / (sourceTable.Rows.Count) * 100);
string fileName = sourceRow[Model.AfterBomFieldName] + "";
string dirPath = filesDic.ContainsKey(fileName) ? filesDic[fileName] : "";
FileInfo parentInfo = null;
if (string.IsNullOrEmpty(dirPath))
{
continue;
}
parentInfo = new FileInfo(dirPath);
Model = frmMain.Model;
string pattern = @"([A-Za-z]+)(\d*)$";
//原物料名称
string productCode = sourceRow != null && sourceRow.Table.Columns.Contains(Model.BeforeBomFieldName) ? sourceRow[Model.BeforeBomFieldName] + "" : "";
Match match = Regex.Match(productCode, pattern);
if (match.Success)
{
if (parentInfo != null && (parentInfo.Name.Trim().StartsWith("QD") || parentInfo.Name.Trim().StartsWith("ZZQD")))
{
string code = "";
string name = "";
string namepattern = @"^(.+?)\s+(.+)$";
Match namematch = Regex.Match(Path.GetFileNameWithoutExtension(parentInfo.Name).Trim(), namepattern);
if (namematch.Success)
{
code = namematch.Groups[1].Value;
name = namematch.Groups[2].Value;
}
match = Regex.Match(code, pattern);
if (match.Success)
{
//更新或新增并备份清单
int.TryParse(Model.FirstRowIndex, out int index);
frmMain.FirstRowIndex = index;
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
FileInfo childInfo = new FileInfo(dirPath);
if (childInfo != null)
{
frmBillInfo.OnBillAdd();
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"] = 1;
detailRow["amount"] = lastAmount;
}
SetProcessBar(20, allCount);
string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{productCode}') as billdocument_id,'0' affirmer,'0' rtagid,'{productCode}' as productid";
billMasterSql = ReplaceHelper.ReplaceRowParam(sourceRow, billMasterSql);
// 处理单据表头数据
DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql);
SetProcessBar(40, allCount);
frmBillInfo.AddOrUpdateBill(masterRow, detailTable);
SetProcessBar(60, allCount);
//备份Bom清单明细
string bakBomListSql = @"delete bom_BillListlogTab where parentProduct = '{0}' and historyVer = (select top 1 historyVer from bom_BillListTab where parentProduct = '{0}');insert into bom_BillListlogTab select * from bom_BillListTab where parentProduct = '{0}';";
SqlHelper.ExecuteNonQuery(string.Format(bakBomListSql, productCode));
string billNo = "";
frmBillInfo.BillSave(ref billNo);
SetProcessBar(80, allCount);
frmBillInfo.OnBillAdd();
//记录历史版本号
string updateHistoryVerSql = @"update bom_BillListTab set historyVer = '{0}' where Billdocument_Id='{1}'";
SqlHelper.ExecuteNonQuery(string.Format(updateHistoryVerSql, code, billNo));
StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() =>
{
if (sourceRow.Table.Columns.Contains("qms_laddf_RelatedId"))
{
sourceRow["qms_laddf_RelatedId"] = billNo;
}
}));
//执行配置的保存后sql
if (!string.IsNullOrEmpty(Model.AfterAddBomSql))
{
string afterAddBomSql = ReplaceHelper.ReplaceRowParam(sourceRow, Model.AfterAddBomSql);
SqlHelper.ExecuteNonQuery(afterAddBomSql);
}
if (!string.IsNullOrEmpty(Model.AfterAddBomSql))
{
//string afterAddBomSql = ReplaceHelper.ReplaceRowParam(sourceRow, Model.AfterAddBomSql);
//SqlHelper.ExecuteNonQuery(afterAddBomSql);
}
//上传文件
bool isUpload = UploadFile(childInfo.FullName, billNo, out string msg);
SetProcessBar(100, finishCount);
SetProcessLabelAllMsg($"总进度:{childIndex + 1}/{sourceTable.Rows.Count }");
}
else
{
throw new Exception($"Bom明细获取失败\r\nBom导入失败");
}
}
}
else
{
throw new Exception($"文件名{code}不符合规则");
}
}
else
{
MessageUtil.Show("不是QD或ZZQD文件");
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
else
{
throw new Exception($"文件名{productCode}不符合规则");
}
}
this.DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
}
finally
{
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 开始导入
/// </summary>
/// <param name="dirPaths"></param>
public void StartImportInMxFileNew(string dirPath)
{
try
{
Model = frmMain.Model;
FileInfo parentInfo = new FileInfo(dirPath);
if (parentInfo != null && parentInfo.Name.Trim().StartsWith("MX"))
{
DataTable parentTable = ExcelToDatatable(parentInfo.FullName, Model, "", 5);
parentTable = parentTable.Rows.Cast<DataRow>().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["图号"] + "")).ToList().CopyToDataTable();
Dictionary<string, string> childFileDic = new Dictionary<string, string>();
foreach (DataRow parentRow in parentTable.Rows)
{
string fileName = (parentRow["图号"] + "").Trim();
if (fileName.StartsWith("QD") || fileName.StartsWith("ZZQD"))
{
string fileSql = $"select webpath,sName from P_fm_FileTab where sName like '{fileName}%'";
DataRow fileRow = BaseImpl.GetDataRowResult(fileSql);
string webpath = fileRow != null ? fileRow["webpath"] + "" : "";
string sName = fileRow != null ? fileRow["sName"] + "" : "";
if (string.IsNullOrEmpty(webpath))
{
throw new Exception($"Bom明细附件{fileName}不存在\r\nBom导入失败");
}
else
{
using (WebClient webClient = new WebClient())
{
try
{
webpath = webpath.StartsWith("/") ? webpath : $"/{webpath}";
string url = $"{SystemInfo.Instance.OAUrl}/{webpath}";
string tempFileName = $"BomImportTemp/{sName}";
webClient.DownloadFile(url, tempFileName);
childFileDic.Add(fileName, tempFileName);
}
catch (Exception)
{
throw new Exception($"Bom明细附件{fileName}获取失败\r\nBom导入失败");
}
}
}
}
}
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);
}
}
foreach (DataRow parentRow in parentTable.Rows)
{
string code = (parentRow["图号"] + "").Trim();
if (code.StartsWith("QD") || code.StartsWith("ZZQD"))
{
string tempFileName = childFileDic[code];
FileInfo childInfo = new FileInfo(tempFileName);
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
{
throw new Exception($"Bom明细附件{code}获取失败\r\nBom导入失败");
}
}
}
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);
string billNo = "";
frmBillInfo.BillSave(ref billNo);
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, 100);
SetProcessLabelAllMsg($"总进度:1/1");
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
finally
{
this.DialogResult = DialogResult.OK;
this.Close();
ImportTimer?.Dispose();
}
});
task.Start();
};
frmBillInfo.OnLoad(Model);
frmMain.ParentView = frmBillInfo.GcMainView;
}
else
{
MessageUtil.Show("不是MX文件");
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
this.DialogResult = DialogResult.Cancel;
Close();
ImportTimer?.Dispose();
}
}
/// <summary>
/// 显示当前文件
/// </summary>
/// <param name="text"></param>
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;
}));
}
/// <summary>
/// 显示当前进度
/// </summary>
/// <param name="current"></param>
/// <param name="total"></param>
private void SetProcessBar(int current, int total)
{
this.Invoke(new Action(() =>
{
this.progressBarCurrent.Value = current;
this.progressBarTotal.Value = total;
}));
}
/// <summary>
/// 获取表格数据
/// </summary>
/// <param name="fileName"></param>
/// <param name="sheetName"></param>
/// <param name="isFirstRowColumn"></param>
/// <returns></returns>
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 != null && 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));
}
}
/// <summary>
/// 获取单元格值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 获取合并区域
/// </summary>
/// <param name="sheet"></param>
/// <param name="rowIndex"></param>
/// <param name="columnIndex"></param>
/// <returns></returns>
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; // 未找到合并区域
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="filePath"></param>
/// <param name="msg"></param>
/// <returns></returns>
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;
string speciesno = " 010102";
// 检查扩展名是否为 .xlsx 或 .xls
if (suffix.Equals(".xlsx", StringComparison.OrdinalIgnoreCase) ||
suffix.Equals(".xls", StringComparison.OrdinalIgnoreCase))
{
speciesno = "010101";
}
//上传文件到服务器目录
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<string, string> loginPmsDic = new Dictionary<string, string>();
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<JObject>(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", speciesno);
HttpTools.setting("application/x-www-form-urlencoded", null, null);
string result = "";
CookieCollection cookieCollection = null;
Dictionary<string, string> headerDic = new Dictionary<string, string>();
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;