using Modbus.Device; using OfficeOpenXml; using OfficeOpenXml.Style; using Sunny.UI; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using 全自动水压检测仪.Data; using 材料热传导系数; namespace 全自动水压检测仪 { public partial class Report : UIForm { public List CurrentReport { get; set; } Function ma; private DataGridView dataGridView; private Button btnExport; private Button btnReturn; public Report() { InitializeComponent(); SetupFormStyle(); CreateDataGridView(); CreateButtons(); this.SuspendLayout(); this.ClientSize = new System.Drawing.Size(1000, 600); this.Name = "ReportForm"; this.Text = "测试数据报表"; this.StartPosition = FormStartPosition.CenterScreen; this.ResumeLayout(false); } public Report(List CurrentReport) { InitializeComponent(); SetupFormStyle(); CreateDataGridView(); CreateButtons(); this.SuspendLayout(); this.ClientSize = new System.Drawing.Size(1000, 600); this.Name = "ReportForm"; this.Text = "测试数据报表"; this.StartPosition = FormStartPosition.CenterScreen; this.ResumeLayout(false); this.CurrentReport = CurrentReport; } /// /// 设置窗体基础样式 /// private void SetupFormStyle() { this.BackColor = SystemColors.Control; // 使用系统默认窗体背景色 this.Font = new Font("Microsoft YaHei", 9F, FontStyle.Regular, GraphicsUnit.Point); } /// /// 创建数据表格 /// private void CreateDataGridView() { // 初始化DataGridView dataGridView = new DataGridView(); dataGridView.Dock = DockStyle.Fill; dataGridView.Margin = new Padding(10); dataGridView.BackgroundColor = this.BackColor; dataGridView.BorderStyle = BorderStyle.None; dataGridView.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal; dataGridView.GridColor = Color.LightGray; // 禁止排序、编辑、添加行 dataGridView.AllowUserToAddRows = false; dataGridView.AllowUserToDeleteRows = false; dataGridView.AllowUserToOrderColumns = false; dataGridView.AllowUserToResizeRows = false; dataGridView.ReadOnly = true; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 设置表头样式 dataGridView.ColumnHeadersHeight = 40; dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.LightSkyBlue; dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black; dataGridView.ColumnHeadersDefaultCellStyle.Font = new Font(this.Font, FontStyle.Bold); dataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single; // 设置单元格样式 dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dataGridView.DefaultCellStyle.Font = this.Font; dataGridView.DefaultCellStyle.BackColor = Color.White; dataGridView.DefaultCellStyle.SelectionBackColor = Color.LightSteelBlue; dataGridView.DefaultCellStyle.SelectionForeColor = Color.Black; dataGridView.AutoGenerateColumns = false; // 创建列 CreateGridColumns(); // 添加到窗体 this.Controls.Add(dataGridView); } /// /// 创建表格列 - 修改为绑定数据源 /// private void CreateGridColumns() { dataGridView.Columns.Clear(); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "Id", HeaderText = "编号", Width = 70, DataPropertyName = "Id", // 绑定到ConductivityTestData的Id属性 SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "ContactNumber", HeaderText = "联络单号", Width = 150, DataPropertyName = "ContactNumber", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "ItemNumber", HeaderText = "件号", Width = 130, DataPropertyName = "ItemNumber", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "CreateTime", HeaderText = "时间日期", Width = 170, DataPropertyName = "CreateTime", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter, Format = "yyyy-MM-dd HH:mm:ss" // 设置日期格式 } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "startpressure", HeaderText = "初始压力(PSI)", Width = 95, DataPropertyName = "StartPressure", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter, Format = "F2" // 保留2位小数 } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "endpressure", HeaderText = "结束压力(PSI)", Width = 95, DataPropertyName = "EndPressure", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter, Format = "F2" } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "diffpressure", HeaderText = "压差(PSI)", Width = 75, DataPropertyName = "DiffPressure", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter, Format = "F2" } }); dataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "dwelltime", HeaderText = "保压时间(h)", Width = 80, DataPropertyName = "DwellTime", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter, Format = "F1" // 保留1位小数 } }); DataGridViewTextBoxColumn temperatureColumn = CreateTemperatureModeColumn(); dataGridView.Columns.Add(temperatureColumn); } /// /// 创建按钮 /// private void CreateButtons() { // 按钮容器面板 Panel btnPanel = new Panel(); btnPanel.Dock = DockStyle.Bottom; btnPanel.Height = 60; btnPanel.BackColor = this.BackColor; btnPanel.Padding = new Padding(20, 10, 20, 10); // 导出报表按钮 btnExport = new Button { Text = "导出报表", Width = 100, Height = 35, Font = new Font(this.Font, FontStyle.Regular), BackColor = Color.LightSteelBlue, FlatStyle = FlatStyle.Flat, FlatAppearance = { BorderSize = 1, BorderColor = Color.SteelBlue }, Left = 20, Top = 10, }; btnExport.Click += BtnExport_Click; btnExport.Cursor = Cursors.Hand; // 返回按钮 btnReturn = new Button { Text = "返回", Width = 100, Height = 35, Font = new Font(this.Font, FontStyle.Regular), BackColor = Color.LightSteelBlue, FlatStyle = FlatStyle.Flat, FlatAppearance = { BorderSize = 1, BorderColor = Color.SteelBlue }, Left = btnExport.Right + 20, Top = 10, }; btnReturn.Click += BtnReturn_Click; btnReturn.Cursor = Cursors.Hand; btnPanel.Controls.Add(btnExport); btnPanel.Controls.Add(btnReturn); this.Controls.Add(btnPanel); btnPanel.BringToFront(); } private DataGridViewTextBoxColumn CreateTemperatureModeColumn() { DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn { Name = "Type", HeaderText = "温度模式", Width = 100, DataPropertyName = "Type", SortMode = DataGridViewColumnSortMode.NotSortable, DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter } }; // 添加单元格格式化事件 dataGridView.CellFormatting += DataGridView_CellFormatting; return column; } /// /// 在导出报表时也需要转换 /// private string GetTemperatureModeDisplay(int type) { switch (type) { case 1: return "常温"; case 0: return "高温"; default: return "未知"; } } // 单元格格式化事件 private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // 只处理温度模式列 if (e.ColumnIndex == dataGridView.Columns["Type"].Index && e.RowIndex >= 0) { if (e.Value != null) { string typeValue = e.Value.ToString(); // 根据Type值转换显示文本 switch (typeValue) { case "1": e.Value = "常温"; break; case "0": e.Value = "高温"; break; case "常温": case "高温": // 已经是转换后的值,保持不变 break; default: e.Value = "未知"; break; } e.FormattingApplied = true; } } } private void Report_Load(object sender, EventArgs e) { // 检查数据源 if (CurrentReport == null || CurrentReport.Count == 0) { MessageBox.Show("没有测试数据可显示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { dataGridView.CellFormatting += DataGridView_CellFormatting; dataGridView.DataSource = CurrentReport; // 刷新显示 dataGridView.Refresh(); this.Text = $"测试数据报表(共{CurrentReport.Count}条记录)"; } catch (Exception ex) { MessageBox.Show($"加载数据失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// /// 导出报表按钮点击事件 /// private void BtnExport_Click(object sender, EventArgs e) { ExportReport(); } /// /// 返回按钮点击事件 /// private void BtnReturn_Click(object sender, EventArgs e) { ReturnToMain(); } /// /// 导出报表功能 /// private void ExportReport() { if (CurrentReport == null || CurrentReport.Count == 0) { MessageBox.Show("没有数据可以导出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "CSV文件|*.csv|Excel文件|*.xlsx|文本文件|*.txt"; saveFileDialog.Title = "导出报表"; saveFileDialog.FileName = $"测试报表_{DateTime.Now:yyyyMMdd_HHmmss}"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filePath = saveFileDialog.FileName; switch (Path.GetExtension(filePath).ToLower()) { case ".csv": ExportToCsv(filePath); break; case ".txt": ExportToTxt(filePath); break; case ".xlsx": ExportToExcel(filePath); break; default: ExportToCsv(filePath); break; } MessageBox.Show($"报表已成功导出到:\n{filePath}", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show($"导出报表失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// /// 修改导出功能中的温度模式显示 /// private void ExportToCsv(string filePath) { using (StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8)) { // 写入表头 writer.WriteLine("编号,联络单号,件号,时间日期,初始压力(PSI),结束压力(PSI),压差(PSI),保压时间(h),温度模式"); // 写入数据 foreach (var data in CurrentReport) { string tempMode = GetTemperatureModeDisplay(data.Type); writer.WriteLine($"{data.Id}," + $"{data.ContactNumber ?? ""}," + $"{data.ItemNumber ?? ""}," + $"{data.CreateTime:yyyy-MM-dd HH:mm:ss}," + $"{data.startpressure:F2}," + $"{data.endpressure:F2}," + $"{data.diffpressure:F2}," + $"{data.dwelltime:F1}," + $"{tempMode}"); } } } /// /// 修改文本导出中的温度模式显示 /// private void ExportToTxt(string filePath) { using (StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8)) { writer.WriteLine("===================== 测试数据报表 ====================="); writer.WriteLine($"生成时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"); writer.WriteLine($"记录数量:{CurrentReport.Count}"); writer.WriteLine("=======================================================\n"); // 写入表头 writer.WriteLine(string.Format("{0,-8}{1,-15}{2,-15}{3,-20}{4,-12}{5,-12}{6,-12}{7,-12}{8,-10}", "编号", "联络单号", "件号", "时间日期", "初始压力", "结束压力", "压差", "保压时间", "温度模式")); writer.WriteLine(new string('-', 130)); // 写入数据 foreach (var data in CurrentReport) { string tempMode = GetTemperatureModeDisplay(data.Type); writer.WriteLine(string.Format("{0,-8}{1,-15}{2,-15}{3,-20}{4,-12:F2}{5,-12:F2}{6,-12:F2}{7,-12:F1}{8,-10}", data.Id, data.ContactNumber ?? "", data.ItemNumber ?? "", data.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), data.startpressure, data.endpressure, data.diffpressure, data.dwelltime, tempMode)); } } } /// /// 导出为Excel文件(简单实现) /// private void ExportToExcel(string filePath) { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("测试数据报表"); // 设置默认样式 worksheet.Cells.Style.Font.Name = "微软雅黑"; worksheet.Cells.Style.Font.Size = 11; int currentRow = 1; // 主标题 worksheet.Cells[currentRow, 1, currentRow, 9].Merge = true; var titleCell = worksheet.Cells[currentRow, 1]; titleCell.Value = "测试数据报表"; titleCell.Style.Font.Size = 16; titleCell.Style.Font.Bold = true; titleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; titleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center; currentRow++; // 副标题 worksheet.Cells[currentRow, 1, currentRow, 9].Merge = true; var subTitleCell = worksheet.Cells[currentRow, 1]; subTitleCell.Value = $"生成时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} | 记录数量:{CurrentReport.Count}条"; subTitleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; subTitleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center; currentRow += 2; // 表头 string[] headers = { "编号", "联络单号", "件号", "时间日期", "初始压力(PSI)", "结束压力(PSI)", "压差(PSI)", "保压时间(h)", "温度模式" }; for (int i = 0; i < headers.Length; i++) { var cell = worksheet.Cells[currentRow, i + 1]; cell.Value = headers[i]; cell.Style.Font.Bold = true; cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center; cell.Style.Fill.PatternType = ExcelFillStyle.Solid; cell.Style.Fill.BackgroundColor.SetColor(Color.LightSkyBlue); cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black); // 设置列宽 worksheet.Column(i + 1).Width = 15; } // 设置表头行高 worksheet.Row(currentRow).Height = 35; currentRow++; // 数据行 foreach (var data in CurrentReport) { string tempMode = GetTemperatureModeDisplay(data.Type); worksheet.Cells[currentRow, 1].Value = data.Id; worksheet.Cells[currentRow, 2].Value = data.ContactNumber ?? ""; worksheet.Cells[currentRow, 3].Value = data.ItemNumber ?? ""; worksheet.Cells[currentRow, 4].Value = data.CreateTime; worksheet.Cells[currentRow, 5].Value = data.startpressure; worksheet.Cells[currentRow, 6].Value = data.endpressure; worksheet.Cells[currentRow, 7].Value = data.diffpressure; worksheet.Cells[currentRow, 8].Value = data.dwelltime; worksheet.Cells[currentRow, 9].Value = tempMode; // 设置数据行样式 for (int col = 1; col <= 9; col++) { var cell = worksheet.Cells[currentRow, col]; cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center; cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.LightGray); // 隔行变色 if (currentRow % 2 == 0) { cell.Style.Fill.PatternType = ExcelFillStyle.Solid; cell.Style.Fill.BackgroundColor.SetColor(Color.AliceBlue); } } // 设置格式 worksheet.Cells[currentRow, 4].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss"; worksheet.Cells[currentRow, 5].Style.Numberformat.Format = "0.00"; worksheet.Cells[currentRow, 6].Style.Numberformat.Format = "0.00"; worksheet.Cells[currentRow, 7].Style.Numberformat.Format = "0.00"; worksheet.Cells[currentRow, 8].Style.Numberformat.Format = "0.0"; // 设置行高 worksheet.Row(currentRow).Height = 25; currentRow++; } // 自动调整列宽 worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); // 保存 package.SaveAs(new FileInfo(filePath)); } } /// /// 返回主界面 /// private void ReturnToMain() { this.Close(); } private void Report_FormClosing(object sender, FormClosingEventArgs e) { //base.OnFormClosing(e); dataGridView.CellFormatting -= DataGridView_CellFormatting; } } }