Sunday, December 25, 2011

Serialize an Object to a JSON String in Java Using Gson

To serialize a specified object or bean into its equivalent Json representation in Java we can use Google's GSON library. First create a serializable object and set its fields to some values. Next new up a com.google.gson.Gson object. Finally call the Gson objects's toJson() method passing it your serializable object.


import com.google.gson.Gson;

// The following example code demonstrates how to serialize a Bean
// object to a JSON String using the GSON library from Google.

public class Bean2JsonUsingGson {

    public static void main(String[] args) {

        SampleBean sampleBean = new SampleBean(3.14, "xyz", 42);
        Gson gson = new Gson();
        String json = gson.toJson(sampleBean);

        System.out.println(json);
    }

    static class SampleBean {

        private double value1;
        private String value2;
        private int value3;

        // Constructor
        SampleBean(double value1, String value2, int value3) {
            this.value1 = value1;
            this.value2 = value2;
            this.value3 = value3;
        }
    }
}

Here is the output of the example program:
{"value1":3.14,"value2":"xyz","value3":42}

Piece of cake!!!

Tuesday, December 6, 2011

Set Font Style in an Excel File Using Java and POI

To create an Excel file and style a cell's font in Java we can use Apache's POI library. First a HSSFWorkbook object is created and a HSSFSheet object is added. A HSSFRow is added to the sheet, and a HSSFCell is added to the row. To sent the font style of a cell's content, a HSSFFont object is created, customized, and applied to a HSSFCellStyle object which in turn is applied to a cell in the spreadsheet. The following sample code was successfully tested with POI versions 3.6 and 3.7.



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

// The following example code demonstrates how to create an Excel  
// file using the org.apache.poi library and style the font in a cell.

public class StyleExcelFileFont {

    public static void main(String[] args) {

        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet firstSheet = workbook.createSheet("Sheet 1");

        // Write a String in Cell 2B
        HSSFRow row1 = firstSheet.createRow(1);
        HSSFCell cell2B = row1.createCell(1);
        cell2B.setCellValue(new HSSFRichTextString("Sample String"));

        // Style Font in Cell 2B
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle = workbook.createCellStyle();
        HSSFFont hSSFFont = workbook.createFont();
        hSSFFont.setFontName(HSSFFont.FONT_ARIAL);
        hSSFFont.setFontHeightInPoints((short) 16);
        hSSFFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        hSSFFont.setColor(HSSFColor.GREEN.index);
        cellStyle.setFont(hSSFFont);
        cell2B.setCellStyle(cellStyle);

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File("/Temp/Test5.xls"));
            workbook.write(fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


Here is a screenshot of the generated Excel File:


Piece of cake!!!

Monday, December 5, 2011

Set Background Color and Add Border to a Cell in an Excel File Using Java and POI

To create an Excel file and style a cell with a background color and a border in Java we can use Apache's POI library. First a HSSFWorkbook object is created and a HSSFSheet object is added. A HSSFRow is added to the sheet, and a HSSFCell is added to the row. To add a String to the cell, a HSSFRichTextString is used. To add a background color to the cell and add a border, a HSSFCellStyle object is applied to the cell. The following sample code was successfully tested with POI versions 3.6 and 3.7.



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

// The following example code demonstrates how to create an Excel  
// file using the org.apache.poi library and style the cell by setting
// its background color and adding a border.

public class StyleExcelFileCells {

    public static void main(String[] args) {

        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet firstSheet = workbook.createSheet("Sheet 1");

        // Write a String in Cell 2B
        HSSFRow row1 = firstSheet.createRow(1);
        HSSFCell cell2B = row1.createCell(1);
        cell2B.setCellValue(new HSSFRichTextString("Sample String"));

        // Style Cell 2B
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setBorderTop((short) 1); // single line border
        cellStyle.setBorderBottom((short) 1); // single line border
        cell2B.setCellStyle(cellStyle);

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File("/Temp/Test4.xls"));
            workbook.write(fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Here is a screenshot of the generated Excel File:


Piece of cake!!!

Sunday, December 4, 2011

Read Contents of an Excel File using Java and POI

To get the content from an Excel file in Java we can use Apache's POI library. First a file is imported from disk passing a FileInputStream object to a org.apache.poi.hssf.usermodel.HSSFWorkbook object. In this example only the first sheet was parsed. To access the cell content of the entire sheet, each row is iterated followed by iterating over each cell in the row. For each cell, the content is simply read using the getStringCellValue() method from the HSSFCell object. The following sample code was successfully tested with POI versions 3.6 and 3.7.

Here is a screenshot of the test file I used for this example:





import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

// The following example code demonstrates how to parse the contents
// of all cells in the first sheet of an Excel spreadsheet file

public class ReadExcelFile {

    public static void main(String[] args) {

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("/Temp/Test1.xls");

            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);

            HSSFSheet sheet = workbook.getSheetAt(0);

            Iterator rows = sheet.rowIterator();
            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();

                Iterator cells = row.cellIterator();
                while (cells.hasNext()) {
                    HSSFCell cell = (HSSFCell) cells.next();

                    System.out.println(cell.getStringCellValue());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Here is the output of the program:
Hello
There
Piece of cake!!!

Crow Vending Machine - Crows Find Coins for Peanuts