簡體   English   中英

如何使用C#獲取excel的單元格背景顏色?

[英]how to get cell background color of excel using C#?

我想使用 c# 檢索 excel 單元格的背景顏色,但我找不到辦法做到這一點

  1. 我應該使用哪個庫? microsoft.office.tools.excel.workbook.aspx還是microsoft.office.interop.excel 有什么不同?

  2. 我嘗試了以下代碼,但沒有運氣:

     using Excel = Microsoft.Office.Interop.Excel; private void button1_Click(object sender, EventArgs e) { ofd.Filter = "xlsx|*.xlsx|xls|*.xls"; if(ofd.ShowDialog() == DialogResult.OK) { textBox2.Text = ofd.FileName; Excel.Application excel = new Excel.Application(); Excel.Workbook wb = excel.Workbooks.Open(textBox2.Text); Excel.Worksheet ws = wb.Sheets[1]; Excel.Range xlRange = ws.Cells[0, 0]; Debug.WriteLine("===" + xlRange.Interior.Color); } }

有一個名為 EPPlus 的不錯的庫,它使您與 excel 的關系變得更加容易。 你可以在 NuGet 上找到它。
所以使用這個代碼來獲取顏色:

var x = sheet.Cells[rowIndex, colIndex].Style.Fill.BackgroundColor;

這設置顏色:

sheet.Cells[rowIndex, colIndex].Style.Fill.SetCellsColor( Color.Yellow );

最簡單的解決方案:

 private void Get_Colors()
  {
      Excel.Workbook excel = Globals.ThisAddIn.Application.ActiveWorkbook;
      Excel.Worksheet sheet = null;
      Excel.Range ran = sheet.UsedRange;
      for (int x = 1; x <= ran.Rows.Count; x++)
      {
          for (int y = 1; y <= ran.Columns.Count; y++)
          {
              string CellColor = sheet.Cells[x, y].Interior.Color.ToString(); //Here I go double value which is converted to string.
              if (sheet.Cells[x, y].Value != null && (CellColor == Color.Transparent.ToArgb().ToString() || **CellColor == Excel.XlRgbColor.rgbGold.GetHashCode().ToString()**))
              {
                  sheet.Cells[x, y].Interior.Color = Color.Transparent;
              }
          }
      }
  }

這是一個使用closed.xml的答案。 它是開源的,適用於現代 Excel 工作表。

IXLWorkbook wb = new XLWorkbook("C:\File_path_to_excel_file"); // Replace with your file path
IXLWorksheet ws = wb.Worksheet("SheetName") // Put your sheet name here
int backgroundColor = ws.Cell(rowIndex, colIndex).Style.Fill.BackgroundColor.Color.ToArgb(); // Gives the Argb values for the cell's background. Replace rowIndex and colIndex with the index numbers of the cell you want to check

通常,未着色單元格的 Argb 顏色為 16777215。

這很簡單,如下所示:

using Excel = Microsoft.Office.Interop.Excel;
var cellColor  = sheet.Cells[rowIndex, colIndex].Style.Fill.BackgroundColor;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM