using SmartScanner.ViewModel; using OfficeOpenXml; using OfficeOpenXml.Style; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; namespace SmartScanner { public static class ExcelResultRecorder { private static readonly string reportDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Reports"); private static readonly string reportFileName = $"DetectionResults_{DateTime.Now:yyyyMMdd}.xlsx"; private static readonly List _pendingRecords = new List(); private static readonly object _lock = new object(); private static Timer _autoFlushTimer; static ExcelResultRecorder() { try { // 确保报告目录存在 if (!Directory.Exists(reportDirectory)) { Directory.CreateDirectory(reportDirectory); } // 设置EPPlus许可证上下文 //ExcelPackage.LicenseContext = LicenseContext.NonCommercial; ExcelPackage.License.SetNonCommercialPersonal("Lanbao"); InitializeAutoFlush(); } catch (Exception ex) { Console.WriteLine($"ExcelResultRecorder初始化失败: {ex.Message}"); throw; } } public static void RecordDetectionResult(int sequence, string result, string qrCode = "N/A") { lock (_lock) { _pendingRecords.Add(new DetectionRecord { QrCode = qrCode, Sequence = sequence, Result = result, Operator = UserManager.CurrentUser?.Username ?? "Unknown" }); // 每10条记录或每隔20秒自动保存一次 if (_pendingRecords.Count >= 10) { Task.Run(() => FlushRecords()); } } } public static void FlushRecords() { lock (_lock) { if (_pendingRecords.Count == 0) return; try { string filePath = Path.Combine(reportDirectory, reportFileName); using (var package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets["检测结果"] ?? package.Workbook.Worksheets.Add("检测结果"); // 初始化表头(如果文件是新创建的) if (worksheet.Dimension == null) { CreateHeader(worksheet); } // 找到第一个空行 int startRow = worksheet.Dimension?.End.Row + 1 ?? 2; // 批量写入数据 for (int i = 0; i < _pendingRecords.Count; i++) { var record = _pendingRecords[i]; int currentRow = startRow + i; worksheet.Cells[currentRow, 1].Value = record.QrCode; worksheet.Cells[currentRow, 2].Value = $"点位 {record.Sequence}"; worksheet.Cells[currentRow, 3].Value = record.Result; worksheet.Cells[currentRow, 4].Value = record.DetectionTime.ToString("yyyy-MM-dd HH:mm:ss"); worksheet.Cells[currentRow, 5].Value = record.Operator; // 根据结果设置单元格背景色 var resultCell = worksheet.Cells[currentRow, 3]; resultCell.Style.Fill.PatternType = ExcelFillStyle.Solid; resultCell.Style.Fill.BackgroundColor.SetColor( record.Result == "OK" ? Color.LightGreen : Color.Red); } // 自动调整列宽 worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // 保存文件 package.Save(); EnhancedLogViewModel.Instance.AddLog($"{_pendingRecords.Count}条检测结果已保存至{reportFileName}"); } _pendingRecords.Clear(); } catch (Exception ex) { // 记录错误并保留未写入的记录 Console.WriteLine($"记录检测结果到Excel失败: {ex.Message}"); EnhancedLogViewModel.Instance.AddLog($"{_pendingRecords.Count}条检测结果保存失败,请关闭{reportFileName}后重试", "ERROR"); } } } private static void CreateHeader(ExcelWorksheet worksheet) { // 设置表头 worksheet.Cells["A1"].Value = "二维码"; worksheet.Cells["B1"].Value = "检测点位"; worksheet.Cells["C1"].Value = "检测结果"; worksheet.Cells["D1"].Value = "检测时间"; worksheet.Cells["E1"].Value = "操作人员"; // 设置表头样式 using (var range = worksheet.Cells["A1:E1"]) { range.Style.Font.Bold = true; range.Style.Border.Top.Style = ExcelBorderStyle.Thin; range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; range.Style.Border.Left.Style = ExcelBorderStyle.Thin; range.Style.Border.Right.Style = ExcelBorderStyle.Thin; range.Style.Fill.PatternType = ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(Color.LightGray); range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; } } public static void OpenReportFolder() { try { if (Directory.Exists(reportDirectory)) { System.Diagnostics.Process.Start("explorer.exe", reportDirectory); } else { Console.WriteLine("报告目录不存在"); } } catch (Exception ex) { Console.WriteLine($"打开报告文件夹失败: {ex.Message}"); } } // 定时保存任务 public static void InitializeAutoFlush() { // 如果定时器已存在,先停止并释放 if (_autoFlushTimer != null) { _autoFlushTimer.Stop(); _autoFlushTimer.Dispose(); } // 创建新的定时器 _autoFlushTimer = new Timer(20000); _autoFlushTimer.Elapsed += (s, e) => { try { Task.Run(() => FlushRecords()); } catch (Exception ex) { Console.WriteLine($"定时保存记录失败: {ex.Message}"); } }; _autoFlushTimer.AutoReset = true; _autoFlushTimer.Start(); } private class DetectionRecord { public string QrCode { get; set; } public int Sequence { get; set; } public string Result { get; set; } public DateTime DetectionTime { get; } = DateTime.Now; public string Operator { get; set; } } } }