Friday, March 14, 2014

Writing Excel Using Apache POI

Writing excel is another important thing to do,here we learn how to write xls and xlsx file using apache POI.

In Apache POI also have some problem when we write large excel file....we know later how to overcome this situation.

In below code we combined the write .xls and .xlsx file according to the file extention.Below code is self descriptive so we no need to more now to deep down to the code.



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class WriteExcel {

    public static void main(String args[]) {
        try {


            //Sample data to fill the sheet.
          
            Map<Integer, Object[]> data = new HashMap<>();
            data.put(1, new Object[]{"Emp No.", "Name", "Salary"});
            data.put(2, new Object[]{1d, "Ram", 25000d});
            data.put(3, new Object[]{2d, "Sam", 50000d});
            data.put(4, new Object[]{3d, "Rahim", 70000d});


            //Give the File name with file extention

            File fileToWrite = new File("resources/new.xlsx");
            String fileToWritename = fileToWrite.getName();
            String extension = fileToWritename.substring(fileToWritename.lastIndexOf(".")
                    + 1, fileToWritename.length());
           
            if (extension.equalsIgnoreCase("xls")) {
                Workbook workbook = new HSSFWorkbook();
                Sheet sheet = workbook.createSheet("Sample sheet");
                insertToSheet(data, sheet);
                writeToExcel(workbook, fileToWrite);
            } else if (extension.equalsIgnoreCase("xlsx")) {
                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("Sample sheet");
                insertToSheet(data, sheet);
                writeToExcel(workbook, fileToWrite);
            }

        } catch (Exception e) {
            e.getMessage();
        }

    }

    public static void insertToSheet(Map<Integer, Object[]> data, Sheet sheet) {
        int rownum = 0;
        for (Integer key : data.keySet()) {
            Row row = sheet.createRow(rownum++);
            Object[] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);
                if (obj instanceof Date) {
                    cell.setCellValue((Date) obj);
                } else if (obj instanceof Boolean) {
                    cell.setCellValue((Boolean) obj);
                } else if (obj instanceof String) {
                    cell.setCellValue((String) obj);
                } else if (obj instanceof Double) {
                    cell.setCellValue((Double) obj);
                } else {
                    System.out.println("error");
                }
            }
        }
    }

    public static void writeToExcel(Workbook workbook, File fileToWrite) {
        try {
            FileOutputStream out
                    = new FileOutputStream(fileToWrite);
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully..");
           
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment