Hi Friend,
Try the following code:
1)excel.jsp:
<%@page import=" java.io.*"%>
<%@page import=" java.sql.*"%>
<%@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"%>
<%
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection("jdbc:
mysql://localhost:3306/test","root";, "root");
PreparedStatement psmnt = null;
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery("Select * from student");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("Roll No");
rowhead.createCell((short) 1).setCellValue("Name");
rowhead.createCell((short) 2).setCellValue("Marks");
rowhead.createCell((short) 3).setCellValue("Grade");
int index=1;
while(rs.next()){
HSSFRow row = sheet.createRow((short)index);
row.createCell((short)0).setCellValue(rs.getInt(1));
row.createCell((short)1).setCellValue(rs.getString(2));
row.createCell((short)2).setCellValue(rs.getInt(3));
row.createCell((short)3).setCellValue(rs.getString(4));
index++;
}
FileOutputStream fileOut = new FileOutputStream("c:\\excelFile.xls");
wb.write(fileOut);
fileOut.close();
out.println("Data is saved in excel file.");
rs.close();
connection.close();
}
catch(Exception e){}
%>
2)readExcel.jsp:
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%@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"%>
<form action="updateExcel.jsp">
<%
short a=0;
short b=1;
short c=2;
short d=3;
String filename ="C:/excelFile.xls";
if (filename != null && !filename.equals("")) {
try{
FileInputStream fs =new FileInputStream(filename);
HSSFWorkbook wb = new HSSFWorkbook(fs);
for (int k = 0; k < wb.getNumberOfSheets(); k++){
HSSFSheet sheet = wb.getSheetAt(k);
int rows = sheet.getPhysicalNumberOfRows();
for (int r = 1; r < rows; r++){
HSSFRow row = sheet.getRow(r);
if (row != null) {
int cells = row.getPhysicalNumberOfCells();
%><br><%
HSSFCell cell1 = row.getCell(a);
if (cell1 != null){
String value = null;
switch (cell1.getCellType()){
case HSSFCell.CELL_TYPE_FORMULA :
value = "FORMULA ";
break;
case HSSFCell.CELL_TYPE_NUMERIC :
value = ""+cell1.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_STRING :
value = cell1.getStringCellValue();
break;
default :
}
%>
<input type="text" name="roll" value="<%=value%>">
<%
}