0

我想从 Excel 文件中读取第一行并将 DataGridView 作为列标题应用。在该操作期间,我遇到了正确读取前景色和背景色的问题。

查看侧

for (var i = 0; i < this.dataGridView1.Columns.Count; ++i)
{
  this.dataGridView1.Columns[i].HeaderCell.Style = controller.getHeadingStyle(i);
  this.dataGridView1.Columns[i].HeaderCell.Value = controller.getHeadingValue(i);
}

控制器端

internal DataGridViewCellStyle getHeadingStyle(int i)
{
  var DGVCellStyle = new DataGridViewCellStyle();
  var excelStyle = excel.getStyleAt(1, i + 1);
  DGVCellStyle.ForeColor = System.Drawing.ColorTranslator.FromOle(Int32.Parse(excelStyle.Font.Color.ToString()));
  view.Log(i + " excelStyle.Font.Color: " + excelStyle.Font.Color);
  DGVCellStyle.BackColor = System.Drawing.ColorTranslator.FromOle(Int32.Parse(excelStyle.Interior.Color.ToString()));
  view.Log(i + " excelStyle.Interior.Color: " + excelStyle.Interior.Color);

  view.Log(i + " DGVCellStyle.ForeColor: " + DGVCellStyle.ForeColor);
  view.Log(i + " DGVCellStyle.BackColor: " + DGVCellStyle.BackColor);
  return DGVCellStyle;
}

internal string getHeadingValue(int i)
{
  return excel.getValueAt(1, i + 1);
}

Excel 对象端

internal Microsoft.Office.Interop.Excel.Style getStyleAt(int row, int col)
{
  return excelRange.Cells[row, col].Style;
}

public string getValueAt(int row, int col)
{
  var val = excelRange.Cells[row, col].Value;
  if (val == null)
  {
    val = "";
  }
  return val.ToString().Trim();
}

日志输出

[09/08/2013 11:24:42]: 0 excelStyle.Font.Color: 0
[09/08/2013 11:24:42]: 0 excelStyle.Interior.Color: 16777215
[09/08/2013 11:24:42]: 0 DGVCellStyle.ForeColor: Color [Black]
[09/08/2013 11:24:42]: 0 DGVCellStyle.BackColor: Color [White]
[09/08/2013 11:24:42]: 1 excelStyle.Font.Color: 0
[09/08/2013 11:24:42]: 1 excelStyle.Interior.Color: 16777215
[09/08/2013 11:24:42]: 1 DGVCellStyle.ForeColor: Color [Black]
[09/08/2013 11:24:42]: 1 DGVCellStyle.BackColor: Color [White]
[09/08/2013 11:24:42]: 2 excelStyle.Font.Color: 0
[09/08/2013 11:24:42]: 2 excelStyle.Interior.Color: 16777215
[09/08/2013 11:24:42]: 2 DGVCellStyle.ForeColor: Color [Black]
[09/08/2013 11:24:42]: 2 DGVCellStyle.BackColor: Color [White]
[09/08/2013 11:24:42]: 3 excelStyle.Font.Color: 0
[09/08/2013 11:24:42]: 3 excelStyle.Interior.Color: 16777215
[09/08/2013 11:24:42]: 3 DGVCellStyle.ForeColor: Color [Black]
[09/08/2013 11:24:42]: 3 DGVCellStyle.BackColor: Color [White]
(etc)

问题

  • 看起来所有单元格都是白底黑字,事实并非如此
  • 同时读取值保证我读取正确的 Excel 单元格
4

1 回答 1

1

我认为您必须直接从单元格范围中获取颜色,而不是从关联的样式中获取颜色:

internal int getInteriorColorAt(int row, int col)
{
  return ((Excel.Range)excelRange.Cells[row, col]).Interior.Color;
}

internal int getFontColorAt(int row, int col)
{
  return ((Excel.Range)excelRange.Cells[row, col]).Font.Color;
}
于 2013-08-09T01:19:25.260 回答