如何更改MS Excel单元格中文本的颜色? [英] How can I change color of text in a cell of MS Excel?
本文介绍了如何更改MS Excel单元格中文本的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Microsoft.Office.Interop.Excel
库.
我有一个值为绿色红色"的单元格.我想要的很简单.我想插入绿色"文本为绿色,插入红色"文本为红色,如下所示:
I have a cell with values "Green Red". What I want is pretty simple. I want to insert "Green" text to be green and "Red" to be red, like that:
我正在使用以下代码在单元格中插入数据:
I am using this code to insert data in cell:
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
for (int startIndex = 0; startIndex < 10; startIndex++)
{
workSheet.Cells[1, (startIndex + 1)] ="Green" + " Red";
}
该怎么做?
我已经尝试了这种方法,但是我不知道什么是[RangeObject]
:
I've tried this approach, but I do not know what [RangeObject]
is:
[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
推荐答案
尝试:
workSheet.Cells[1, (i + 1)].Characters[start_pos, len].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
其中start_pos
和len
是字符串中要应用颜色的部分.
where start_pos
and len
is the part of the string where to apply color.
您的用例示例:
Application excelApp = new Application();
excelApp.Workbooks.Add();
// single worksheet
_Worksheet workSheet = excelApp.ActiveSheet;
string Green = "Green";
string Red = "Red";
for (int start = 0; start < 10; start++)
{
Range ColorMeMine = workSheet.Cells[1, (start + 1)];
ColorMeMine.Value = string.Format("{0} {1}", Green, Red);
ColorMeMine.Characters[0, Green.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
ColorMeMine.Characters[Green.Length + 1, Green.Length + 1 + Red.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
这篇关于如何更改MS Excel单元格中文本的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文