Monday 17 November 2014

How to generate .XLS file in Java using Apache POI

How to generate .XLS file in Java using Apache POI


String contextName = request.getContextPath().substring(1);
HttpSession hs = request.getSession();
String path = hs.getServletContext().getRealPath("/" + contextName);
char pathSep = new File(path).separatorChar;
path = path.substring(0, path.lastIndexOf(pathSep + contextName));
path = path + pathSep;
 //String filename = "c:\\Send\\text.xls";
String filename = path+"text.xls";
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
int width = 30;
sheet.setAutobreaks(true);
sheet.setDefaultColumnWidth(width);
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((int) 0).setCellValue("SR No.");
rowhead.createCell((int) 1).setCellValue("Name");
rowhead.createCell((int) 2).setCellValue("Code");
rowhead.createCell((int) 3).setCellValue("Salary");
rowhead.createCell((int) 4).setCellValue("City");
rowhead.createCell((int) 5).setCellValue("State");
int i = 0,index=0;
for(i=0;i<6;i++) {
            index++;
            HSSFRow row = sheet.createRow((short) index);
            row.createCell((int) 0).setCellValue(index);
            row.createCell((int) 1).setCellValue("Name -- "+index);
            row.createCell((int) 2).setCellValue("12345 -- "+index);
            row.createCell((int) 3).setCellValue("4500"+index);
            row.createCell((int) 4).setCellValue("City -- "+index);
            row.createCell((int) 5).setCellValue("State -- "+index);
}
       
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
String disHeader = "Attachment;Filename=\"Report.xls\"";
response.setHeader("Content-Disposition", disHeader);
File desktopFile = new File(filename);
PrintWriter pw = response.getWriter();
FileInputStream fileInputStream = new FileInputStream(desktopFile);
int j;
//pw.flush();
while ((j = fileInputStream.read()) != -1) {
            pw.write(j);
}
fileInputStream.close();
response.flushBuffer();
pw.flush();

pw.close();

No comments:

Post a Comment