java从数据库导出.csv文件及中文乱码问题

要输出csv文件,只要改一下头信息就可以,如下设置就可以:
response.setContentType("application/csv;charset=gb18030");
response.setHeader("Content-Disposition","attachment; filename=x.csv");

乱码问题:
一开始我觉的编码设置的应该是正确的(在网上看资料也是这样设置),应该不是编码问题了,搞不明白,后来我把设置头信息的语句放在了最前面,中文乱码问题就解决了!

*这里还使用了中文转拼音的外包(pinyin4j.jar)--只关心导出csv文件的不用管它,主要看绿色字体的代码


我是写在了servlet当中
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("application/csv;charset=gb18030");
   response.setHeader("Content-Disposition","attachment; filename=x.csv");


   PrintWriter out = response.getWriter();//放在第一句是会出现乱码
     String str = request.getParameter("name");
     //out.println(str.charAt(0));
    try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  try{
   java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","accp");
     //out.println(con);
     java.sql.Statement stat = con.createStatement();

     ResultSet rs = stat.executeQuery("desc book");//mysql语法
     while(rs.next()){
      out.print("\""+(String)rs.getObject(1)+"\",");//输出表的列名
     }
     out.print("\n");
    
     rs = stat.executeQuery("select * from book");
     while(rs.next()){
      String name=rs.getString(3);
      char c = name.charAt(0);
      
     String[] t2 = new String[10];
      //宣告輸出的格式
      net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat t3 = new
        HanyuPinyinOutputFormat();
     t3.setCaseType(HanyuPinyinCaseType.UPPERCASE);
     t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
     t3.setVCharType(HanyuPinyinVCharType.WITH_V);

         t2 = PinyinHelper.toHanyuPinyinStringArray(c, t3);
         if(t2[0].charAt(0)==str.toUpperCase().charAt(0)){
          out.print("\""+rs.getInt(1)+"\","); //单元格的内容用""并用","隔开
          out.print("\""+rs.getString(2)+"\",");
          out.print("\""+name+"\",");  
          out.print("\""+rs.getFloat(4)+"\"\n");// \n在excel里也是换行
         }
        
    }
  }catch(SQLException e){
  e.printStackTrace();
  } catch (BadHanyuPinyinOutputFormatCombination e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  out.flush();
  out.close();
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/diquren/archive/2008/11/14/3300141.aspx

你可能感兴趣的:(java,sql,mysql,jdbc,Excel)