我正在使用 C# 为 Excel 文件的特定单元格着色。 我正在使用:
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(destPath);
Worksheet ws = wb.Worksheets[1];
ws.get_Range(ws.Cells[row, clmn]).Cells.Interior.Color = 36;
...给单元格着色,但这不起作用。 有人可以帮我吗?
尝试类似的事情
ws.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
Cells[row, clmn] 是一个范围,因此您不需要调用 get_Range() 并且有一个可用于颜色的枚举。
ws.Cells[row, clmn].Interior.Color = XlRgbColor.rgbBlack;
如果想通过颜色索引来设置颜色,需要使用这个方法:
Cells[row, col].Interior.ColorIndex = 36;
您可以为单元格或整列或整行着色。
下面的代码可以帮助你。
xlWorkSheet.get_Range(xlWorkSheet.Cells[2, 2], xlWorkSheet.Cells[2, 4]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
否则
xlWorkSheet.get_Range(xlWorkSheet.Cells[2, 3], xlWorkSheet.Cells[2, 3]).Interior.Color = Excel.XlRgbColor.rgbRed;
这里xlWorksheet是excel Worksheet对象。
get_Range 采用 2 个变量,一个是起始单元格,另一个是结束单元格。
因此,如果您指定两个相同的值,则只有一个单元格被着色。
xlWorkSheet.cells[row, column]用于指定单元格。
System.Drawing.ColorTranslator.ToOle(SystemDrawing.Color.Green)用于定义OLE格式的颜色。
Excel.XlRgbColor.rgbRed是Excel给单元格着色的方法 此方法可以访问大量颜色,可以在此处找到颜色列表
下面的代码是我定义Excel工作表的方式。
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range xlwidthadjust; //used this to adjust width of columns
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
使用此代码,我确信您不会遇到此异常 来自 HRESULT 的异常:0x800A03EC
确保您正在使用:
using Excel = Microsoft.Office.Interop.Excel;
如果您有要更改范围的变量,请使用:
chartRange = xlWorkSheet.get_Range("a5", "a8");
chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
如果您只想更改特定单元格的颜色,请使用:
xlWorkSheet.Cells[row, col].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
...其中“row”是行号,“col”是分配给给定字母列的列号(从 1 开始)。
using System.Drawing;
using Microsoft.Office.Interop.Excel;
然后跟随
ws.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
不要忘记将 System.Drawing.dll 程序集添加到您的引用中。
Exception from HRESULT: 0x800A03EC
解决方案:将
misValue
更改为sheet1
、sheet2
或sheet3
。
xlWorkBook = xlApp.Workbooks.Add("sheet1");
这对我有用。
system.reflaction.missing.value
那是什么,与来自Excel文件默认值的Excel.workbooks.add
无关。
创建 Excel 文件时,默认工作表为sheet1、sheet2 和sheet3。