JSP code to generate excel sheet of data retrieved in jsp page - java

I want to export data to Excel sheet
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#include file="connection.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String ht = (String)session.getAttribute("ht");
%>
<table border="1">
<%
pst = con.prepareStatement("select * from attendance where ht='"+ht+"'");
res = pst.executeQuery();
if(res.next())
{
String uname = res.getString(2);
%>
<b>Student Name:<%=uname%></b>
<%
String hlt = res.getString(1);
%>
<b>Hallticket:<%=hlt%></b>
<tr><th>CG</th><th>CD</th><th>MPI</th><th>HCI</th><th>WT</th><th>MPI-Lab</th><th>CT=Lab</th><th>WT-Lab</th></tr>
<%
String cg = res.getString(3);
String cd = res.getString(4);
String mpi = res.getString(5);
String hci = res.getString(6);
String wt = res.getString(7);
String mpi_lab = res.getString(8);
String ct_lab = res.getString(9);
String wt_lab = res.getString(10);
%>
<tr>
<td align="center"><%=cg%></td>
<td align="center"><%=cd%></td>
<td align="center"><%=mpi%></td>
<td align="center"><%=hci%></td>
<td align="center"><%=wt%></td>
<td align="center"><%=mpi_lab%></td>
<td align="center"><%=ct_lab%></td>
<td align="center"><%=wt_lab%></td>
</tr>
<br/><br/>
<%
}
%>
</table>
</body>
</html>
I want the data that is retrieved from database and displayed in table should be printed on excel sheet
Please can any one tell me how to do it ... :(
I used mysql databse.

Try using a servlet to do the Excel writing.
You could use it as a JSP:Include in your existing page if you wanted
to.
From the servlet you'll have to do something like this:
ServletOutputStream out = resp.getOutputStream();
resp.setContentType("application/vnd.ms-excel")
/*
* get data
*/
if (data != null) {
for (int i=0; i data.length; i++) {
String dataRow = "";
for (int j = 0; j data[0].length; j++) {
dataRow += data[i][j] + "\t";// add tab delimiter
}
out.println(dataRow);// print data
}
} else {//Bad data...
out.println("No data to report.");
}
out.flush();
Hope it helps you. :)

You must add following lines to your jsp page which you want to export to excel:
response.setContentType("application/xls");
response.setHeader("Content-Disposition", "attachment;filename=File.xls");
Or you must learn about POI
And you must change if(res.next()) with while(res.next())

Related

How to compare excel file table and mysql table and insert data into mysql column wise using jsp?

I am new in JSP and Apache POI library, i have one excel file with data:My Excel Sheet
And i have one mysql table "data" with column name "address" and "name". I am using following code for insertion excel data into mysql table. Data insertion is successfully complete.
<%# page language="java" import="java.sql.*" contentType="text/html charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import ="java.util.Date" %>
<%# page import ="java.io.*" %>
<%# page import ="java.io.FileNotFoundException" %>
<%# page import ="java.io.IOException" %>
<%# page import ="java.util.Iterator" %>
<%# page import ="java.util.ArrayList" %>
<%# page import ="javax.servlet.http.HttpServletRequest"%>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
<%# page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%!
Connection con;
PreparedStatement ps=null;
Statement stmt= null;
public static ArrayList readExcelFile(String fileName)
{
ArrayList cellArrayLisstHolder = new ArrayList();
try{
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreArrayList=new ArrayList();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreArrayList.add(myCell);
}
cellArrayLisstHolder.add(cellStoreArrayList);
}
}catch (Exception e){e.printStackTrace(); }
return cellArrayLisstHolder;
}%>
<%
String file = request.getParameter("file");
String fileName="/home/data.xls";
ArrayList dataHolder=readExcelFile(fileName);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
stmt =con.createStatement();
String query="insert into data(address, name) values(?,?)";
ps=con.prepareStatement(query);
int count=0;
ArrayList cellStoreArrayList=null;
for(int i=1;i<dataHolder.size();i++) {
cellStoreArrayList=(ArrayList)dataHolder.get(i);
ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
count= ps.executeUpdate();
}
if(count>0)
{
%> Following deatils from Excel file have been inserted in student table of database
<table>
<tr>
<th>Address</th>
<th>Name</th>
</tr>
<%
for (int j=1;j < dataHolder.size(); j++) {
cellStoreArrayList=(ArrayList)dataHolder.get(j);%>
<tr>
<td><%=((HSSFCell)cellStoreArrayList.get(0)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(1)).toString() %></td>
</tr>
<%}
}
else
{%>
<center> Details have not been inserted!!!!!!!!!</center>
<% }
}catch(Exception e)
{}%>
</table>
</body>
</html>
Here my excel sheet have only two columns, but in another case my excel sheet have more than two columns. Column quantity in excel sheet and MySQL table is same, but column sequence is not same. Means suppose in excel sheet have four column like: "address", "name", "age", "class", and mysql table also have four column but in another sequence like: "address", "age", "name", "class". In this case data insertion is not done successfully. Means "age" and "name" column data insertion is exchange with each other. So What is solution for check excel sheet column name and mysql table column name, and insert data into particular column. Position of column may vary but data insertion is done true. Please give me some solution for this. Correct my code if i have made some mistake. Thank you in advance.

