问题描述
- JavaWeb导出Excel,提示格式与文件扩展名不一致
-
下载部分代码如下
我是参考别人的代码,很多地方不懂,希望大牛解答!
<%@ page language="java" contentType = " text/html;charset=utf-8" import="java.util.*,java.io.File,java.io.*,java.net.*,com.model.*,com.controller.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
DownLoad File
<%
request.setCharacterEncoding( "utf-8" );
String targerName = new String(request.getParameter("targerName").getBytes("ISO-8859-1"), "gb2312");
String filepath="C:/Users/HP/Downloads/";
//以下红色部分最主要
String fullPath = filepath + targerName;response.reset();
response.setContentType("application/octet-stream");
response.addHeader( "Content-Disposition", "attachment;filename=" + new String(targerName.getBytes("gb2312"), "ISO8859-1"));OutputStream output = null;
FileInputStream fis = null;try{
File f = new File(fullPath);
output = response.getOutputStream();
fis = new FileInputStream(f);
byte[] b = new byte[(int)f.length()];
int i = 0;
while((i = fis.read(b)) >0){
output.write(b, 0, i);
}
output.flush();
}catch(Exception e){
e.printStackTrace();
}
finally{
if(fis != null){
fis.close();
fis = null;
}
if(output != null){
output.close();
output = null;
out.clear();
out = pageContext.pushBody();
}
}
%>
解决方案
ASP.NET导出Excel,打开Excel文件时提示“您尝试打开文件'XXX.xls'的格式与文件扩展名指定文件不一致”
C# 导出Excel文件 打开Excel文件格式与扩展名指定格式不一致。
解决方案二:
request.setCharacterEncoding( "utf-8" );
String targerName = new String(request.getParameter("targerName").getBytes("ISO-8859-1"), "gb2312");
utf-8和gbk不能同时用哦,要嘛是你写的代码不正确,就是你导出的EXCEL和你导入的编码不匹配
解决方案三:
导出为excel
response.setContentType("application/vnd.ms-excel;charset=utf-8");
还有文件中文名你这么写不对呀
public static String encodeChineseDownloadFileName(
HttpServletRequest request, String pFileName) throws UnsupportedEncodingException {
String filename = null;
String agent = request.getHeader("USER-AGENT");
if (null != agent){
if (-1 != agent.indexOf("Firefox")) {//Firefox
filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+ "?=";
}else if (-1 != agent.indexOf("Chrome")) {//Chrome
filename = new String(pFileName.getBytes(), "ISO8859-1");
} else {//IE7+
filename = java.net.URLEncoder.encode(pFileName, "UTF-8");
filename = StringUtils.replace(filename, "+", "%20");//替换空格
}
} else {
filename = pFileName;
}
return filename;
}
这是方法试用不同浏览器