webLogic环境下,导出excel2007打不开问题

之前的项目一直运行到tomcat7环境中,由于客户要求使用webLogic服务器,项目部署到webLogic环境中,遇到很多问题,其中导出报表问题涉及范围比较多,本人花了两天时间一直研究,查资料,终于解决在webLogic环境下,导出excel表格问题。以下是关键性代码:




        // 设置response的Header
        PrintWriter writer = null;
        try
        {
            response.setContentType("octets/stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("gbk"), "iso-8859-1"));
            response.setContentLength(new Long(file.length()).intValue());
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        response.setCharacterEncoding("utf-8");
        InputStream inputStream = null;
        OutputStream os = null;
        try
        {
            try
            {
                inputStream = new FileInputStream(file);
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
                writer = response.getWriter();
                writer.write(JSON.toJSONString("下载文件出错"));
                writer.flush();
                // throw new RoxException("下载文件出错");
            }
            
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            // throw new RoxException("下载文件出错");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            // throw new RoxException("下载文件出错");
        }
        finally
        {
            if (writer != null)
            {
                writer.close();
            }
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (inputStream != null)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    

关键性代码中,其中response.setContentLength(new Long(file.length()).intValue());代码是关键代码,如果不指定下载文件大小,在导出文件,使用excel2007打开,会提示“文件格式错误”,指定文件大小之后,在使用excel2007就可以正常打开了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章