当前位置: 首页 > 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.dtcms.com/a/278604.html

相关文章:

  • 深入浅出Kafka Producer源码解析:架构设计与编码艺术
  • 创客匠人:创始人 IP 打造的破局点,藏在 “小而精” 的需求里
  • React源码3:update、fiber.updateQueue对象数据结构和updateContainer()中enqueueUpdate()阶段
  • 分布式系统中设计临时节点授权的自动化安全审计
  • postgreSQL的sql语句
  • 时序预测 | Pytorch实现CNN-LSTM-KAN电力负荷时间序列预测模型
  • 2025 春秋杯夏季个人挑战赛 Web
  • lesson13:Python的datetime模块
  • 登录校验与异常处理(web后端笔记第三期)
  • NAT原理与实验指南:网络地址转换技术解析与实践
  • 中国AI应用“三分天下”:国企成主力、中小企偏订阅、C端仍在观望
  • 使用axios向服务器请求信息并渲染页面
  • TCP心跳机制详解
  • 【Linux系统】进程切换 | 进程调度——O(1)调度队列
  • 如何在服务器上运行一个github项目
  • VMware 虚拟机 Ubuntu 无法主机与虚拟机之间复制粘贴的详细解决方案
  • ZLMediaKit流媒体服务器:不用docker -java源码部署Linux问题处理
  • day20 力扣235. 二叉搜索树的最近公共祖先 力扣701.二叉搜索树中的插入操作 力扣450.删除二叉搜索树中的节点
  • 8:从USB摄像头把声音拿出来--ALSA大佬登场!
  • Bash常见条件语句和循环语句
  • rk3588平台USB 3.0 -OAK深度相机适配方法
  • springboot 好处
  • [Nagios Core] 事件调度 | 检查执行 | 插件与进程
  • JAVA 设计模式 适配器
  • 八、nginx搭建,实现vue跳转nginx跳转gateway
  • Java设计模式(java design patterns)
  • 概率论与数理统计(二)
  • Maven+Spring
  • 在Maven多模块项目中进行跨模块的SpringBoot单元测试
  • 【橘子分布式】Thrift RPC(理论篇)