Search code examples
excelborderasposenamed-rangesaspose-cells

Why is a subsection of my range failing to add borders (Aspose Cells)?


Based on code from here, I added the following:

string bottomRightRange = string.Format("F{0}", rowsUsed);
var range = locationWorksheet.Cells.CreateRange("A8", bottomRightRange);

//Setting border for each cell in the range
var style = workBook.CreateStyle();
style.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Black);
style.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Black);
style.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Black);
style.SetBorder(BorderType.TopBorder, CellBorderType.Thin, Color.Black);

for (int r = range.FirstRow; r < range.RowCount; r++)
{
    for (int c = range.FirstColumn; c < range.ColumnCount; c++)
    {
        Cell cell = locationWorksheet.Cells[r, c];
        cell.SetStyle(style, new StyleFlag()
        {
            TopBorder = true,
            BottomBorder = true,
            LeftBorder = true,
            RightBorder = true

        });
    }
}

//Setting outline border to range
range.SetOutlineBorder(BorderType.TopBorder, CellBorderType.Thin, Color.Black);
range.SetOutlineBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.Black);
range.SetOutlineBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.Black);
range.SetOutlineBorder(BorderType.RightBorder, CellBorderType.Thin, Color.Black);

That worked well - for the most part - but notice this:

enter image description here

The last seven rows at the end (except for bottom border on the last row, and the right border for all of them) are not borderized. Why not?

NOTE: bottomRightRange equates to "F94" in this case.

Why would a big chunk work right, then a small portion at the end not work as it should?


Solution

  • The problem was (not obvious from the code above) that the sheet has a few preliminary rows used as header information. These have to be taken into account when looping. So this:

    for (int r = range.FirstRow; r < range.RowCount; r++)
    

    ...needs to become this:

    for (int r = range.FirstRow; r < range.RowCount + FUDGE_FACTOR; r++`)
    

    FUDGE_FACTOR is the number of rows used before the "real" data commences.