FileOutputStream已生成但无法下载

时间:2013-06-06 17:38:21

标签: java

我使用此代码生成了一个Excel文件:

try {
   FileOutputStream out = new FileOutputStream(new File("D:\\new1.xls"));
   workbook.write(out);
   out.close();
   System.out.println("Excel written successfully..");
}

那么在写完这个文件后如何下载呢?

UPDATE1:

我没有使用servlet。我正在使用struts2和这个类来生成带有poi.jar的Excel文件。

public class ExportToExcel{

    public void execToexcel() {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Sample sheet");

        Map<String, Object[]> data = new HashMap<String, Object[]>();
        data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
        ...
        }
        }

        try {
            FileOutputStream out = 
                    new FileOutputStream(new File("D:\\new1.xls"));
            workbook.write(out);
            DownloadManager.downloadFile("out");
            //out.flush();
            // Runtime.getRuntime().exec("new1.xls"); 
            out.close();
            System.out.println("Excel written successfully..");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想从网页下载这个文件,也许你可以使用这种方法。

public void donwloadFile(){

    try{
        ByteArrayOutputStream b= // put here the ByteArray of the content of your file
        if(b!=null){
            FacesContext facesContext=FacesContext.getCurrentInstance();
            HttpServletResponse response=(HttpServletResponse)facesContext.getExternalContext().getResponse();

            response.reset();
            response.setContentType("application/xls");
            response.setHeader("Content-disposition","attachment; filename=\""nameFile.xls\"");

            BufferedOutputStream output=null;
            output=new BufferedOutputStream(response.getOutputStream());

            output.write(b.toByteArray());
            output.close();

            // Inform JSF to not take the response in hands.
            facesContext.responseComplete();
        }
    }
    catch(IOException e){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}