out.clearBuffer();
String filename="test.csv";
response.addHeader("Content-Disposition", new String(("attachment; filename=" + filename).getBytes("GBK"), "ISO-8859-1"));
response.setContentType("application/vnd.ms-excel");
// 后面输出你的字符串吧

解决方案 »

  1.   

    谢谢!
    我现在碰到了乱码问题,我用的是UTF-8格式,英文操作系统,当有中文下载到CSV文件的时候,出现乱码
      

  2.   

    解决乱码可以如下:
    <%
      java.io.BufferedInputStream bis=null;
      java.io.BufferedOutputStream  bos=null;
    try{
     String filename=request.getParameter("filename");
                 filename=new String(filename.getBytes("iso8859-1"),"gb2312");
     response.setContentType("application/x-msdownload");
     response.setHeader("Content-disposition","attachment; filename="+new String(filename.getBytes("gb2312"),"iso8859-1"));
     bis =new java.io.BufferedInputStream(new java.io.FileInputStream(config.getServletContext().getRealPath("files/" + filename)));
     bos=new java.io.BufferedOutputStream(response.getOutputStream()); 
     byte[] buff = new byte[2048];
     int bytesRead;
     while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
      bos.write(buff,0,bytesRead);
     }
    }
    catch(Exception e){
     e.printStackTrace();
    }
    finally {
     if (bis != null)bis.close();
     if (bos != null)bos.close();
    }
    %> 
    注意,关键就是setHeader里的filename需要重新编码,格式是ISO-8859-1就OK了
      

  3.   

    to yangzi315,
    我这里只有一个字符串String, 我不需要,也没有文件可以读取
      

  4.   

    response.setContentType("application/text;charset="UTF-8");
    response.setHeader("Content-disposition", "attachment;filename=11.csv");
    DataOutputStream out;
    try{
       out = new DataOutputStream(response.getOutputStream());
       out.write("AAAA".getBytes("UTF-8"));
       out.close();
    }......