java web匯出csv檔案中文亂碼問題解決。

來源:互聯網
上載者:User
要輸出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();
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.