Save As DialogueBox is not working in servlet response.setHeader - java

I am exporting data displayed in jqgrid into .excel file by clicking button .
Here is my code for export to excel button click..
$('#excel').click(function(){
var fromdate=$('#fromdate').val();
var todate=$('#todate').val();
if(fromdate && todate)
{
var URL='excel?fromdate='+$('#fromdate').val()+'&todate='+$('#todate').val();
$.ajax({
url:URL,
type:'GET',
success:function(data){
alert('Exported To Excel');
}
});
}
});
Now this button will direct to excel.java page which is servlet.Below is my exceljava page code .Now Asper my need when the user click on export to excel button a openwith and save as dialogue box should popup which gives user ability to give desired name and save to desired positionbut it is not happening with this code.plz point out my mistake ..
excel.java
try {
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=excel.xls");
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("CallBillingSystem");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("calldate");
rowhead.createCell((short) 1).setCellValue("src");
rowhead.createCell((short) 2).setCellValue("dst");
rowhead.createCell((short) 3).setCellValue("dstchannel");
rowhead.createCell((short) 4).setCellValue("lastapp");
rowhead.createCell((short) 5).setCellValue("duration");
rowhead.createCell((short) 6).setCellValue("disposition");
rowhead.createCell((short) 7).setCellValue("amaflags");
rowhead.createCell((short) 8).setCellValue("cdrcost");
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
//strQuery = "SELECT * FROM cdrcost where date(calldate) between '2011-09-01' and '2012-01-01'";
rs = conexiondb.Consulta(strQuery);
int i = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs.getString("calldate"));
row.createCell((short) 1).setCellValue(rs.getString("src"));
row.createCell((short) 2).setCellValue(rs.getString("dst"));
row.createCell((short) 3).setCellValue(rs.getString("dstchannel"));
row.createCell((short) 4).setCellValue(rs.getString("lastapp"));
row.createCell((short) 5).setCellValue(rs.getString("duration"));
row.createCell((short) 6).setCellValue(rs.getString("disposition"));
row.createCell((short) 7).setCellValue(rs.getString("amaflags"));
row.createCell((short) 8).setCellValue(rs.getString("cdrcost"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
hwb.write(response.getOutputStream());
System.out.println("Your excel file has been generated!");
FileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}

Related

Eclipse - POI XSSF generates corrupted Workbook

Whenever I run this code, it creates or updates the existing xlsx spreadsheet and immediately corrupts it. I have tried to leave the file open before continuing but that does not help. This worked prior to our hosting provider forcing us to use an SSH tunnel to reach our MySQL server. Connectivity through SQL tools seems fine. The file is stored on the local machine (OneDrive).
JButton btnRecordCompletions = new JButton("Record Completions");
btnRecordCompletions.setBounds(26, 168, 156, 23);
btnRecordCompletions.setMnemonic(KeyEvent.VK_R);
panelReporting.add(btnRecordCompletions);
btnRecordCompletions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (realm == "Security") {
System.out.println("Realm is " + realm);
DateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date date1 = new java.util.Date();
System.out.println("Date is " + date1);
dateFormat1.format(date1);
String dateof = (new java.text.SimpleDateFormat("yyyy/MM/dd")).format(compdate.getDate());
String mark_complete = "SELECT DISTINCT wpgc.user_id, wpgc.timestamp\r\n"
+ "FROM wp_grassblade_completions as wpgc \r\n" + " INNER JOIN \r\n"
+ "wp_usermeta ON wpgc.user_id = wp_usermeta.user_id\r\n"
+ "WHERE wpgc.user_id NOT IN (SELECT atc_reporting.user_id FROM atc_reporting WHERE course = 'SECURITY') AND wpgc.timestamp BETWEEN (CURRENT_DATE -INTERVAL 30 DAY) AND DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY) AND content_id IN (1575, 642, 1580) \r\n"
+ "GROUP BY wpgc.user_id\r\n" + "order BY wpgc.timestamp, wp_usermeta.user_id";
try {
FileInputStream inputstream = new FileInputStream(
"D://OneDrive//ABSEC//ATC_Reporting//expdata.xlsx");
int index0 = 0;
Workbook workbook = WorkbookFactory.create(inputstream);
XSSFSheet sheet0 = (XSSFSheet) workbook.getSheet("Security_Completions");
if (sheet0 != null) {
index0 = workbook.getSheetIndex(sheet0);
workbook.removeSheetAt(index0);
}
FileOutputStream output = new FileOutputStream(
"D://OneDrive//ABSEC//ATC_Reporting//expdata.xlsx");
workbook.write(output);
output.close();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3307/wp_dashort", "dashort",
"gt9wkk6r1TPnkgrY");
PreparedStatement ps = null;
ps = connection.prepareStatement(mark_complete);
dateof = dateof + " 00:00";
connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
System.out.println("Executing Query");
Sheet sheet = workbook.createSheet("Security_Completions");
org.apache.poi.ss.usermodel.Row rowhead = sheet.createRow((short) 0);
System.out.println("Sheet created");
rowhead.createCell((short) 0).setCellValue("Column 1");
rowhead.createCell((short) 1).setCellValue("Column 2");
System.out.println("Number of records = " + size);
// Running thru the ResultSet
int index = 0;
int r = 0;
rs.next();
while (rs.next()) {
index = index + 1;
Row row = sheet.createRow((short) index);
for (int i = 0; i < 1; ++i) {
String value = rs.getString(1);
row.createCell(i).setCellValue(value);
row.createCell(1).setCellValue(StringUtils.left((rs.getString(2)), 16));
rs.next();
}
++r;
}
FileOutputStream fileOut = new FileOutputStream(
"D://OneDrive//ABSEC//ATC_Reporting//expdata.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
rs.close();
connection.close();

Excel sheet is not opening in server side but it is opening in local

String filepath="";
try {
//String filename=file_name.replace('/','_');
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(file_name);
HSSFRow rowhead = sheet.createRow((short) 0);
filepath=prop.getProperty("file_store_path")+file_name+timeStamp+".xls";
FileOutputStream fileOut = new FileOutputStream(filepath);
/* rowhead.createCell((short) 1).setCellValue("Domain ID");*/
rowhead.createCell((short) 0).setCellValue("Person ID");
rowhead.createCell((short) 1).setCellValue("Domain ID");
rowhead.createCell((short) 2).setCellValue("First Name");
rowhead.createCell((short) 3).setCellValue("Last Name");
rowhead.createCell((short) 4).setCellValue("Email Address");
rowhead.createCell((short) 5).setCellValue("SBU");
int i = 1;
while (rs.next()){
HSSFRow row = sheet.createRow((short) i);
/* row.createCell((short) 0).setCellValue(rs.getString("domain_id"));*/
row.createCell((short) 0).setCellValue(rs.getString("person_id"));
row.createCell((short) 1).setCellValue(rs.getString("domain_id"));
row.createCell((short) 2).setCellValue(rs.getString("first_name") );
row.createCell((short) 3).setCellValue(rs.getString("last_name"));
row.createCell((short) 4).setCellValue(rs.getString("email_address"));
row.createCell((short) 5).setCellValue(rs.getString("business_unit"));
i++;
}
workbook.write(fileOut);
fileOut.close();
System.out.println("XLS done!!");
}
I am having some issue with excel sheet exporting in Server side. The sheet is working fine in local but not working when deploying in Server. I am using XSSF format here (I have also used HSSF but getting different issue with that). I have attached the error message here.
How can I solve this issue?
The error I am getting is
java.lang.IndexOutOfBoundsException
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(Unknown Source)
at com.controllers.ActiveUserReport.getDownloaded(ActiveUserReport.java:308)
at com.controllers.ActiveUserReport.doGet(ActiveUserReport.java:113)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)

Java to excel not writing to multiple sheets

I am using Apache POI and Java to take an SQL query and format the data and put it into two separate sheets. The first sheet works fine but it never loads data into the second sheet. I've tried just using the code for the second sheet and it works as long as the first sheets code is commented out. This leads me to believe it is caused by my poor java code.
Code is below
public static void createSheet1(ResultSet rs3) throws SQLException, FileNotFoundException {
Desktop dt = Desktop.getDesktop();
//CREATE WORKBOOK
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Run Tickets");
int i=0;
while (rs3.next()){
if (i <= 0){
XSSFRow rowhead = sheet.createRow((short)0);
XSSFCellStyle style = workbook.createCellStyle();
XSSFFont defaultFont = workbook.createFont();
defaultFont.setBold(true);
defaultFont.setFontHeight(13);
style.setFont(defaultFont);
rowhead.createCell((short) 0).setCellValue("ROUTE_NAME");
rowhead.createCell((short) 1).setCellValue("STOP_NAME");
rowhead.createCell((short) 2).setCellValue("EQUIP_NAME");
rowhead.createCell((short) 3).setCellValue("DESTINATION");
rowhead.createCell((short) 4).setCellValue("PURCHASER");
rowhead.createCell((short) 5).setCellValue("Ticket DT");
rowhead.createCell((short) 6).setCellValue("Ticket #");
rowhead.createCell((short) 7).setCellValue("EQUIP_TYPE");
rowhead.createCell((short) 8).setCellValue("OPEN_FEET");
rowhead.createCell((short) 9).setCellValue("OPEN_INCH");
rowhead.createCell((short) 10).setCellValue("OPEN_TMP");
rowhead.createCell((short) 11).setCellValue("CLOSE_FEET");
rowhead.createCell((short) 12).setCellValue("CLOSE_INCH");
rowhead.createCell((short) 13).setCellValue("CLOSE_TMP");
rowhead.createCell((short) 14).setCellValue("OBSV_GRAV");
rowhead.createCell((short) 15).setCellValue("OBSV_TMP");
rowhead.createCell((short) 16).setCellValue("BSW");
rowhead.createCell((short) 17).setCellValue("CLOSE_DT");
rowhead.createCell((short) 18).setCellValue("OPEN_VOLUME");
rowhead.createCell((short) 19).setCellValue("CLOSE_VOLUME");
rowhead.createCell((short) 20).setCellValue("GROSS_VOLUME");
rowhead.createCell((short) 21).setCellValue("NET_VOLUME");
rowhead.createCell((short) 22).setCellValue("STATION_NAME");
for(int j =0; j<23;j++){
rowhead.getCell(j).setCellStyle(style);
}
}
else{
XSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs3.getString("ROUTE_NAME"));
row.createCell((short) 1).setCellValue(rs3.getString("STOP_NAME"));
row.createCell((short) 2).setCellValue(rs3.getString("EQUIP_NAME"));
row.createCell((short) 3).setCellValue(rs3.getString("COMMENTS"));
row.createCell((short) 4).setCellValue(rs3.getString("BA_NAME"));
row.createCell((short) 5).setCellValue(rs3.getString("LQVOL_DT"));
row.createCell((short) 6).setCellValue(rs3.getString("LQVOL_TRANS"));
row.createCell((short) 7).setCellValue(rs3.getString("EQUIP_TYPE"));
row.createCell((short) 8).setCellValue(rs3.getInt("OPEN_FEET"));
row.createCell((short) 9).setCellValue(rs3.getInt("OPEN_INCH"));
row.createCell((short) 10).setCellValue(rs3.getInt("OPEN_TMP"));
row.createCell((short) 11).setCellValue(rs3.getInt("CLOSE_FEET"));
row.createCell((short) 12).setCellValue(rs3.getInt("CLOSE_INCH"));
row.createCell((short) 13).setCellValue(rs3.getInt("CLOSE_TMP"));
row.createCell((short) 14).setCellValue(rs3.getInt("OBSV_GRAV"));
row.createCell((short) 15).setCellValue(rs3.getInt("OBSV_TMP"));
row.createCell((short) 16).setCellValue(rs3.getInt("BSW"));
row.createCell((short) 17).setCellValue(rs3.getString("CLOSE_DT"));
row.createCell((short) 18).setCellValue(rs3.getInt("OPEN_VOLUME"));
row.createCell((short) 19).setCellValue(rs3.getInt("CLOSE_VOLUME"));
row.createCell((short) 20).setCellValue(rs3.getInt("GROSS_VOLUME"));
row.createCell((short) 21).setCellValue(rs3.getInt("NET_VOLUME"));
row.createCell((short) 22).setCellValue(rs3.getString("STATION_NAME"));
}
++i;
}
//AUTOSIZE COLUMNS
int j =0;
while(j<23)
{
sheet.autoSizeColumn(j);
j++;
}
createSheet2(rs3,workbook, dt);
outputExcel(workbook, dt);
}
public static XSSFWorkbook createSheet2(ResultSet rs3, XSSFWorkbook workbook, Desktop dt2) throws SQLException, FileNotFoundException {
//CREATES SECOND SHEET "ALLOCATION"
XSSFSheet sheet2 = workbook.createSheet("Allocation");
int rowcnt = 0;
while(rs3.next()){
if(rowcnt == 0){
XSSFRow rowhead2 = sheet2.createRow((short)0);
XSSFCellStyle style = workbook.createCellStyle();
XSSFFont defaultFont = workbook.createFont();
defaultFont.setBold(true);
defaultFont.setFontHeight(13);
style.setFont(defaultFont);
rowhead2.createCell((short) 0).setCellValue(rs3.getString("STATION_NAME"));
}
rowcnt++;
}
return workbook;
}
public static void outputExcel(XSSFWorkbook workbook, Desktop dt) throws FileNotFoundException {
String yemi = "M:/MonthlyEndClosing.xlsx";
FileOutputStream fileOut = new FileOutputStream(yemi);
try {
workbook.write(fileOut);
fileOut.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
dt.open(new File("M:/MonthlyEndClosing.xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried this in just one method,separate classes and now in two methods with the same results. I appreciate any help you can give.
Your problem is not in POI API using but in your resultSet :
while (rs3.next()){
...
}
//rs3.next() will now be false

Generate excel file using java with different column width

I am doing a java application (J2SE) which I have to generate a excel document (.xls). I did generate the file but I am not able to change the cell width dynamically according to the content which is having the maximum length in the same cell.
Here is my coding...
try {
ResultSet rs = com.dss.system.DBORCL.search("sql statement");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("Site");
rowhead.createCell((short) 1).setCellValue("Part No");
rowhead.createCell((short) 2).setCellValue("Part Description");
int index = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) index);
row.createCell((short) 0).setCellValue(rs.getString("site"));
row.createCell((short) 1).setCellValue(rs.getString("part_no"));
row.createCell((short) 1).setCellValue(rs.getString("description"));
index++;
}
FileOutputStream fileOut = new FileOutputStream("F:\\IFS\\IFSDOC" + txtPLCode.getText() + "[" + currentDate + "-" + usesecond + "]" + ".xls");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
// rs.close();
sheet.autoSizeColumn(0) //for first column
sheet.autoSizeColumn(1) //for second column ... etc
Refer: http://poi.apache.org/spreadsheet/quick-guide.html#Autofit

How can I present a "save file" dialog box for a downloaded file generated using JSP?

HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet(seldate+"|"+seldate2);
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("NUMBER");
rowhead.createCell((short) 1).setCellValue("EMPLOYEE NAME");
rowhead.createCell((short) 2).setCellValue("ITEM QUANTITY");
rowhead.createCell((short) 3).setCellValue("AMOUNT PAID");
//rowhead.createCell((short) 4).setCellValue("");
String sql="something";
ResultSet rs=st.executeQuery(sql);
ResultSetMetaData rsmd=null;
rsmd=rs.getMetaData();
int colcnt=rsmd.getColumnCount();
int i=1;
double grandTotal = 0.0;
while(rs.next())
{
/*----*/
String [] dot=new String[colcnt];
//System.out.println("\n record count for data :"+(++tr));
for (int jk=1;jk<=colcnt;jk++)
{
dot[jk-1]=rs.getString( jk);
}
al.add(dot);
}
String pot []=null;
//HSSFRow row= sheet.createRow((short)i);
for(int mn=0;mn<al.size();mn++)
{
pot=(String[])al.get(mn);
String number=pot[0];
String empname=pot[1];
String itemqty=pot[2];
String emprate=pot[3];
double Rate=Double.parseDouble(emprate);
//out.println(Rate);
int Qty=Integer.parseInt(itemqty);
//out.println(Rate);
totAmt=(Rate)*(Qty);
grandTotal += totAmt;
/*----*/
HSSFRow row= sheet.createRow((short)i);
//row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("BID")));
row.createCell((short) 0).setCellValue(number);
row.createCell((short) 1).setCellValue(empname);
row.createCell((short) 2).setCellValue(itemqty);
row.createCell((short) 3).setCellValue(totAmt);
//row.createCell((short) 4).setCellValue(rs.getString(""));
i++;
//row.createCell((short)3).setCellValue("12345");
}
/*--------------------------*/
HSSFRow row1=sheet.createRow((short)i);
row1.createCell((short) 2).setCellValue("Grand Total");
row1.createCell((short) 3).setCellValue(grandTotal);
/*---------------------------*/
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
//out.println("<script>win=window.open('ExcelMsg.jsp','popup','toolbar=no,status=no,height=300,width=800');</script>");
I have the above code which on executing generates an Excel file stored on the client side, directly to "D" drive in a directory named "report." That I want this to happen by user choice means it must open a file dialog box (save dialog box) and let the user specify where he wants to store the Excel file. How this can be done?
UPDATED CODE
<%
ArrayList al=new ArrayList();
int tr=0;
double totAmt=0.0;
try
{
String seldate=request.getParameter("Sdate");
out.println("\n selected date : :"+seldate);
String seldate2=request.getParameter("Sdate2");
out.println("\n selected date 2 : :"+seldate2);
String str_date=seldate2;
SimpleDateFormat formatter ;
Date date =new Date() ;
Calendar cal2=Calendar.getInstance();
formatter = new SimpleDateFormat("dd-MMM-yyyy");
//date = (Date)formatter.parse(str_date);
cal2.setTime(formatter.parse(str_date));
cal2.add(Calendar.DATE,1);
str_date=formatter.format(cal2.getTime());
out.println("\n Today is " +str_date );
Calendar cal = new GregorianCalendar();
String name=cal.get(Calendar.DATE) +"-" +(cal.get(Calendar.MONTH)+1) + "-"+cal.get(Calendar.YEAR);
/*-------------------------------------------------------------------------------------------------*/
System.out.println("1");
String fileStoreURL="";
String rootpath="D:";
fileStoreURL =rootpath+"/Report";
System.out.println("2");
try {
File f = new File(fileStoreURL);
if (!f.exists())
{
f.mkdirs();
}
}
catch (Exception e)
{
}
System.out.println("3");
String filename=fileStoreURL+"/"+name+".xls" ;
//String filename=name+".xls" ;
System.out.println("4");
/*-------------------------------------------------------------------------------------------------*/
System.out.println("5");
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet(seldate+"|"+seldate2);
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("NUMBER");
rowhead.createCell((short) 1).setCellValue("EMPLOYEE NAME");
rowhead.createCell((short) 2).setCellValue("ITEM QUANTITY");
rowhead.createCell((short) 3).setCellValue("AMOUNT PAID");
//rowhead.createCell((short) 4).setCellValue("");
String sql="something";
ResultSet rs=st.executeQuery(sql);
ResultSetMetaData rsmd=null;
rsmd=rs.getMetaData();
int colcnt=rsmd.getColumnCount();
int i=1;
double grandTotal = 0.0;
while(rs.next())
{
/*----*/
String [] dot=new String[colcnt];
//System.out.println("\n record count for data :"+(++tr));
for (int jk=1;jk<=colcnt;jk++)
{
dot[jk-1]=rs.getString( jk);
}
al.add(dot);
}
String pot []=null;
//HSSFRow row= sheet.createRow((short)i);
for(int mn=0;mn<al.size();mn++)
{
pot=(String[])al.get(mn);
String number=pot[0];
String empname=pot[1];
String itemqty=pot[2];
String emprate=pot[3];
double Rate=Double.parseDouble(emprate);
//out.println(Rate);
int Qty=Integer.parseInt(itemqty);
//out.println(Rate);
totAmt=(Rate)*(Qty);
grandTotal += totAmt;
/*----*/
HSSFRow row= sheet.createRow((short)i);
//row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("BID")));
row.createCell((short) 0).setCellValue(number);
row.createCell((short) 1).setCellValue(empname);
row.createCell((short) 2).setCellValue(itemqty);
row.createCell((short) 3).setCellValue(totAmt);
//row.createCell((short) 4).setCellValue(rs.getString(""));
i++;
//row.createCell((short)3).setCellValue("12345");
}
/*--------------------------*/
HSSFRow row1=sheet.createRow((short)i);
row1.createCell((short) 2).setCellValue("Grand Total");
row1.createCell((short) 3).setCellValue(grandTotal);
/*---------------------------*/
response.setHeader("Content-Length", String.valueOf(filename.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
InputStream input = new BufferedInputStream(new FileInputStream(filename), 1024 * 10);
OutputStream output = new BufferedOutputStream(response.getOutputStream(), 1024 * 10);
byte[] buffer = new byte[1024 * 10];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
ERROR:
java.io.FileNotFoundException: 1-8-2012.xls (The system cannot find the file spe
cified)
java.io.FileNotFoundException: 1-8-2012.xls (The system cannot find the file spe
cified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at org.apache.jsp.sapep.elrservices.processor.ExcelReport2_jsp._jspServi
ce(ExcelReport2_jsp.java:238)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper
.java:377)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:3
13)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java
:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.proce
ss(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:48
9)
at java.lang.Thread.run(Unknown Source)
You need to write the contents of the File to the ServletOutputStream, in addition to that you need to set the content-length and content-disposition of the response,
Here is a simple example:
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
InputStream input = new BufferedInputStream(new FileInputStream(file), 1024 * 10);
OutputStream output = new BufferedOutputStream(response.getOutputStream(), 1024 * 10);
byte[] buffer = new byte[1024 * 10];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
Obviously, you will also need to add the proper exception handling code.
You need to write the contents of the File to the ServletOutputStream, in addition to that you need to set the content-length and content-disposition of the response as shown above answer.
And the coming to the "Save As" You need to do something like below,
Go to your browser Settings and Change the by default download location to Ask where to save each file before downloading.
For Google Chrome,
Go To :- Settings > Show Advances Settings > Downloads. tick the check box Ask where to save each file before downloading.

Categories