how to Write a java program which will be extracting the variables and putting them in an excel format?
The given code allow the user to enter some fields and using the POI API, these field values will get inserted into the excel file.
1)Create form.jsp
<html> <body> <form name="userform" method="post" action="excelFile.jsp"> <table> <tr><td>Enter First Name:</td><td><input type="text" name="firstName"></td></tr> <tr><td>Enter Last Name:</td><td><input type="text" name="lastName"></td></tr> <tr><td>Enter User Name:</td><td><input type="text" name="userName"></td></tr> <tr><td>Enter Address:</td><td><input type="text" name="address"></td></tr> <tr><td>Enter Email ID:</td><td><input type="text" name="email"></td></tr> <tr><td>Enter DOB:</td><td><input type="text" name="dob"></td></tr> <tr><td><input type="submit" value="Export to excel"></td></tr> </table> </form> </body> </html>
2)Create excelFile.jsp
<%@page import="java.io.*"%> <%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%> <%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%> <%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%> <%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%> <% String value1=request.getParameter("firstName"); String value2=request.getParameter("lastName"); String value3=request.getParameter("userName"); String value4=request.getParameter("address"); String value5=request.getParameter("email"); String value6=request.getParameter("dob"); try{ HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Excel Sheet"); HSSFRow rowhead = sheet.createRow((short)0); rowhead.createCell((short) 0).setCellValue("First Name"); rowhead.createCell((short) 1).setCellValue("Last Name"); rowhead.createCell((short) 2).setCellValue("User Name"); rowhead.createCell((short) 3).setCellValue("Address"); rowhead.createCell((short) 4).setCellValue("E-mail Id"); rowhead.createCell((short) 5).setCellValue("Date Of Birth"); HSSFRow row = sheet.createRow((short)1); row.createCell((short)0).setCellValue(value1); row.createCell((short)1).setCellValue(value2); row.createCell((short)2).setCellValue(value3); row.createCell((short)3).setCellValue(value4); row.createCell((short)4).setCellValue(value5); row.createCell((short)5).setCellValue(value6); FileOutputStream fileOut = new FileOutputStream("c:\\File.xls"); wb.write(fileOut); fileOut.close(); out.println("Data is saved in excel file."); }catch ( Exception ex ){ } %>
Ads