JSP generating Excel spreadsheet (XLS) to download

后端 未结 6 1659
感动是毒
感动是毒 2020-11-27 07:01

I have this application I\'m developing in JSP and I wish to export some data from the database in XLS (MS Excel format).

Is it possible under tomcat to just write a

6条回答
  •  轮回少年
    2020-11-27 07:30

      try {
                String absoluteDiskPath =  test.xls";
                File f = new File(absoluteDiskPath);
                response.setContentType("application/xlsx");
                response.setHeader("Content-Disposition", "attachment; filename=" + absoluteDiskPath);
                String name = f.getName().substring(f.getName().lastIndexOf("/") + 1, f.getName().length());
                InputStream in = new FileInputStream(f);
                out.clear(); //clear outputStream prevent illegalStateException write binary data to outputStream
                ServletOutputStream outs = response.getOutputStream();
                int bit = 256;
                int i = 0;
                try {
                    while ((bit) >= 0) {
                        bit = in.read();
                        outs.write(bit);
                    }
                    outs.flush();
                    outs.close();
                    in.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                } finally {
                    try {
                        if(outs != null)
                            outs.close(); 
                        if(in != null)
                            in.close(); 
                    }catch (Exception ioe2) {
                        ioe2.printStackTrace(); 
                    }
                }
        } catch (Exception ex) {
            ex.printStackTrace();
    
        }
    

提交回复
热议问题