1
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 文件,直接存储到名为“report”的目录中的“D”驱动器中。我希望这由用户选择发生意味着它必须打开一个文件对话框(保存对话框)并让用户指定他想要存储 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)
4

2 回答 2

1

您需要将 的内容写入FileServletOutputStream此外还需要设置响应的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();

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

于 2012-08-01T11:59:30.943 回答
0

您需要将文件的内容写入 ServletOutputStream,此外您还需要设置响应的内容长度和内容处置,如上面的答案所示。

来到“另存为”您需要执行以下操作,

转到您的浏览器设置并将默认下载位置更改为在下载前询问每个文件的保存位置。

对于谷歌浏览器,

转到:- 设置 > 显示高级设置 > 下载。勾选复选框下载前询问每个文件的保存位置

于 2017-03-08T06:41:57.730 回答