java导出Excel文件并解决中文乱码

导出Excel如下jsp代码。以jsp实现导出,一般情况下会出现中文的乱码问题,在这里进行一些转码可以达到OK。
JSP文件如下:
<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="com.flow.util.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.*" %>

<%--
       功能:突发流量分析导出EXCEL
       编码:徐彬
       日期: 2009-6-4
--%>
<%
request.setCharacterEncoding("GBK");

String tiaoJian = request.getParameter("tiaoJian");
         //这里是得到的一些查询条件参数。
SysTools sys=new SysTools();// 这是转码封装的类,如最下边

   Connection conn = null;
   Statement stmt = null;
   ResultSet rs = null;


String sql="select one,two,three,four from test_b where three='"+tiaoJian +"'";

String tmp=sys.chgGBKToISO("统计时间\t流量方向\t本次流量\t发生次数\n");

response.setContentType("application/vnd.ms-excel;charset=GBK");

response.setHeader("Content-Disposition","attachment;filename="+new String("详单查询.xls".getBytes("GBK"),"ISO8859_1"));
     
OutputStream output=response.getOutputStream();
   conn = DB.getConnection();
   stmt = conn.createStatement();
   rs = stmt.executeQuery(sql.toString());
   output.write(tmp.getBytes());
   while(rs.next()){
tmp = rs.getString(1)+"\t"+rs.getString(2)+"\t"+sys.chgGBKToISO(rs.getString(3))+"\t"+rs.getString(4)+"\n";
    output.write(tmp.getBytes());
      
             }
    output.flush();
    output.close();
             DB.releaseCursor(conn,stmt,rs);

%>


<%

package com.flow.util;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.flow.config.ReadConfig;

/**
* @author 徐彬
* @time 2009-05-25
* @see 系统工具类
*/
public class SysTools {


  /**
  * @see GBK-ISO
  * @param str
  * @return
  */
  public static String chgGBKToISO(String str) {
try {
  if (str != null && !str.equals("")) {
  str = new String(str.getBytes("GBK"), "iso-8859-1");
}
         } catch (UnsupportedEncodingException e) {
  SysTools.debugOut("字符转换异常:"+e.getMessage(), "no");
}
  return str;
}

%>

你可能感兴趣的:(java,html,sql,jsp,Excel)