项目中用 response.getOutputStream() 导出 excel 却内容不对。我要导出一个 excel 的表头,却给我导出的是那个导出按钮所在页的页面的内容。我将这段代码复制到另一个项目中,就能正确导出 excel 的表头。  
我用  FileOutputStream os = new FileOutputStream("c:\\test.xls");  也能正确导出 excel 的表头,但要求的是用os = response.getOutputStream(); 来写文件。
请教,是哪里的问题?
public ActionForward export (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ List resultList = new ArrayList();
resultList.add(" ");

OutputStream os = null;
try {
os = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}

response.reset();// 清空输出流   
response.setHeader("Content-disposition", "attachment; filename=Result.xls");// 设定输出文件头
response.setContentType("msexcel");// 定义输出类型

exportUser( resultList, os ); 

     return null;
    }     // 导出到 xls  
public static int exportUser( List list, OutputStream os ) {
try {
// FileOutputStream os = new FileOutputStream("c:\\test.xls");   WritableWorkbook wwb = Workbook.createWorkbook( os );  
WritableSheet ws = wwb.createSheet("导出", 0); 

// 设定指定列的宽度
ws.setColumnView(0, 15);
ws.setColumnView(1, 15);
ws.setColumnView(2, 15); // 设定标签颜色
WritableFont wf_merge = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD, false,
UnderlineStyle.SINGLE_ACCOUNTING, Colour.RED);
WritableCellFormat wff_merge = new WritableCellFormat( wf_merge); 
wff_merge.setBackground( Colour.WHITE );  // 设置首行标题栏
Label label10 = new Label(0, 0, "123", wff_merge);
ws.addCell(label10);
Label label20 = new Label(1, 0, "123", wff_merge);
ws.addCell(label20);
Label label30 = new Label(2, 0, "123", wff_merge);
ws.addCell(label30);

wwb.write();
wwb.close();
os.close();
} catch (IOException e) {
return 1;
} catch (Exception e) {
return 1;
}
return 0;
}

解决方案 »

  1.   

    export方法中,response.getOutputStream()这个response里是页面过来的字节流你直接将其传入exportUser方法中后并未进行其他操作,而只有一个关闭os【这里os是export方法中传过来的】的操作,你并没有将xls文件写进os去。所以不能下载所以下载出来的还是你页面的response.getOutputStream()。而直接//FileOutputStream os = new FileOutputStream("c:\\test.xls")能导出表头,是因为你这个时候的os将test.xls加载进去了
      

  2.   

    WritableWorkbook wwb = Workbook.createWorkbook( os );  
    这一句不就是 将xls文件写进os去 吗?  
    为什么我在另一个项目中,同样这么写就能正确导出excel 呢? 
      

  3.   


    你这里的os是上面那个export方法中的response.getOutputStream(),而它是页面过来的流。
      

  4.   


    这句os是页面过来的流。。因为你的response的流是来自页面的。。WritableWorkbook wwb = Workbook.createWorkbook( os );  
    这句os就是上面的os,所以无法写入细心看一下
      

  5.   

    另一个项目有可能response的原因OutputStream os = null;
            try {
                os = response.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            response.reset();// 清空输出流  你把reset()方法,放到获取os之前 看看行不行
      

  6.   

    把reset()方法,放到获取os之前 还是不行   还是输出一个网页,而且是乱码