java导出txt

Java代码   收藏代码
  1.  第一种形式,是以流的开式直接response,适用于数据量不是很大的情况下。  
Java代码   收藏代码
  1. 第二种形式,是先将要下载的文件写到后台的一个文件或者excel 中,然后再进行下载。  
Java代码   收藏代码
  1. 第一种实现:  
Java代码   收藏代码
  1. package com.smartdot.pdm.business.corp.magazine.util;  
  2.   
  3. import java.io.BufferedOutputStream;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Date;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.ServletOutputStream;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.apache.commons.lang.StringUtils;  
  12.   
  13. import com.smartdot.pdm.business.corp.magazine.bean.MagazineBean;  
  14.   
  15. public class MagazineUtils {  
  16.   
  17.     // 输出TXT  
  18.     public static void writeToTxt(HttpServletResponse response, List list) {  
  19.   
  20.         response.setContentType("text/plain");// 一下两行关键的设置  
  21.         response.addHeader("Content-Disposition",  
  22.                 "attachment;filename=期刊出版社.txt");// filename指定默认的名字  
  23.         BufferedOutputStream buff = null;  
  24.         StringBuffer write = new StringBuffer();  
  25.         String tab = "  ";  
  26.         String enter = "\r\n";  
  27.         MagazineBean magazine;  
  28.         ServletOutputStream outSTr = null;  
  29.         try {  
  30.             outSTr = response.getOutputStream();// 建立  
  31.             buff = new BufferedOutputStream(outSTr);  
  32.             for (int i = 0; i < list.size(); i++) {  
  33.                 magazine = (MagazineBean) list.get(i);  
  34.                 write.append("期刊名称:" + tab);  
  35.                 write.append(delNull(magazine.getChineseName()) + enter);  
  36.                 write.append(enter);          
  37.             }  
  38.             buff.write(write.toString().getBytes("UTF-8"));  
  39.             buff.flush();  
  40.             buff.close();  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.         } finally {  
  44.             try {  
  45.                 buff.close();  
  46.                 outSTr.close();  
  47.             } catch (Exception e) {  
  48.                 e.printStackTrace();  
  49.             }  
  50.         }  
  51.     }  
  52.     public static String delNull(Date date) {  
  53.         String returnStr="";  
  54.         if (date!=null) {  
  55.             SimpleDateFormat sf=new SimpleDateFormat("yyyy年MM月");  
  56.             returnStr=sf.format(date);    
  57.         }   
  58.         return returnStr;  
  59.     }  
  60.     public static String delNull(String str) {  
  61.         String returnStr="";  
  62.         if (StringUtils.isNotBlank(str)) {  
  63.             returnStr=str;        
  64.         }   
  65.         return returnStr;  
  66.     }  
  67. }  

 第二种实现:

Java代码   收藏代码
  1. // 输出TXT  
  2.     public static void writeToTxt(HttpServletRequest request, List list) {  
  3.         FileOutputStream outSTr = null;  
  4.         BufferedOutputStream Buff = null;  
  5.         String path = request.getSession().getServletContext().getRealPath(  
  6.                 "upordown/down/model/magazinePub.txt");  
  7.         String tab = "  ";  
  8.         String enter = "\r\n";  
  9.         MagazineBean magazine;  
  10.         StringBuffer write ;  
  11.         try {  
  12.             outSTr = new FileOutputStream(new File(path));  
  13.             Buff = new BufferedOutputStream(outSTr);  
  14.             for (int i = 0; i < list.size(); i++) {  
  15.                 magazine = (MagazineBean) list.get(i);  
  16.                 write = new StringBuffer();  
  17.                 write.append("期刊名称:" + tab);  
  18.                 write.append(delNull(magazine.getTenet()) + enter);  
  19.                 write.append(enter);      
  20.                 Buff.write(write.toString().getBytes("UTF-8"));  
  21.             }         
  22.             Buff.flush();  
  23.             Buff.close();  
  24.         } catch (Exception e) {  
  25.             e.printStackTrace();  
  26.         } finally {  
  27.             try {  
  28.                 Buff.close();  
  29.                 outSTr.close();  
  30.             } catch (Exception e) {  
  31.                 e.printStackTrace();  
  32.             }  
  33.         }  
  34.     }  

 下载的代码:

