在Windows应用程序中使用C#在Excel中以不同颜色突出显示数据

4

我正在使用一个Windows应用程序。我需要找出如何在Excel中以不同的颜色和样式突出显示数据。我正在使用C#将数据导出到Excel。

这是我用来将DataTable导出到Excel的代码:

private void btnExportexcel_Click(object sender, EventArgs e)
{
    oxl = new Excel.Application();
    oxl.Visible = true;
    oxl.DisplayAlerts = false;

    wbook = oxl.Workbooks.Add(Missing.Value);

    wsheet = (Excel.Worksheet)wbook.ActiveSheet;
    wsheet.Name = "Customers";

    DataTable dt = clsobj.convert_datagrid_orderlist_to_datatable(dvgorderlist);

    int rowCount = 1;
    foreach (DataRow dr in dt.Rows)
    {
        rowCount += 1;
        for (int i = 1; i < dt.Columns.Count + 1; i++)
        {
            // Add the header the first time through
            if (rowCount == 2)
            {
                wsheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
            }
                wsheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        range = wsheet.get_Range(wsheet.Cells[1, 1],
        wsheet.Cells[rowCount, dt.Columns.Count]);
        range.EntireColumn.AutoFit();
    }

    wsheet = null;
    range = null;
}
2个回答

10
你需要获取单元格或区域的“Interior”对象,并在其上设置颜色。
Range cellRange = (Range)wsheet.Cells[rowCount, i];
cellRange.Interior.Color = 255;

Excel的颜色是一个整数序列,因此您需要计算您想要的颜色的值。您可能会发现以下方法有帮助:

public static int ConvertColour(Color colour)
{
    int r = colour.R;
    int g = colour.G * 256;
    int b = colour.B * 65536;

    return r + g + b;
}

那么你可以这样做:

cellRange.Interior.Color = ConvertColour(Color.Green);

您可以使用`.font`属性来设置文本的样式:

cellRange.Font.Size = "20";
cellRange.Font.Bold = true;

你可以使用类似 ColorItalicUnderline 的其他属性来获取所需的样式。


0

我意识到我晚了十年,但作为Simon自定义的ConvertColour方法的简单替代方案,你也可以使用ColorTranslator.ToOle方法,它也位于System.Drawing命名空间中。

例如,实现对指定范围进行黄色高亮的一行代码是:

range.Interior.Color = ColorTranslator.ToOle(Color.Yellow);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接