jsp
<input type="button" class="wd1 btn" value="导出csv" onclick="download();" />
function download(){
window.location.href = '/esf/ModelAction_download.jspx' ; //要么使用a标签,不能使用ajax,否则不会弹出选择框
}
Action
//导出csv文件 TODO
public void download(){
String savePath = getWebRootDir()+"upload/esf/csvfile/";
SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
String datetime = tempDate.format(new java.util.Date());
String filePath = savePath + "/" + datetime + "_模型.csv";
List<String> dataList=new ArrayList<String>();
List<Object> list = _assistAdpater.selectAllByMapParam("T_ESF_MODEL_selectXiaoQuNeed", null); //需要在csv文件显示的数据
for(int i=0 ;i<list.size(); i++){
EsfModel e = (EsfModel) list.get(i);
dataList.add(e.getModelid()+","+e.getModelname()+","+e.getGrade()+","+e.getEvaluatetime()); //字符串拼接,csv文件使用,来区分
}
boolean isSuccess=CSVUtils.exportCsv(new File(filePath), dataList);
if(isSuccess){
downloadCsv(filePath);
}
}
public void downloadCsv(String filePath){
HttpServletResponse response= ServletActionContext.getResponse();
//设置下载弹出框
String csvEncoding = "UTF-8";
response.setCharacterEncoding(csvEncoding);
response.setContentType("text/csv;charset=" + csvEncoding);
response.setHeader("Content-Disposition", "attachment;fileName=model.csv");
try {
InputStream inputStream = new FileInputStream(new File(filePath));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (Exception e) {
}
}
CSVUtils.java
/**
* 导出
*
* @param file csv文件(路径+文件名),csv文件不存在会自动创建
* @param dataList 数据
* @return
*/
public static boolean exportCsv(File file, List<String> dataList){
boolean isSucess=false;
FileOutputStream out=null;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
try {
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out);
bw =new BufferedWriter(osw);
if(dataList!=null && !dataList.isEmpty()){
bw.append("MODELID,MODELNAME,GRADE,EVALUATETIME").append("\r"); //csv文件第一行
for(String data : dataList){
bw.append(data).append("\r");
}
}
isSucess=true;
} catch (Exception e) {
isSucess=false;
}finally{
if(bw!=null){
try {
bw.close();
bw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
osw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSucess;
}