Java代码   收藏代码
  1. //下载  
  2. public ActionForward downFile(ActionMapping mapping, ActionForm form,  
  3.         HttpServletRequest request, HttpServletResponse response)  
  4.         throws Exception {  
  5.     String name=request.getParameter("filename");  
  6.     // TODO Auto-generated method stub  
  7.     try {  
  8.         String path = request.getSession().getServletContext().getRealPath(  
  9.                 "upordown/down/model/"+name);  
  10.         File file = new File(path);  
  11.         String filename = file.getName();  
  12.   
  13.         // 取得文件的扩展名ext  
  14.         String ext = filename.substring(filename.lastIndexOf(".") + 1)  
  15.                 .toUpperCase();  
  16.   
  17.         InputStream fis = new BufferedInputStream(new FileInputStream(path));  
  18.         byte[] buffer = new byte[fis.available()];  
  19.         fis.read(buffer);  
  20.         fis.close();  
  21.   
  22.         response.reset();  
  23.         response.addHeader("Content-Disposition""attachment;filename="  
  24.                 + new String(filename.getBytes()));  
  25.         response.addHeader("Content-Length""" + file.length()); // 设置返回的文件类型  
  26.         OutputStream toClient = new BufferedOutputStream(response  
  27.                 .getOutputStream()); // 得到向客户端输出二进制数据的对象  
  28.         // 根据扩展名声称客户端浏览器mime类型  
  29.         if (ext.equals("xls"))  
  30.             response.setContentType("application/msexcel");  
  31.         else  
  32.             response.setContentType("application/octet-stream"); // 设置返回的文件类型  
  33.         toClient.write(buffer); // 输出数据  
  34.         toClient.flush();  
  35.         toClient.close();  
  36.     } catch (IOException ex) {  
  37.         ex.printStackTrace();  
  38.         return mapping.findForward("error");  
  39.     }  
  40.     return null;  
  41. }  

  客户端调用

Js代码   收藏代码
  1. //下载txt  
  2. function  downTxt(){  
  3. window.open ('${pageContext.request.contextPath}/business/magazineAction.do?method=downFile&filename=magazinePub.txt''文件下载''height=300, width=400, top='+(screen.availHeight-300)/2+', left='+(screen.availWidth-400)/2+', toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');  
  4. }  
  5.   
  6.   
  7. //导出txt  
  8. function exportTxt(){  
  9.     var queryForm=document.queryForm;  
  10.     var minRow=queryForm.minRow.value;  
  11.     var maxRow=queryForm.maxRow.value;  
  12.     var totalCnt="${totalCnt}";  
  13.     if(StringUtils.isBlank(totalCnt)){  
  14.         totalCnt=0;  
  15.         }  
  16.  if(Validator.Validate(2)){   
  17.          minRow=parseInt(minRow);  
  18.          maxRow=parseInt(maxRow);         
  19.      // if(maxRow-minRow+1>1000){  
  20.      //     alert("每次最多可以导出1000条数据");  
  21.      //     return ;  
  22.      //     }  
  23.             if(maxRow>totalCnt){  
  24.                 alert("结束记录数不能等大于总记录条数:"+totalCnt);  
  25.             return ;  
  26.             }   
  27.             if(maxRow<minRow){  
  28.                     alert("结束记录数不能小于开始记录数");  
  29.                     return ;  
  30.             }  
  31.        
  32.         req.setRequestMethod("post");  
  33.         var url="${pageContext.request.contextPath}/business/magazineAction.do?method=doExportTxt&orderColumn=${orderColumn}&orderType=${orderType}&queryCondition="+encodeURIComponent('${queryCondition}')+"&maxRow="+maxRow+"&minRow="+minRow+"&isDecorator=false";  
  34.         req.setRequestURL(url);  
  35.         req.setAsync(true);  
  36.         req.setMethodOnSuccess(displayMsg);  
  37.         req.setRequestHeader("Content-Type","text/html;charset=gbk");  
  38.         req.send(null);  
  39.     }  
  40.       
  41. }  

猜你喜欢

转载自blog.csdn.net/java_12138/article/details/79012585