当前位置: 首页 > news >正文

.net winfrom 获取上传的Excel文件 单元格的背景色

需求:根据Excel某行标注了黄色高亮颜色,说明该行数据已被用户选中(Excel文件中并没有“已选中”这一列,纯粹用颜色表示),导入数据到数据库时标注此行已选中

直接上代码:

//选择Excel文件private void btnBrowse_Click(object sender, EventArgs e){using (OpenFileDialog openFileDialog = new OpenFileDialog()){//openFileDialog.InitialDirectory = "c:\\";openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";openFileDialog.Title = "Select an Excel File";if (openFileDialog.ShowDialog() == DialogResult.OK){txtFilePath.Text = openFileDialog.FileName;}}}//上传Excel文件(判断单元格背景色)
private DataTable ReadExcelToDataTable(string filePath)
{DataTable dataTable = new DataTable();ExcelPackage.LicenseContext = LicenseContext.NonCommercial;using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filePath))){// 获取第一个工作表ExcelWorksheet worksheet = package.Workbook.Worksheets[0];// 获取最大列数和行数int rowCount = worksheet.Dimension.Rows;int columnCount = worksheet.Dimension.Columns;// 创建列for (int col = 1; col <= columnCount; col++){string columnName = worksheet.Cells[1, col].Value?.ToString() ?? $"Column{col}";dataTable.Columns.Add(columnName);}// 添加数据行(从第2行开始,第1行是标题)for (int row = 2; row <= rowCount; row++){DataRow dataRow = dataTable.NewRow();for (int col = 1; col <= columnCount; col++){var cell = worksheet.Cells[row, col];if ((col - 1) == 0)//第一列{var BackgroundColor = cell.Style.Fill.BackgroundColor.LookupColor();//单元格背景颜色:#FFFFFF00黄色;#FFFFFF白色 if (!string.IsNullOrWhiteSpace(BackgroundColor)){dataRow[col - 1] = BackgroundColor;//获取单元格背景颜色}else{dataRow[col - 1] = "#FFFFFF";//纯白色}}else//第二列.....N列,Excel数据列{dataRow[col - 1] = worksheet.Cells[row, col].Value?.ToString() ?? "";//数据}}dataTable.Rows.Add(dataRow);}}return dataTable;
}//处理Excel的数据(节选)
private void btnImport_Click(object sender, EventArgs e)
{if (!string.IsNullOrWhiteSpace(txtFilePath.Text) && File.Exists(txtFilePath.Text)){System.Data.DataTable dt = ReadExcelToDataTable(txtFilePath.Text);//读取excelif (dt != null && dt.Rows.Count > 0)//有数据{for (int i = 0; i < dt.Rows.Count; i++){//...略...if (dt.Rows[i][0]?.ToString() == "#FFFFFF00")//判断颜色代码,黄色{u.Winningbidder = dt.Rows[i][6]?.ToString();//添加选中行数据}else{u.Winningbidder = null;//不添加数据}u.WinningbidderColor = dt.Rows[i][0]?.ToString();//保存颜色代码//...略...}//...略...}//...略...}
}//根据条件替换整行背景颜色 
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{if (e.RowIndex > -1){string WinningbidderColor = this.dataGridView1.Rows[e.RowIndex].Cells["WinningbidderColor"].Value.ToString();//背景色代码 string ID = this.dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString();if (WinningbidderColor == "#FFFFFF00"){this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = ConvertToColor(WinningbidderColor);//整行颜色}else if (ID == "")//合计{this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = ConvertToColor("Red");//整行颜色this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = ConvertToColor("#FFFFFF");//字体颜色}else{this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = ConvertToColor("#FFFFFF");//#FFFFFF 白色}}
}// 通用方法:支持 "#RGB", "#RRGGBB", "#ARGB", "#AARRGGBB", "Red" 等格式 public static System.Drawing.Color ConvertToColor(string colorCode){if (string.IsNullOrEmpty(colorCode))return System.Drawing.Color.Empty;// 处理 HTML 格式if (colorCode.StartsWith("#")){try{return System.Drawing.ColorTranslator.FromHtml(colorCode);}catch{// 忽略异常,继续尝试其他格式}}// 处理 RGB 整数格式(如 "255,0,0")if (colorCode.Contains(",")){var parts = colorCode.Split(',');if (parts.Length == 3){return System.Drawing.Color.FromArgb(int.Parse(parts[0]),int.Parse(parts[1]),int.Parse(parts[2]));}else if (parts.Length == 4){return System.Drawing.Color.FromArgb(int.Parse(parts[0]),int.Parse(parts[1]),int.Parse(parts[2]),int.Parse(parts[3]));}}// 处理颜色名称或其他格式return System.Drawing.Color.FromName(colorCode);}

核心代码:

var BackgroundColor = cell.Style.Fill.BackgroundColor.LookupColor();//返回单元格背景色


图例:

Excel导入前

Excel导入后

http://www.lryc.cn/news/588052.html

相关文章:

  • 使⽤Pytorch构建⼀个神经⽹络
  • Solid Edge多项目并行,浮动许可如何高效调度?
  • 在项目中集成开源的表单设计器FcDesigner源码
  • mongodb原理及其实现
  • Context Tuning for In-Context Optimization
  • 日语学习-日语知识点小记-构建基础-JLPT-N3阶段(4):语法+单词+復習+发音
  • Nacos 技术研究文档(基于 Nacos 3)
  • Linux:1_Linux下基本指令
  • C++-linux 6.makefile和cmake
  • 多线程--单例模式and工厂模式
  • FreeRTOS之链表操作相关接口
  • QT——文件操作类 QFile和QTextStream
  • 第一次接触自动化监测,需要付费厂家安装服务吗?比人工测量主要区别是啥?
  • 用Python向PDF添加文本:精确插入文本到PDF文档
  • 2024-2025-2 山东大学《毛概》期末(回忆版)
  • 复习笔记 38
  • linux下的消息队列数据收发
  • “国乙黑月光”指的是谁?
  • 动态规划题解——单词拆分【LeetCode】
  • 【字节跳动】数据挖掘面试题0017:推荐算法:双塔模型,怎么把内容精准地推送给用户
  • 设计模式(行为型)-迭代器模式
  • iOS App 安全加固全流程:静态 + 动态混淆对抗逆向攻击实录
  • Linux进程优先级机制深度解析:从Nice值到实时调度
  • 基于MATLAB的LSTM长短期记忆神经网络的时间序列数据预测方法应用
  • .NET ExpandoObject 技术原理解析
  • C#/.NET/.NET Core技术前沿周刊 | 第 46 期(2025年7.7-7.13)
  • 如何用深度学习实现图像风格迁移
  • 面试150 路径总和
  • 电脑升级Experience
  • WPF自定义日历选择控件