首页 > 解决方案 > 更改 Excel 单元格的颜色会引发“'System.__ComObject' 不包含 'Interior' 的定义”

问题描述

当我想更改我的 Excel 工作表的颜色时,我目前正面临着这种情况。使用我的代码,我已经将条目插入到我的 excel 文件中。一些特定的单元格应该收到特殊的颜色。

当我运行我的代码时,我总是得到同样的错误。

分析 Google/Stackoverflow 结果,我没有找到解决方案,尽管对此有一些抱怨。

Workbooks wbs = excel.Workbooks;
Workbook sheet = wbs.Open(fileName);
excel.DisplayAlerts = false;
Worksheet y = sheet.ActiveSheet;
y.Copy(y, Type.Missing);
int index = y.Index;
int addRow = 2;
Worksheet x = (Worksheet)excel.Worksheets[index];
//...
//this line throws the error
x.Cells[addRow++, 1].Interior.Color = System.Drawing.Color.Blue;
//...

我正在使用 Microsoft Office Interop,它非常有用并且完成了它的工作......直到现在。

标签: c#.netoffice-interop

解决方案


您必须使用 XlRgbColor 来实现颜色(对于 Excel 互操作 14.0):

x.Cells[addRow++, 1].Interior.Color = XlRgbColor.xlBlue;  

如果您有旧版本:您必须使用翻译器

x.Cells[addRow++, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Silver

推荐阅读