java下载 字符串整成的word 文档

来源:互联网 发布:去哪里下载ubuntu 编辑:程序博客网 时间:2024/05/21 09:20
public String downloadCompanyInfo() throws Exception{
        String fName="导入单位信息";
        //用来处理文件名在IE、火狐下载时乱码的现象
        if(request.getHeader("user-agent").indexOf("MSIE") != -1) {    
            fName = java.net.URLEncoder.encode(fName,"utf-8") + ".doc";    
        } else {    
            fName = new String(fName.getBytes("utf-8"),"iso-8859-1") + ".doc";    
        }
        
        //设置输出的格式
         response.reset();
         response.setContentType("application/x-msdownload");
         response.setHeader("Content-Disposition", "attachment; filename=" + fName);
         OutputStream out = null;
        ByteArrayInputStream bais = null;
        try {
        
             String content = StrTable; //就是表格字符串  <table><tr><td>数据</td></tr></table>           这个东西我用的时候是用来做导入excel的时候把错如信息生成一个table字符串输出到word中  当用户点击下载信息的时候,把word下载下来。
             byte b[] = content.getBytes();
             bais = new ByteArrayInputStream(b);
             POIFSFileSystem poifs = new POIFSFileSystem();
             DirectoryEntry directory = poifs.getRoot();
             DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
             out = response.getOutputStream();
             poifs.writeFilesystem(out);
             bais.close();
             response.flushBuffer();
        } catch (Exception e) {
               e.printStackTrace();
        } finally {
            StrTable="";  //把表格清空
                try {
                    if(out != null){
                        out.close();
                    }
                    if(bais != null){
                        bais.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
0 0
原创粉丝点击