C# Excel 更改字符颜色

问题描述 投票:0回答:1

我想将Excel文件中的所有红色字符更改为蓝色字符,然后保存。

我一直在尝试,但方法好像不对,没有成功..

请指教。

color = xlRange.Cells[i, j].Characters[k,1].Font.Color;
if(color == Color.Red)
{
     xlRange.Cells[i, j].Characters[k, 1].Font.Color = Color.Blue;
}

我只想获取每个字符的颜色,更改它,然后保存它,但无论我做什么,都不起作用。

谢谢你。

我在下面附上了更多代码。

打开 Excel 后,我尝试读取颜色。

但是,它的行为并不如预期。

请指教..

//Create COM Objects. Create a COM object for everything that is referenced
Excel.Application xlApp = new Excel.Application();

int nSheetNo = 3;

Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@SelectedFilePath);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[nSheetNo];
Excel.Range xlRange = xlWorksheet.UsedRange;

int rowCount = 10;// xlRange.Rows.Count;
int colCount = 10;// xlRange.Columns.Count;

double color;

for (int i = 1; i <= rowCount; i++)
{
    for (int j = 1; j <= colCount; j++)
    {
        if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
        {
            strSentence = xlRange.Cells[i, j].Characters;
            if (strSentence is not null)
            {
                LenSentence = strSentence.Count;

                for (int k = 0; k < strSentence.Count; k++)
                {
                    color = xlRange.Cells[i, j].Characters[k,1].Font.Color;
                    if(color == Color.Red)
                    {
                        xlRange.Cells[i, j].Characters[k, 1].Font.Color = Color.Blue;
                    }
                }

            }


        }
    }
}
c# winforms mfc winforms-interop
1个回答
0
投票

代码的主要问题是颜色值转换。

希望下面的代码对您有帮助

        Excel.Application xlApp = new Excel.Application();
        xlApp.Visible = false;
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@SelectedFilePath);
        Excel._Worksheet xlWorksheet = xlWorkbook.ActiveSheet;
        Excel.Range xlRange = xlWorksheet.UsedRange;

        for (int i = 1; i <= xlRange.Rows.Count; i++)
        {
            for (int j = 1; j <= xlRange.Columns.Count; j++)
            {
                if ((xlRange.Cells[i, j] != null) && (xlRange.Cells[i, j].Value2 != null))
                {
                    if (xlRange.Cells[i, j].Characters != null)
                    {
                        for (int k = 1; k <= xlRange.Cells[i, j].Characters.Count; k++)
                        {
                            int color = Convert.ToInt32(xlRange.Cells[i, j].Characters(k, 1).Font.Color);

                            if (ColorTranslator.FromOle(color) == Color.Red)
                                xlRange.Cells[i, j].Characters(k, 1).Font.Color = ColorTranslator.ToOle(Color.Blue);
                        }
                    }
                }
            }
        }

        xlWorkbook.Save();
        xlApp.Visible = true;
© www.soinside.com 2019 - 2024. All rights reserved.