how to store the data in data base
hi,
i read data from excel file to console. i want to store this data in to db. can anyone please help me...here is the code...
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ControllerServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
MultipartRequest multi = new MultipartRequest(req, ".",
5 * 1024 * 1024);
// Show which files we received
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String) files.nextElement();
String filename = multi.getFilesystemName(name);
//String type = multi.getContentType(name);
//File f = multi.getFile(name);
// read workbook file
readWorkbook(filename);
}
} catch (Exception e) {
e.printStackTrace(out);
}
}
private static void readWorkbook(String filename) throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
//System.out.println(cell);
printCellValue(cell);
}
}
}
}
}
private static void printCellValue(HSSFCell c) {
int cellType = c.getCellType();
if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
System.out.println(c.getBooleanCellValue());
} else if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
System.out.println(c.getNumericCellValue());
} else if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
System.out.println(c.getCellFormula());
} else if (cellType == HSSFCell.CELL_TYPE_STRING) {
System.out.println(c.getStringCellValue());
} else if (cellType == HSSFCell.CELL_TYPE_ERROR) {
System.out.println(c.getErrorCellValue());
}
}
}