0

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

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

那么这个文件写好后怎么下载呢?

更新1:

我没有使用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();
        }
    }
}
4

1 回答 1

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();
    }
}
于 2013-06-06T17:55:31.250 回答