如何使使用 c# 制作的自定义 Excel sheet 的外观与从 SharePoint 下载的相似

How to make look and feel of custom Excel sheet made using c# similar to the one downloaded from SharePoint

我制作了一个 excel 下载控制台应用程序,使用 csom 从 SharePoint 下载列表数据。我希望这个 excel 看起来像下面的 SharePoint Excel:

目前我的自定义 excel 如下所示:

任何人都可以帮我设置自定义 excel 的格式代码吗?我需要为任意长度的交替行设置格式。

注意:上面的 SharePoint Excel 是列表所有项目的 SharePoint OOTB 导出到 Excel 功能。

我的回答基于this answer

以下内容应该有效,workSheet 是您的 Excel 工作表:

// define your colors (header, odd rows, even rows)
var HeaderColor = XlRgbColor.rgbAliceBlue;
var EvenRowColor = XlRgbColor.rgbLightBlue;
var OddRowColor = XlRgbColor.rgbWhite;

// get the column/row count
int ColumnCount = _;
int RowCount = _;

// set the header color
var firstHeaderCell = workSheet.Cells[1, 1];
var lastHeaderCell = workSheet.Cells[1, ColumnCount];
workSheet.Range[firstHeaderCell, lastHeaderCell].Interior.Color = HeaderColor;

// loop through all the rows
for(int i=2; i<=RowCount; i++)
{
    var currentColor = i%2 == 1 ? OddRowColor : EvenRowColor;

    var firstRowCell = workSheet.Cells[i, 1];
    var lastRowCell = workSheet.Cells[i, ColumnCount];
    // set row color based on i being even or odd
    workSheet.Range[firstRowCell, lastRowCell].Interior.Color = currentColor;
}

请注意,您可以使用 XlRgbColor enumeration 选择颜色。