日期:2014-05-18  浏览次数:20715 次

在服务器端生成的EXCEl如何下载到客户端!100分 急!
File       f       =       new       File( "c:\\测试.xls ");      
    FileInputStream       fin       =       new       FileInputStream(f);      
    response.setContentType( "application/vnd.ms-excel;charset=GB2312 ");      
    response.setHeader( "Content-Disposition ",       "attachment;       filename=测试.xls ");      
    OutputStream       output       =       response.getOutputStream();      
    byte[]       buf       =       new       byte[1024];      
    int       r       =       0;      
    while((r       =       fin.read(buf,       0,       buf.length))!=       -1)       {      
                        output.write(buf,       0,       r);      
    }      
    fin.close();      
    output.close();  
这段代码放在jsp中,点击jsp时,jsp中出现乱码,excel也没有下载到客户端

------解决方案--------------------
给你一个源代码,希望给你有用:
<%@ page import= "java.io.* "%>
<%@ page contentType= "text/html;charset=GBK "%>
<%!
public String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i=0;i <s.length();i++) {
char c = s.charAt(i);
if (c > = 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes( "utf-8 ");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append( "% " + Integer.toHexString(k).
toUpperCase());
}
}
}
System.out.println( "sb: "+sb.toString());
return sb.toString();
}
%>
<%
request.setCharacterEncoding( "GBK ");
//文件名
String filename = request.getParameter( "filenme ");
//服务器相关程序下的相对路径,完整路径:export/home/process/web/test/data/images
String dirName=application.getRealPath( "test/data/images ");
java.io.File strFile=null;
String strPath=dirName+System.getProperties().getProperty( "file.separator ")+filename;
System.out.println( "生成图片路径: "+strPath);
try{
strFile=new java.io.File(strPath);
}catch(Exception e){
e.printStackTrace();
}
if (strFile!=null&&strFile.exists()&&strFile.isFile())
{
long filelength = strFile.length();
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(strPath);
//设置输出的格式
response.reset();
response.setContentType( "application/x-msdownload ");
response.setContentLength((int)file