Setting Styles & Formula in excel file using Apache POI

Requirement – Setting styles on excel cells

Solutions– You can set FONT,Color, Bold etc.Use cell.setCellStyle(style) method.

Following is code for setting styles

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Style example");
<strong> //Example 1 of setting styles in cell</strong>
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName(HSSFFont.FONT_ARIAL); 
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
 
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Setting text in BOLD and in Arial font");
cell.setCellStyle(style);
 
<strong>  //Example 2 of setting styles in cell</strong>
font = workbook.createFont();
font .setItalic(true);  // setting cell value as italic
font setFontHeightInPoints((short) 12);   //setting font height.
font.setColor(HSSFColor.GREEN.index);  // setting color as green
style = workbook.createCellStyle();
style.setFont(font);
 
row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("Setting text in italic & green");
cell.setCellStyle(style);
 
try {
    FileOutputStream out = new FileOutputStream(new File("C:\\Vinaystyle.xls"));
    workbook.write(out);
    out.close();
    System.out.println("Excel written successfully..");
     
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


You can also set the background color for the rows as well in sheet

  // Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
row.setRowStyle(style);

Setting Formula in Excel –

    Row row= sheet.createRow(1);
    row.createCell(0).setCellValue(100);
    rpw.createCell(1).setCellValue(200);
    row.createCell(2).setCellValue(300);
    row.createCell(3).setCellFormula("SUM(A1:A4)");
  or 
    cell.setCellFormula("A2*B3*C4")
 

For evaluating formula you can use –

FormulaEvaluator evaluator = 
workbook.getCreationHelper().createFormulaEvaluator(); 

evaluateFormulaCell(Cell cell) will check to see if the supplied cell is a formula cell. If it isn’t, then no changes will be made to it. If it is, then the formula is evaluated. The value for the formula is saved alongside it, to be displayed in excel. The formula remains in the cell, just with a new value.

Happy coding with Vinay in techartifact

Write an excel file in java using Apache POI

Requirment – How to write an excel file in Java

Solutions– Well Apache POI is answer.This API will help you a lot.you have to download and add the POI JAR file to your project’s class path. The Apache POI JAR file can be found http://poi.apache.org/download.html

Following is code –

public static void main(String[] args) throws IOException {
     
    // Directory path where the xls file will be created
    String filePath = "C:/Vinay/ApachePoi/VinayExcel.xls";
    FileOutputStream fout = new FileOutputStream(filePath );
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    HSSFWorkbook workBook = new HSSFWorkbook();
 
    // Create the spreadsheet
    HSSFSheet spreadSheet = workBook.createSheet("vinay_sheet");
     
    // Create the first row
    HSSFRow row = spreadSheet.createRow((short) 0);
     
    // Create the cells and write to the file
    HSSFCell cell;
     
    cell = row.createCell(0);
    cell.setCellValue(new HSSFRichTextString("Vinay"));
    cell = row.createCell(1);
    cell.setCellValue(new HSSFRichTextString("Kumar"));
     
    workBook.write(outputStream);
     
    outputStream.writeTo(fout);
    outputStream.close();
    fout.close();
}

Happy coding with Vinay in techartifact

Read Excel file using Apache POI in Java

Requirment – How to read an excel file in Java

Solutions– Well Apache POI is answer.This API will help you a lot.you have to download and add the POI JAR file to your project’s class path. The Apache POI JAR file can be found http://poi.apache.org/download.html
Please note

HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.

Following snippet we will use

//..
FileInputStream file = new FileInputStream(new File("C:\\VinayTest.xls"));
             
//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);
 
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
 
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
 
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();

Following is code to read from excel file

public static void main(String[] args) throws IOException {
         
        // Location of the source file
        String sourceFilePath = "C:/Vinay/ApachePoi/TestFile.xls";
         
        FileInputStream fileInputStream = null;
         
        // Array List to store the excel sheet data
        List excelData = new ArrayList();
         
        try {
             
            // FileInputStream to read the excel file
            fileInputStream = new FileInputStream(sourceFilePath);
  
            // Create an excel workbook
            HSSFWorkbook excelWorkBook = new HSSFWorkbook(fileInputStream);
             
            // Retrieve the first sheet of the workbook.
            HSSFSheet excelSheet = excelWorkBook.getSheetAt(0);
  
            // Iterate through the sheet rows and cells. 
            // Store the retrieved data in an arrayList
            Iterator rows = excelSheet.rowIterator();
            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();
                Iterator cells = row.cellIterator();
  
                List cellData = new ArrayList();
                while (cells.hasNext()) {
                    HSSFCell cell = (HSSFCell) cells.next();
                    cellData.add(cell);
                }
  
                excelData .add(cellData);
            }
             
            // Print retrieved data to the console
            for (int rowNum = 0; rowNum < excelData.size(); rowNum++) {
                 
                List list = (List) excelData.get(rowNum);
                 
                for (int cellNum = 0; cellNum < list.size(); cellNum++) {
                     
                    HSSFCell cell = (HSSFCell) list.get(cellNum);
                     
                    if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        System.out.print(cell.getRichStringCellValue().getString() + " ");
                    } else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                        System.out.print(cell.getNumericCellValue() + " ");
                    } else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                        System.out.println(cell.getBooleanCellValue() + " ");
                    }
                }
                System.out.println("");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }
}}

Happy coding with Vinay in techartifact