EPPlus:在应用LoadFromCollection后,如何在每个单元格周围分配边框?

27 c# epplus asp.net-mvc-5

在我的导出ActionResult中,我能够将模型加载到我的ExcelPackage中.

我遇到问题的地方是在LoadFromCollection应用后为每个单元格分配边框.虽然AutoFitColumns正确适用,但我应用的边框样式仅适用于Cells["D1"]表,但不适用于表.

BorderAround成功地在整个表格周围放置边框,但我宁愿将边框应用于表格的单元格.有没有办法可以做到这一点?

// Fill worksheet with data to export
var modelCells = worksheet.Cells["D1"];
var border = modelCells.Style.Border.Top.Style = modelCells.Style.Border.Left.Style = modelCells.Style.Border.Right.Style = modelCells.Style.Border.Bottom.Style = ExcelBorderStyle.Medium;                    

modelCells
    .LoadFromCollection(Collection: exportQuery, PrintHeaders: true)
    .AutoFitColumns(); 
Run Code Online (Sandbox Code Playgroud)

小智 47

如果我知道模型的列数,我可以用函数计算行数并执行以下操作:

var modelRows = exportQuery.Count()+1;    
string modelRange = "D1:F" + modelRows.ToString();
var modelTable = worksheet.Cells[modelRange];
Run Code Online (Sandbox Code Playgroud)

或者,有更多的背景.我验证了EPPlus将接受Cells []中的字符串变量,这允许我选择整个表并AutoFitColumns{}正确应用我的边框样式.我必须手动完成输入modelRange变量中的起始列和结束列.

var modelCells = worksheet.Cells["D1"];
var modelRows = exportQuery.Count()+1;    
string modelRange = "D1:F" + modelRows.ToString();
var modelTable = worksheet.Cells[modelRange];

// Assign borders
modelTable.Style.Border.Top.Style = ExcelBorderStyle.Thin;
modelTable.Style.Border.Left.Style = ExcelBorderStyle.Thin;
modelTable.Style.Border.Right.Style = ExcelBorderStyle.Thin;
modelTable.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;


// Fill worksheet with data to export
modelCells.LoadFromCollection(Collection: exportQuery, PrintHeaders: true);
modelTable.AutoFitColumns();
Run Code Online (Sandbox Code Playgroud)

  • 围绕excelrange的边框的快捷方式:`modelTable.Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);` (9认同)