unable to display all info from the database through jsp

My requirement is to insert artist details and his picture through jsp into oracle database and retrieve back information and picture through another jsp program.
artist table has five columns, four are varchar2 and fifth column is blob type.
I have successfully inserted and successfully able to retrieve but the problem it displays only image. Below is the code. I am stuck. I need help. Please suggest me.
PreparedStatement ps=con.prepareStatement("select * from artist");
ResultSet rs=ps.executeQuery();
while(rs.next()){ %>
<table><tr><th>artist fast name:</th><td><%=rs.getString(1) %></td></tr>
<tr><th>artist middle name:</th><td><%=rs.getString(2) %></td></tr>
<tr><th>artist last name</th><td><%=rs.getString(3) %></td></tr>
<tr><th>artist job</th><td><%=rs.getString(4) %></td></tr>
<tr><th>artist image</th><td><img src="
<%
Blob bl=rs.getBlob(5);
byte[] image=bl.getBytes(1, (int)bl.length());
response.setContentType("image/jpeg");
OutputStream o = response.getOutputStream();
o.write(image);
o.flush();
o.close();
}
%>" height="100" width="100" alt="bye"/> </td></tr>
</table>
<%
con.close();
As of version 6, Java SE provides JAXB by which the bytes may be converted in to base64 string. Here also you may convert the image byte[] into base 64 string and it can be displayed using the <img html tag specifying the src data as base 64 i.e. src="data:image/png;base64,.
Modify your code as follows :
<%
PreparedStatement ps=con.prepareStatement("select * from artist");
ResultSet rs=ps.executeQuery();
while(rs.next()){ %>
<table><tr><th>artist fast name:</th><td><%=rs.getString(1) %></td></tr>
<tr><th>artist middle name:</th><td><%=rs.getString(2) %></td></tr>
<tr><th>artist last name</th><td><%=rs.getString(3) %></td></tr>
<tr><th>artist job</th><td><%=rs.getString(4) %></td></tr>
<tr><th>artist image</th><td>
<%
Blob bl=rs.getBlob(5);
byte[] image=bl.getBytes(1, (int)bl.length());
%>
<img src="data:image/jpeg;base64, <%=javax.xml.bind.DatatypeConverter.printBase64Binary(image)%>
" height="100" width="100" alt="bye"/> </td></tr>
</table>
<%
}
con.close();
%>
Here is another sample jsp page for getting a clear idea :
<%#page import="java.awt.image.BufferedImage"%>
<%#page import="javax.imageio.ImageIO"%>
<%#page import="java.io.*"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
BufferedImage bImage = ImageIO.read(new File("/home/visruth/Desktop/Visruth.jpg"));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray);
%>
<div>
<p>As of v6, Java SE provides JAXB</p>
<img src="data:image/jpg;base64, <%=b64%>" alt="Visruth.jpg not found" />
</div>
</body>
</html>

Table width is too much

Please have a look at the below code
<%--
Document : index
Created on : Feb 7, 2014, 1:03:15 PM
--%>
<%#page import="java.util.Map"%>
<%#page import="java.util.Iterator"%>
<%#page import="analyzer.DataHolder"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><center>Web Site Analizer</center></h1>
<br/>
<form action=http://localhost:8080/WebSiteAnalizer/SiteAnalizer method=post>
Enter the Percentage (0-100): <input type="Text" name="percentage">
<br/><br/><br/>
Enter the Words (Separated from New Line (/n)): <br/>
<textarea name='wordList' value='wordList'></textarea>
<br/><br/>
<input type="submit" value="Submit">
</form>
<%#page import="java.util.List" %>
<%#page import="java.util.ArrayList" %>
<%#page import="java.util.HashMap" %>
<%
List<DataHolder> dataHolder = (ArrayList)request.getAttribute("list");
HashMap hashMap = (HashMap)request.getAttribute("wordMap");
if(hashMap==null)
{
out.println("Hashmap null");
}
if(dataHolder!=null && dataHolder.size()>0)
{
out.println("</br>");
out.println("<table border='1'><th>Primary Key</th><th>Original Hash</th><th>Matching Words</th><th>Non Matching words</th>");
for(int i=0;i<dataHolder.size();i++)
{
DataHolder d = dataHolder.get(i);
int primaryKey = d.getPrimaryKey();
String originalHash = d.getOriginalHash();
ArrayList matchingWords = d.getMatchingWords();
ArrayList unMatchingWords = d.getUnmatchingWords();
StringBuffer matchingWordsStr = new StringBuffer("");
StringBuffer unMatchingWordsStr = new StringBuffer("");
//Populating Strings
for(int m=0;m<matchingWords.size();m++)
{
Iterator iter = hashMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
if(mEntry.getValue().equals(matchingWords.get(m)))
{
//out.println(matchingWords.get(m)+" : "+true);
matchingWordsStr.append(mEntry.getKey());
matchingWordsStr.append(",");
}
}
}
for(int u=0;u<unMatchingWords.size();u++)
{
Iterator iter = hashMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
if(mEntry.getValue().equals(unMatchingWords.get(u)))
{
//out.println(matchingWords.get(m)+" : "+true);
unMatchingWordsStr.append(mEntry.getKey());
unMatchingWordsStr.append(",");
}
}
}
out.println("<tr>");
out.println("<td>");
out.println(String.valueOf(primaryKey));
out.println("</td>");
out.println("<td>");
out.println(originalHash);
out.println("</td>");
out.println("<td>");
out.println(matchingWordsStr);
out.println("</td>");
out.println("<td>");
out.println(unMatchingWordsStr);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
%>
</body>
</html>
This code generates a table, but it is really huge, which means the width is too much to fit to the screen. The reason for that is, the String values this code enters into the columns are very lengthy. May be 5000 to 10000 words and everything in one column is being displayed in one line. For an example, if "Original Hash" is 10000 characters, then the entire thing is displayed in one line. So is there anyway that I can make the length of this make suit for the screen?
Also please note that I am a developer and not a designer. I very rarely work on scripting languages.
use this css to break the really long word-
td{
word-wrap:break-word;
}
You may need to also set the table-layout to fixed see Set the table column width constant regardless of the amount of text in its cells?. Also for performance you probably want to change it from individual printlns to single a println that takes a string of all your html.

