如何使用OfficeOpenXML将Excel格式存储为C#中的变量?

时间:2016-06-13 18:21:35

标签: c# excel

使用OfficeOpenXML包在C#中初学者。我已经想出如何使用以下内容在输出文件上边框/填充/加粗单元格:

worksheet.Cells["B4:E4"].Style.Font.Bold = true;
worksheet.Cells["B4:E4"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
worksheet.Cells["B4:E4"].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; 
worksheet.Cells["B4:E4"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightSkyBlue);

我不想为每个要设置样式的单元格区域调用它,而是如何将此格式包存储到变量中以减少我的行数?此外,如果有人可以告诉我如何合并一个单元格,超级巨额双奖励积分。

提前致谢!

1 个答案:

答案 0 :(得分:0)

使用函数为您完成:

void FormatRange(Excel.Range target)
{
    target.Style.Font.Bold = true;
    target.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
    target.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; 
    target.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightSkyBlue);
}

然后执行以下操作:

List<string> ranges = new List<string> {"A1", "B1", "C1:C5"}; //etc...

foreach(string address in ranges.ToArray())
{
    FormatRange(Excel.Range(worksheet.Cells[address]));
}