我想从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)
问题
答案 0 :(得分:1)
我认为您必须直接从Cell范围获取颜色,而不是从相关的样式中获取颜色:
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;
}