<%# page language="java" contentType="application/vnd.ms-excel"%>
<% response.setHeader("Content-Disposition:","attachment;filename=Sample.xls"); %>
<TABLE>
<TR><TD>2</TD></TR>
<TR><TD>3</TD></TR>
<TR><TD>5</TD></TR>
</TABLE>
How to export the JSP table in XLSX format and how to suppress the following exception
The file you are trying to open, name.ext, is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?
use this
html code
<!DOCTYPE html>
<html>
<head>
<title>tableToExcel Demo</title>
<script>
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
</head>
<body>
<h1>tableToExcel Demo</h1>
<p>Exporting the W3C Example Table</p>
<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
<table id="testTable" summary="Code page support in different versions of MS Windows." rules="groups" frame="hsides" border="2"><caption>CODE-PAGE SUPPORT IN MICROSOFT WINDOWS</caption><colgroup align="center"></colgroup><colgroup align="left"></colgroup><colgroup span="2" align="center"></colgroup><colgroup span="3" align="center"></colgroup><thead valign="top"><tr><th>Code-Page<br>ID</th><th>Name</th><th>ACP</th><th>OEMCP</th><th>Windows<br>NT 3.1</th><th>Windows<br>NT 3.51</th><th>Windows<br>95</th></tr></thead><tbody><tr><td>1200</td><td style="background-color: #00f; color: #fff">Unicode (BMP of ISO/IEC-10646)</td><td></td><td></td><td>X</td><td>X</td><td>*</td></tr><tr><td>1250</td><td style="font-weight: bold">Windows 3.1 Eastern European</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1251</td><td>Windows 3.1 Cyrillic</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1252</td><td>Windows 3.1 US (ANSI)</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1253</td><td>Windows 3.1 Greek</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1254</td><td>Windows 3.1 Turkish</td><td>X</td><td></td><td>X</td><td>X</td><td>X</td></tr><tr><td>1255</td><td>Hebrew</td><td>X</td><td></td><td></td><td></td><td>X</td></tr><tr><td>1256</td><td>Arabic</td><td>X</td><td></td><td></td><td></td><td>X</td></tr><tr><td>1257</td><td>Baltic</td><td>X</td><td></td><td></td><td></td><td>X</td></tr><tr><td>1361</td><td>Korean (Johab)</td><td>X</td><td></td><td></td><td>**</td><td>X</td></tr></tbody><tbody><tr><td>437</td><td>MS-DOS United States</td><td></td><td>X</td><td>X</td><td>X</td><td>X</td></tr><tr><td>708</td><td>Arabic (ASMO 708)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr><tr><td>709</td><td>Arabic (ASMO 449+, BCON V4)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr><tr><td>710</td><td>Arabic (Transparent Arabic)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr><tr><td>720</td><td>Arabic (Transparent ASMO)</td><td></td><td>X</td><td></td><td></td><td>X</td></tr></tbody></table>
</body>
</html>
Use this way:
<%# page import="java.sql.* " %>
<%
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=SimDetails.xls");
Connection con = null;
PreparedStatement ps=null;
ResultSet rs = null;
%>
<%# include file="directconnection.jsp"%>
<%
int simid=0;
int net=0;
String sim="";
String mob="";
String contnum="";
String couridate="";
String sendaddr="";
String networkName="";
String contpe="";
try{
%>
<table>
<tr>
<th width="5%">SNo</th>
<th width="30%;">Network</th>
<th width="30%;">Sim Number</th>
<th width="30%;">Mobile Number</th>
<th width="30%;">Sender Address</th>
<th width="30%;">Contact Person Number</th>
<th width="30%;">Contact Person Name</th>
</tr>
<%
String strSimExportQuery=" SELECT SM_SIM_ID,SM_PROVIDER_ID,SM_SIM_NUMBER,SM_MOBILE_NUMBER,"+
" SM_SENDER_ADDRESS,SM_CONTACT_PERSON_NO,SM_CONTACT_PERSON FROM RS_SIM_MASTER ";
ps=con.prepareStatement(strSimExportQuery);
rs=ps.executeQuery();
while(rs.next()){
simid++;
net=rs.getInt("SM_PROVIDER_ID");
if(net==1){
networkName="Vodafone";
}
sim=rs.getString("SM_SIM_NUMBER");
mob=rs.getString("SM_MOBILE_NUMBER");
sendaddr=rs.getString("SM_SENDER_ADDRESS");
contnum=rs.getString("SM_CONTACT_PERSON_NO");
contpe=rs.getString("SM_CONTACT_PERSON");
%>
<tr>
<td><%=simid%></td>
<td><%=networkName%></td>
<td><%=sim%></td>
<td><%=mob%></td>
<td><%=sendaddr%></td>
<td><%=contnum%></td>
<td><%=contpe%></td>
</tr>
<%}%>
</table>
<%
}catch(Exception e){
out.println(e);
}
finally {
if (rs!= null){ rs.close(); rs=null;}
if(ps!=null){ps.close();ps=null;}
if (con != null) {con.close();con = null;}
}
%>
Related
I am displaying data is a jsp page from "resultset.getString("column_name")" attribute which works fine for my columns.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%# page import="java.sql.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.servlet.ServletOutputStream"%>
<style>
th, td {
padding: 15px;
}
</style>
<%
String id = request.getParameter("name");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "employee";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String iurl1=null;
Blob employee_dp=null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<h2 align="center"><font><strong>Retrieve data from database in jsp</strong></font></h2>
<%
try {
connection = DriverManager.getConnection(connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT * FROM employee_details where ID='" + session.getAttribute("ID") + "'";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<table border="0" class="display" >
<tbody>
<tr>
<td>ID : </td>
<td><%=resultSet.getString("ID")%></td>
</tr>
<tr>
<td>First Name : </td>
<td><%=resultSet.getString("name")%></td>
</tr>
<tr>
<td>Last Name : </td>
<td><%=resultSet.getString("Last_Name")%></td>
</tr>
<tr>
<td>D.O.B. : </td>
<td><%=resultSet.getString("DOB")%></td>
</tr>
<tr>
<td>image : </td>
<td><img alt="Smiley face" src="<%=resultSet.getString("employee_dp") %>" width="500" height="500"/></td>
</tr>
<tr>
<td>Attach address proof </td>
<td> <input type="file" name="txtfile"> </td>
</tr>
</tbody>
</table>
<%}}
catch (Exception e) {
out.println("DB problem");
return;
}
finally {
try {
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
%>
Here is the code for my jsp displaying page.
Driver code to this is a basic login page which redirects to my this jsp page.
I changed the code a bit and tuned it to see if my image is available or not.
I tried by just giving the direct destination under "src" tag , it worked but when i retrieve it through resultSet.getString(column_name) it shows bits of symbols.
If i use .getBlob I get a empty image box
If i use .getString I get a lot of symbols
when i edit table and hitting update , after that if i press view button the contents of table set to null.. please help me out of this..
This is my index.jsp page used to retrieve data from database.
<%# 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">
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "test";
String userid = "root";
String password = "root";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<html>
<body>
<!-- <h1>Retrieve data from database in jsp</h1> -->
<table border="1">
<tr>
<td>id</td>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>update</td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from users";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td contenteditable><%=resultSet.getString("id") %></td>
<td contenteditable><%=resultSet.getString("first_name") %></td>
<td contenteditable><%=resultSet.getString("last_name") %></td>
<td contenteditable><%=resultSet.getString("city_name") %></td>
<td contenteditable><%=resultSet.getString("email") %></td>
<td>update</td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
This my update-process.jsp, this is used to store data back to database.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%! String driverName = "com.mysql.jdbc.Driver";%>
<%!String url = "jdbc:mysql://localhost:3306/test";%>
<%!String user = "root";%>
<%!String psw = "root";%>
<%
String id = request.getParameter("id");
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
if(id != null)
{
Connection con = null;
PreparedStatement ps = null;
int personID = Integer.parseInt(id);
try
{
Class.forName(driverName);
con = DriverManager.getConnection(url,user,psw);
String sql="Update users set id=?,first_name=?,last_name=?,city_name=?,email=? where id="+id;
ps = con.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2, first_name);
ps.setString(3, last_name);
ps.setString(4, city_name);
ps.setString(5, email);
int i = ps.executeUpdate();
if(i > 0)
{
out.print("Updated");
}
else
{
out.print("There is a problem in updating Record.");
}
}
catch(SQLException sql)
{
request.setAttribute("error", sql);
out.println(sql);
}
}
%>
<html>
<body>
<form action="index.jsp">
<input type="submit" value="view">
</form>
</body></html>
First of all, I'll suggest you not to put any java code in jsp. Your code looks very messy and its hard for bug finding and further maintenance. I'm not sure about it but as per below lines of code:
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
you will always get null because you are no where having these input fields. The input fields generate request params or you need to append those requestParams in your access url like you have done for id.
Edit: In your index.jsp change:
<td>update</td>
to
<td><a href='update-process.jsp?id=<%=resultSet.getString("id")%>&first_name=<%=resultSet.getString("first_name")%>&last_name=<%=resultSet.getString("last_name")%>&city_name=<%=resultSet.getString("city_name")%>&email=<%=resultSet.getString("email")%>'>update</a></td>
But its a very bad approach to do this.
Better you write one servlet, have a html form in index.jsp with all the input fields.
I just wanted to upload the image using form in JSP, for that I have written a code, as per below code, it is not inserting in while loop. resultant Image is not getting uploaded in directory.
Can you please help to figure out the problem?
html code
<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="upload_jsp.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
<table border="2">
<tr>
<td align="center"><b>Multipale file Uploade</td>
</tr>
<tr>
<td>
Specify file: <input name="file" type="file" id="file">
<td>
</tr>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit files"/>
</td>
</tr>
</table>
<center>
</form>
</body>
</html>
jsp code
<%# page import="java.util.List"%>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.ResourceBundle" %>
<%# page import="java.io.File"%>
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%# page import="org.apache.commons.fileupload.*"%>
<%
String path= "C:\\Users\\gur29175\\Desktop" ;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
String directory="";
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
} else {
try {
String itemName = item.getName();
File savedFile = new File(path+itemName);
//File savedFile = new File("C:\\Users\\sagar\\Desktop\\JAVA Training\\code(1)\\test\\WebContent\\WEB-INF\\uploads\\"+itemName);
//File savedFile = new File(config.getServletContext ().getRealPath("/")+"uploadedFiles/"+itemName);
item.write(savedFile);
//out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath
//("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+path+
("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
This is the line of code that might be problematic, as item.getName() will return the full path where the source file is located. This might result to a malformed file path.
Try replacing:
String itemName = item.getName();
with:
String itemName = FilenameUtils.getName(item.getName());
Make sure FilenameUtils is imported:
<%# page import="org.apache.commons.io.FilenameUtils" %>
and you have commons-io.jar in your Web app libraries.
I am passing the full filename as advised on different questions yet I'm still receiving this error:
`include` requires the 'filename' option.
Here is my app.coffee
db = require('./db')
http = require('http')
fs = require('fs')
ejs = require('ejs')
# bs = require('bootstrap')
db.albums.find({}, {},
(err, data) ->
if err?
console.log("Error: failure to retrieve albums.")
return
else
initiate_server(data)
return
).sort({'play_counts': -1}).limit(20)
initiate_server = (albums) ->
http.createServer(
(req, res) ->
res.writeHead(200, {'Content-Type': 'text/html'})
# res.end(String(data))
fs.readFile('views/index.ejs', 'utf-8',
(err, data) ->
if err?
res.end('error occured')
else
dir_path = __dirname + '/views'
renderedHtml = ejs.render(data,
{
albums: albums,
headerText: 'TempText',
head: '/partials/head.ejs',
header: dir_path + '/partials/header.ejs',
footer: dir_path + '/partials/footer.ejs'
}
)
res.end(renderedHtml)
# res.end(data)
)
return
).listen(8080)
console.log ('Server listening')
return
and here is my index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<% include(head) %>
</head>
<body class="container">
<header>
</header>
<main>
<table class="table table-striped">
<thead>
<tr>
<th> Rank </th>
<th> Album </th>
</tr>
</thead>
<tbody>
<% albums.forEach(function(album, count){ %>
<tr>
<td><%= count %></td>
<td><%= album.album_name %></td>
</tr>
<% }) %>
</tbody>
</table>
</main>
<footer>
</footer>
</body>
</html>
I've tried just passing the relative path too and I'm still getting this error, any suggestions? Thank you.
what iam trying to do is get field parameter and run mysql query to update(decrement) value from field quantity, can any one tell me how to do that?
<form method="post">
<table class="bordered">
<thead>
<tr>
<th>No</th>
<th>Drug Name</th>
<th>Strength</th>
<th>Quantity</th>
<th>Dis Qty</th>
</tr>
</thead>
<% try {
String query="select * from drugs";
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(query);
while(rs.next()) {
%>
<tr>
<td><%=rs.getInt("drugid") %></td>
<td><%=rs.getString("drugname") %></td>
<td><%=rs.getString("strength") %></td>
<td><%=rs.getInt("drugquant") %></td>
<td><INPUT TYPE="TEXT" NAME="getint" SIZE="7">
<INPUT TYPE="SUBMIT" VALUE="Dispense" NAME="B1"></td> </tr>
<%
} %> </table>
<%
rs.close();
stmt.close();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
![enter image description here][1]
%>
</form>
I tryed to use code similar to this but it doesnt work for me :(
<%
String getint = request.getParameter("getint");
String getsize = "";
// check if Update button is clicked
if(request.getParameter("B1") != null) {
// get what user enterd in intbox
getint = request.getParameter("getint");
// DEBUG
PreparedStatement pstmt4;
pstmt4 = conn.prepareStatement("UPDATE drugs SET drugquant=drugquant - "+getint+" WHERE drugid=1");
pstmt4.executeUpdate();
}
%>
you should add and change some following line:
pstmt4 = conn.prepareStatement("UPDATE drugs SET drugquant=?"+"WHERE drugid=?");
INT drugquant = request.getParameter("drugquant");
INT drugid = request.getParameter("drugid");
pstmt4.setString(1, drugquant);
pstmt4.setString(2, drugid);
pstmt4.executeUpdate();
if you had any doubt you should follow this link and give me comment.