Add Borders to Cells in Excel in Java

This article demonstrates how to add borders to cells in an Excel file using Spire.XLS for Java.

The following screenshot shows the input Excel file before adding borders:

Add Borders to Cells in Excel in Java

import com.spire.xls.*;
import java.awt.*;

public class AddBorders {
    public static void main(String[] args){
        //Create a workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("Sample-SetBorder.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Get the cell range that you want to apply border style
        CellRange cr = sheet.getCellRange(sheet.getFirstRow(), sheet.getFirstColumn(), sheet.getLastRow(), sheet.getLastColumn());

        //Apply border style 
        cr.getBorders().setLineStyle(LineStyleType.Double);
        cr.getBorders().getByBordersLineType(BordersLineType.DiagonalDown).setLineStyle(LineStyleType.None);
        cr.getBorders().getByBordersLineType(BordersLineType.DiagonalUp).setLineStyle(LineStyleType.None);
        cr.getBorders().setColor(Color.BLUE);

        //Save the resultant file
        workbook.saveToFile("SetBorder.xlsx", ExcelVersion.Version2010);
    }
}

The following screenshot shows the output Excel file after adding borders:

Add Borders to Cells in Excel in Java