passing the value of an array to a method in javascript

I have to create an HTML table in which I will have images to display. further I want to pass this path to the next servlet page. for this I have created a separate method in javascript. Now the problem is this, whenever I click on any image it passes the same path everytime. please give me any solutions for this problem or tell me any alternate of passing the path to next page.
my code is--->
<%#page import = "java.util.*" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link href="Style.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<center>
<h3>${requestScope.payment}</h3>
<jsp:include page="Header.jsp"/>
<jsp:include page="Menu2.jsp"></jsp:include>
<form method="post" action="ProductFeatures" id="myform">
<table border="1" bordercolor="green" bgcolor="yellow" align="center" id="store" >
</table>
</form>
<%
ArrayList<String> l = null;
if(request.getAttribute("list") instanceof ArrayList<?>){
l = (ArrayList<String>)request.getAttribute("list");
}
%>
<script type="text/javascript">
window.onload = function(){
var path = new Array();
var imagepath = new Array();
var table = document.getElementById("store");
var j=0;
var k=0;
var row = null;
<%for(int i=0;i<l.size();i++) {%>
path.push("<%=l.get(i)%>");
<%}%>
for(i=0;i<path.length;i++){
imagepath[i] =path[i].replace ("F:java_projectsApplication4images","F:\\java_projects\\Application4\\images\\");
}
for(i=0;i<path.length;i++){
if(i%4==0){
row = table.insertRow(j);
k=0;
j++;
}
var data = imagepath[i];
var cell = row.insertCell(k);
var image = document.createElement("img");
image.setAttribute("src",imagepath[i]);
image.setAttribute("height","160");
image.setAttribute("width","120");
image.setAttribute("onclick",function(){getDetails(data);});
cell.appendChild(image);
row.appendChild(cell);
k++;
}
};
function getDetails(imagepath){
document.write(imagepath);
if(path.length>10){
var form = document.getElementById("myform");
var input = document.createElement("input");
input.type="hidden";
input.value=imagepath;
input.name="imagepath";
form.appendChild(input);
form.submit();
}
}
</script>
<jsp:include page="Footer.jsp"/>
</center>
</body>
</html>
Here in this code in function getDetails variable imagepath always contains the same value. please somebody tell me wheres the bug in this code. I am not getting it properly.
Change the following line:
image.setAttribute("onclick",function(){getDetails(data);});
into:
image.setAttribute("onclick",(function(d){return function(){getDetails(d);}}(data));
Also, the line:
row.appendChild(cell);
is redondant because the cell was inserted with row.insertCell(k)

Jquery Autocomplete not passing values to java

I've created autocomplete with Jquery UI library and try to get the text box value in java, but not getting the value instead of getting null value. Please help to get value from text box. This is the line String query = (String)request.getParameter("country"); not getting values ?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
input {
font-size: 120%; }
</style>
</head>
<body>
<h3>Feature</h3>
<input type="text" id="country" name="country"/>
<script>
//$("#country").autocomplete("getdata.jsp");
$("#country").autocomplete({
source: "getdata.jsp",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
String query = (String)request.getParameter("country");
System.out.println("query"+query);
try{
String s[]=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("XXXXX");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select name from table1 where name like '"+query+"%'");
List li = new ArrayList();
while(rs.next())
{
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while(it.hasNext())
{
String p = (String)it.next();
str[i] = p;
i++;
}
//jQuery related start
int cnt=1;
for(int j=0;j<str.length;j++)
{
if(str[j].toUpperCase().startsWith(query.toUpperCase()))
{
out.print(str[j]+"\n");
if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
break;
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
%>
it's not a form,so don't get the value use getParameter().
source: "getdata.jsp?country="+$("#country").val(),

Categories