using LB_SmartVision.SQL; using LB_SmartVisionCommon; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using CsvHelper; namespace LB_SmartVision.CSV { internal class CsvDataHelperRecordProductData { /// /// 将RecordProductDatas字典保存到CSV文件 /// /// CSV文件路径 /// 要保存的数据字典 public static void SaveToCsv(string filePath, List recordProductDatas) { try { using (var writer = new StreamWriter(filePath)) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.Context.RegisterClassMap(); // 将字典转换为CsvRecord列表 var records = recordProductDatas.Select(kvp => new CsvRecordProductData { //DictionaryKey = kvp.Key, ProductName = kvp.ProductName, ProductSN = kvp.ProductSN, InspectionOperator = kvp.InspectionOperator, NGType = kvp.NGType, NGSize = kvp.NGSize, DetectionTime = kvp.DetectionTime, CameraInspection = kvp.CameraInspection, }).ToList(); for (int i = 0; i < records.Count; i++) { AsyncLogHelper.Warn("物料号或产品名称:" + records[i].ProductName + "\r\n" + ",产品SN号:" + records[i].ProductSN + "\r\n" + ",检测作业员:" + records[i].InspectionOperator + "\r\n" + ",NG类型:" + records[i].NGType + " mm" + "\r\n" + ",NG大小:" + records[i].NGSize + " mm" + "\r\n" + ",检测时间:" + records[i].DetectionTime + "\r\n" + ",检测相机:" + records[i].CameraInspection + " mm" + "\r\n" ); } csv.WriteRecords(records); } LogHelper.Info($"数据成功保存到: {filePath}"); } catch (Exception ex) { LogHelper.Error($"保存CSV文件时出错: {ex.Message}"); //throw; } //Task.Factory.StartNew(() => //{ //}); } /// /// 从CSV文件读取数据到RecordProductDatas字典 /// /// CSV文件路径 /// 读取的数据字典 public static List LoadFromCsv(string filePath) { var recordProductDatas = new List(); try { if (!File.Exists(filePath)) { LogHelper.Info($"文件不存在: {filePath}"); return recordProductDatas; } using (var reader = new StreamReader(filePath)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Context.RegisterClassMap(); var records = csv.GetRecords(); foreach (var record in records) { var productData = new RecordProductData { ProductName = record.ProductName, ProductSN = record.ProductSN, InspectionOperator = record.InspectionOperator, NGType = record.NGType, NGSize = record.NGSize, DetectionTime = record.DetectionTime, CameraInspection = record.CameraInspection, }; recordProductDatas.Add(productData); } } LogHelper.Info($"从 {filePath} 成功读取 {recordProductDatas.Count} 条记录"); } catch (Exception ex) { LogHelper.Error($"读取CSV文件时出错: {ex.Message}"); //throw; } return recordProductDatas; } } }