How to add Border to Excel Cells
Java Excel API is an open source java library to read, write and modify Excel spread sheets.
This requires the library jxl-2.6.12.jar to be in classpath.
The following example shows how to set Cell border in Excel Spread sheet.
package com.bethecoder.tutorials.jexcelapi.write;
import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class CellBorderTest {
/**
* @param args
* @throws IOException
* @throws IOException
* @throws WriteException
* @throws BiffException
*/
public static void main ( String [] args ) throws IOException, WriteException {
//Creates a writable workbook with the given file name
WritableWorkbook workbook = Workbook.createWorkbook ( new File ( "C:/JXL/Borders.xls" )) ;
WritableSheet sheet = workbook.createSheet ( "My Sheet" , 0 ) ;
/**
* Add cells with different border styles
*/
addCell ( sheet, Border.LEFT, BorderLineStyle.DOTTED, 1 , 1 , "Left - dotted" ) ;
addCell ( sheet, Border.RIGHT, BorderLineStyle.DASHED, 1 , 3 , "Right - dashed" ) ;
addCell ( sheet, Border.TOP, BorderLineStyle.DOTTED, 1 , 5 , "Top - dotted" ) ;
addCell ( sheet, Border.BOTTOM, BorderLineStyle.DASHED, 1 , 7 , "Bottom - dashed" ) ;
addCell ( sheet, Border.ALL, BorderLineStyle.THIN, 1 , 9 , "All - thin" ) ;
//Writes out the data held in this workbook in Excel format
workbook.write () ;
//Close and free allocated memory
workbook.close () ;
}
private static void addCell ( WritableSheet sheet,
Border border,
BorderLineStyle borderLineStyle,
int col, int row, String desc ) throws WriteException {
WritableCellFormat cellFormat = new WritableCellFormat () ;
cellFormat.setBorder ( border, borderLineStyle ) ;
Label label = new Label ( col, row, desc, cellFormat ) ;
sheet.addCell ( label ) ;
}
}
It gives the following output,