java - 如何为使用 JSP 生成的下载文件显示 "save file"对话框?

标签 java javascript 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>");

我有上面的代码,执行时会生成一个存储在客户端的 Excel 文件,直接存储到“D”驱动器上名为“report”的目录中。我希望通过用户选择来实现这一点,这意味着它必须打开一个文件对话框(保存对话框)并让用户指定他想要存储 Excel 文件的位置。如何做到这一点?

更新的代码

<%
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();

错误:

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)

最佳答案

您需要将File的内容写入ServletOutputStream,此外还需要设置响应的content-lengthcontent-disposition

这是一个简单的例子:

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();

显然,您还需要添加适当的异常处理代码。

关于java - 如何为使用 JSP 生成的下载文件显示 "save file"对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758452/

相关文章:

java - Android项目中渲染库错误

java - 通过调用方法打印右对齐三角形

javascript - MongoDB 安全性,我缺少什么?

JavaScript - 使用具有 AJAX 调用的函数的返回参数

java - Java中的并发(FX)

java - 下面方法的空间复杂度是多少?

javascript - 如何在不影响其他元素的情况下在相同纬度/经度的谷歌地图 v3 中添加标记集群?

java - 在 Tomcat 中部署 WAR 时出现严重错误。ContainerBase addChildInternal 错误

java - JSP 返回 HTTP 状态 404 - 未找到 glassfish

java - 将图像从数据库写入jsp