using Microsoft.Office.Interop.Excel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using UAS_Tools_HY; using UAS_Tools_HY.Properties; using UAS_Tools_HY.PublicMethods; using Application = Microsoft.Office.Interop.Excel.Application; using DataTable = System.Data.DataTable; namespace UAS_MES_Tools { public partial class Main : Form { string _Account, _Password, _UserName; DataTable dt; Timer loadTime; string minTime, maxTime; string curRule, curRuleLeng; int ishaveInd; public Main(string account, string password) { _Account = account; _Password = password; InitializeComponent(); } private void Main_Load(object sender, EventArgs e) { currUser.Text = "当前账户: " + _Account; dt = ConnectDB.ExecuteSelect($"select * from employee where em_code = '{_Account}'"); if (dt.Rows.Count > 0) { _UserName = dt.Rows[0]["em_name"].ToString(); } loadTime_Tick(null, null); loadTime = new Timer(); loadTime.Interval = 1000; loadTime.Tick += loadTime_Tick; loadTime.Start(); SN.SelectAll(); SN.Focus(); settingLeftInput1.Text = BaseUtil.GetCacheData("SettingCount").ToString(); settingLeftInput2.Text = BaseUtil.GetCacheData("SettingVolume").ToString(); dSum.Text = BaseUtil.GetCacheData("SettingVolume").ToString(); settingRightInput1.Text = BaseUtil.GetCacheData("SettingNGPath").ToString(); settingRightInput2.Text = BaseUtil.GetCacheData("SettingExportPath").ToString(); QDcheckbox1.Checked = true; QDdtp2.Value = QDdtp1.Value.AddDays(1); rulesQuery_Click(null, null); QDquery_Click(null, null); } private void SN_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; if (CheckEnter()) return; bool checkRes = true; if (radio1.Checked) { dt = ConnectDB.ExecuteSelect($@"SELECT COUNT(1) sum FROM dcrlogexcel WHERE item = '{SN.Text.Trim()}'"); if (dt.Rows[0]["sum"].ToString() == "0") { PlaySound("NG"); MessageBox.Show($"{SN.Text.Trim()},没有DCR测试数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); checkRes = false; return; } } if (FormMethods.IsCheckSNRules(curRule, SN.Text.Trim(), curRuleLeng)) { PlaySound("NG"); MessageBox.Show($"{SN.Text.Trim()},不符合条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); checkRes = false; return; } ishaveInd = -1; if (Datas.Rows.Count > 0) { foreach (DataGridViewRow item in Datas.Rows) { if (SN.Text.Trim() == item.Cells[0].Value.ToString()) { ishaveInd = Datas.Rows.IndexOf(item); } } } if (ishaveInd >= 0) { int iCou = Convert.ToInt32(Datas.Rows[ishaveInd].Cells[2].Value); iCou += 1; Datas.Rows[ishaveInd].Cells[3].Value = currTime.Text; Datas.Rows[ishaveInd].Cells[6].Value = checkRes ? "OK" : "NG"; PlaySound("OK"); } else { DataGridViewRow row = new DataGridViewRow(); row.CreateCells(Datas); row.Cells[0].Value = SN.Text.Trim(); row.Cells[1].Value = BoxNo.Text.Trim(); row.Cells[2].Value = 1; row.Cells[3].Value = currTime.Text; row.Cells[4].Value = _UserName; row.Cells[5].Value = radio1.Checked ? "是" : "否"; row.Cells[6].Value = checkRes ? "OK" : "NG"; Datas.Rows.Add(row); PlaySound("OK"); Datas.FirstDisplayedScrollingRowIndex = Datas.Rows.Count - 1; if (ChangeDetail()) { SN.Text = ""; BoxNo.Text = ""; dCount.Text = "0"; Datas.Rows.Clear(); BoxNo.Focus(); BoxNo.SelectAll(); } } } private bool ChangeDetail() { int inputSum = Convert.ToInt32(dCount.Text); dCount.Text = (inputSum + 1).ToString(); if(Convert.ToInt32(dCount.Text) == Convert.ToInt32(dSum.Text)) { foreach (DataGridViewRow item in Datas.Rows) { int insertCount = ConnectDB.ExecuteInsert($@"INSERT INTO g_packing_sncheck (work_order,part_no,sn,outbox_no, count,update_time,update_name,check_id,rule_name,rule_value) VALUES ( '', '', '{item.Cells[0].Value}', '{item.Cells[1].Value}', '{item.Cells[2].Value}',sysdate,'{_UserName}',packcheckid_seq.NEXTVAL,'{dRules.Text.Trim()}','{curRule}' )"); } return true; } else { return false; } } private void BoxNo_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) return; if (CheckEnter()) return; if (Datas.Rows.Count > 0) { foreach(DataGridViewRow item in Datas.Rows) { item.Cells[1].Value = BoxNo.Text.Trim(); } } BoxNo.Enabled = false; SN.SelectAll(); SN.Focus(); } private bool CheckEnter() { if (string.IsNullOrEmpty(settingLeftInput1.Text)) { MessageBox.Show("请维护列表记录数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return true; } if (string.IsNullOrEmpty(settingLeftInput2.Text)) { MessageBox.Show("请维护箱内容量", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return true; } if (!Regex.IsMatch(dSum.Text, @"^[1-9]\d*$")) { MessageBox.Show("箱内容量维护应为正整数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return true; } if (string.IsNullOrEmpty(dRules.Text)) { MessageBox.Show("请选择条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return true; } if (dRules.Enabled) { MessageBox.Show("请选择确认条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return true; } return false; } private void settingLeftSubmit_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(settingLeftInput1.Text)) { MessageBox.Show("请输入列表记录数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(settingLeftInput2.Text)) { MessageBox.Show("请输入箱内容量", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } BaseUtil.SetCacheData("SettingCount", settingLeftInput1.Text); BaseUtil.SetCacheData("SettingVolume", settingLeftInput2.Text); dSum.Text = BaseUtil.GetCacheData("SettingVolume").ToString(); MessageBox.Show("已提交扫描设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void settingRightSubmit_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(settingRightInput2.Text)) { MessageBox.Show("请选择导出文件目录", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if(!string.IsNullOrEmpty(settingRightInput1.Text)) BaseUtil.SetCacheData("SettingNGPath", settingRightInput1.Text); BaseUtil.SetCacheData("SettingExportPath", settingRightInput2.Text); MessageBox.Show("已提交文件设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void QDquery_Click(object sender, EventArgs e) { StringBuilder filterStr = new StringBuilder(); if (!string.IsNullOrEmpty(QDInput1.Text)) { filterStr.Append($"WHERE instr(SN,'{QDInput1.Text}') > 0"); } if (!string.IsNullOrEmpty(QDInput2.Text)) { if (filterStr.Length == 0) { filterStr.Append($"WHERE instr(OUTBOX_NO,'{QDInput2.Text}') > 0"); } else { filterStr.Append($" and instr(OUTBOX_NO, '{QDInput2.Text}') > 0"); } } if (QDcheckbox1.Checked) { string dtp1 = QDdtp1.Value.ToString("yyyy-MM-dd 00:00:00"); string dtp2 = QDdtp2.Value.ToString("yyyy-MM-dd 00:00:00"); if (filterStr.Length == 0) { filterStr.Append($"WHERE update_time > TO_DATE('{dtp1}','YYYY-MM-DD HH24:MI:SS') AND update_time <= TO_DATE('{dtp2}','YYYY-MM-DD HH24:MI:SS')"); } else { filterStr.Append($" AND update_time > TO_DATE('{dtp1}','YYYY-MM-DD HH24:MI:SS') AND update_time <= TO_DATE('{dtp2}','YYYY-MM-DD HH24:MI:SS')"); } } dt = ConnectDB.ExecuteSelect($@"SELECT sn dqsn,outbox_no dqoutbox_no,count dqcount, update_time dqupdate_time,update_name dqname,rule_name dqrule_name,rule_value dqrule_value FROM g_packing_sncheck {filterStr.ToString()} ORDER BY update_time"); QDDatas.DataSource = dt; } private void QDexport_Click(object sender, EventArgs e) { if(QDDatas.Rows.Count == 0) { MessageBox.Show("请先查询出导出数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(settingRightInput2.Text)) { MessageBox.Show("请先在设置中选择导出路径", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } Application excelApp = null; Workbook workbook = null; Worksheet worksheet = null; Range range = null; string tempTemplatePath = null; try { string exportPath = Path.Combine(settingRightInput2.Text, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".xlsx"); if (string.IsNullOrEmpty(settingRightInput2.Text) || !Directory.Exists(settingRightInput2.Text)) { MessageBox.Show($"输出目录不存在: {settingRightInput2.Text}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } byte[] templateBytes = Resources.exportModel; // 假设Resources.exportModel是有效的资源 if (templateBytes == null || templateBytes.Length == 0) { MessageBox.Show("未能加载模板文件", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } tempTemplatePath = Path.GetTempFileName().Replace(".tmp", ".xlsx"); File.WriteAllBytes(tempTemplatePath, templateBytes); excelApp = new Application(); excelApp.Visible = false; excelApp.DisplayAlerts = false; workbook = excelApp.Workbooks.Open(tempTemplatePath); object sheetIndex = 1; worksheet = (Worksheet)workbook.Worksheets[sheetIndex]; int startRow = 2; int dataRowsCount = QDDatas.Rows.Count; for (int i = 0; i < QDDatas.Rows.Count; i++) { worksheet.Cells[startRow + i, 1] = i + 1; // 改为从1开始编号,更符合Excel习惯 worksheet.Cells[startRow + i, 2] = QDDatas.Rows[i].Cells[0].Value?.ToString(); } int endRow = startRow + dataRowsCount - 1; range = worksheet.Range[worksheet.Cells[startRow, 1], worksheet.Cells[endRow, 2]]; range.HorizontalAlignment = XlHAlign.xlHAlignCenter; // 水平居中 range.VerticalAlignment = XlVAlign.xlVAlignCenter; // 垂直居中 worksheet.Columns.AutoFit(); // 修复SaveAs方法,使用正确的参数 workbook.SaveAs( Filename: exportPath, FileFormat: XlFileFormat.xlOpenXMLWorkbook, Password: Type.Missing, WriteResPassword: Type.Missing, ReadOnlyRecommended: Type.Missing, CreateBackup: Type.Missing, AccessMode: XlSaveAsAccessMode.xlExclusive, ConflictResolution: Type.Missing, AddToMru: false, TextCodepage: Type.Missing, TextVisualLayout: Type.Missing, Local: Type.Missing ); MessageBox.Show($"Excel文件已成功导出到: {exportPath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"生成 Excel 文件时出错: {ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { // 正确释放COM对象 if (worksheet != null) { try { Marshal.ReleaseComObject(worksheet); } catch { } worksheet = null; } if (workbook != null) { try { workbook.Close(false); Marshal.ReleaseComObject(workbook); } catch { } workbook = null; } if (excelApp != null) { try { excelApp.Quit(); Marshal.ReleaseComObject(excelApp); } catch { } excelApp = null; } if (!string.IsNullOrEmpty(tempTemplatePath) && File.Exists(tempTemplatePath)) { try { File.Delete(tempTemplatePath); } catch (Exception ex) { } } GC.Collect(); GC.WaitForPendingFinalizers(); } } private void rulesAdd_Click(object sender, EventArgs e) { StringBuilder filterStr = new StringBuilder(); if (!string.IsNullOrEmpty(rulesInput1.Text)) { filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0"); } if (!string.IsNullOrEmpty(rulesInput2.Text)) { if(filterStr.Length == 0) { filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0"); } else { filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0"); } } Form rulesList = new RulesList("Add",_UserName); if (rulesList.ShowDialog() == DialogResult.OK) { MessageBox.Show("新增规则成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3, RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc"); RulesDatas.DataSource = dt; } } private void rulesQuery_Click(object sender, EventArgs e) { StringBuilder filterStr = new StringBuilder(); if (!string.IsNullOrEmpty(rulesInput1.Text)) { filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0"); } if (!string.IsNullOrEmpty(rulesInput2.Text)) { if (filterStr.Length == 0) { filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0"); } else { filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0"); } } dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3, RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc"); RulesDatas.DataSource = dt; } private void RulesDatas_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0 && !RulesDatas.Rows[e.RowIndex].IsNewRow) { DataGridView dgv = sender as DataGridView; if (dgv != null) { DataGridViewRow selectedRow = dgv.Rows[e.RowIndex]; string RULE_ID = selectedRow.Cells[0].Value.ToString(); StringBuilder filterStr = new StringBuilder(); if (!string.IsNullOrEmpty(rulesInput1.Text)) { filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0"); } if (!string.IsNullOrEmpty(rulesInput2.Text)) { if (filterStr.Length == 0) { filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0"); } else { filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0"); } } Form rulesList = new RulesList("Modify",RULE_ID, _UserName); if (rulesList.ShowDialog() == DialogResult.OK) { MessageBox.Show("修改规则成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3, RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc"); RulesDatas.DataSource = dt; } } } } private void RulesDatas_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0 && !RulesDatas.Rows[e.RowIndex].IsNewRow) { DataGridView dgv = sender as DataGridView; if (dgv != null) { DataGridViewRow selectedRow = dgv.Rows[e.RowIndex]; if (dRules.Enabled) { dRules.Text = selectedRow.Cells[1].Value.ToString(); curRule = selectedRow.Cells[2].Value.ToString(); curRuleLeng = selectedRow.Cells[4].Value.ToString(); } } } } private void boxBtn_Click(object sender, EventArgs e) { BoxNo.Enabled = true; BoxNo.Focus(); BoxNo.SelectAll(); } private void settingRightInput1_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Title = "请选择告警文件"; openFileDialog.Filter = "可执行文件 (*.wav)|*.wav|所有文件 (*.*)|*.*"; openFileDialog.FilterIndex = 1; openFileDialog.RestoreDirectory = true; if (!string.IsNullOrEmpty(settingRightInput1.Text) && System.IO.File.Exists(settingRightInput1.Text)) { openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(settingRightInput1.Text); } else { openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); } if (openFileDialog.ShowDialog() == DialogResult.OK) { settingRightInput1.Text = openFileDialog.FileName; } } } private void settingRightInput2_Click(object sender, EventArgs e) { using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) { folderBrowserDialog.Description = "请选择导出文件夹"; if (!string.IsNullOrEmpty(settingRightInput2.Text) && System.IO.Directory.Exists(settingRightInput2.Text)) { folderBrowserDialog.SelectedPath = settingRightInput2.Text; } else { folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // folderBrowserDialog.SelectedPath = ""; } if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { settingRightInput2.Text = folderBrowserDialog.SelectedPath; } } } private void QDdtp1_ValueChanged(object sender, EventArgs e) { if (QDdtp1.Value > QDdtp2.Value) { QDdtp1.Value = QDdtp2.Value.AddDays(-1); MessageBox.Show("时间不得大于最大时间", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } minTime = QDdtp1.Value.ToString("yyyy-mm-dd hh:mm:ss"); } private void DRulesBtn_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(dRules.Text)) { MessageBox.Show("请选择条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } dRules.Enabled = false; } private void DRulesBtn1_Click(object sender, EventArgs e) { dRules.Enabled = true; } private void QDdtp2_ValueChanged(object sender, EventArgs e) { if (QDdtp2.Value < QDdtp1.Value) { QDdtp2.Value = QDdtp1.Value.AddDays(1); MessageBox.Show("时间不得小于最小时间", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } maxTime = QDdtp2.Value.ToString("yyyy-mm-dd hh:mm:ss"); } private void PlaySound(string type) { if (type == "OK") { ShowMsg.Text = "Pass"; ShowMsg.BackColor = Color.LawnGreen; } else { ShowMsg.Text = "Fail"; ShowMsg.BackColor = Color.Red; } Task.Run(() => { if (type == "OK") { using (var stream = UAS_Tools_HY.Properties.Resources.OK) { SoundPlayer player = new SoundPlayer(stream); player.Play(); } } else { if (string.IsNullOrEmpty(settingRightInput1.Text)) { using (var stream = UAS_Tools_HY.Properties.Resources.NG) { SoundPlayer player = new SoundPlayer(stream); player.Play(); } } else { string customPath = settingRightInput1.Text.Trim(); if (File.Exists(customPath)) { SoundPlayer player = new SoundPlayer(customPath); player.Play(); } } } }); } public void loadTime_Tick(object sender, EventArgs e) { string currentDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); currTime.Text = currentDate; } } }