JAvaエクスポートtxt


第1の形式は,ストリームのオープンダイレクトresponseであり,データ量がそれほど大きくない場合に適している. 
2つ目の形式は、ダウンロードするファイルをバックグラウンドのファイルまたはexcelに書くことです. を選択してからダウンロードします. 
1つ目の実装:
package com.smartdot.pdm.business.corp.magazine.util;  
  
import java.io.BufferedOutputStream;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.List;  
  
import javax.servlet.ServletOutputStream;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.commons.lang.StringUtils;  
  
import com.smartdot.pdm.business.corp.magazine.bean.MagazineBean;  
  
public class MagazineUtils {  
  
    //   TXT  
    public static void writeToTxt(HttpServletResponse response, List list) {    
        response.setContentType("text/plain");//            
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String timeStamp = sdf.format( new java.util.Date());
        String fileName = "     ";
        response.addHeader("Content-Disposition","attachment;filename="
		+ new String((fileName +"("+ timeStamp + ").txt").getBytes(), "iso-8859-1")); // filename          
        BufferedOutputStream buff = null;  
        StringBuffer write = new StringBuffer();  
        String tab = "  ";  
        String enter = "\r
"; MagazineBean magazine; ServletOutputStream outSTr = null; try { outSTr = response.getOutputStream();// buff = new BufferedOutputStream(outSTr); for (int i = 0; i < list.size(); i++) { magazine = (MagazineBean) list.get(i); write.append(" :" + tab); write.append(delNull(magazine.getChineseName())); write.append(enter); } buff.write(write.toString().getBytes("UTF-8")); buff.flush(); buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { buff.close(); outSTr.close(); } catch (Exception e) { e.printStackTrace(); } } } public static String delNull(Date date) { String returnStr=""; if (date!=null) { SimpleDateFormat sf=new SimpleDateFormat("yyyy MM "); returnStr=sf.format(date); } return returnStr; } public static String delNull(String str) { String returnStr=""; if (StringUtils.isNotBlank(str)) { returnStr=str; } return returnStr; } }

 2つ目の実装:
//   TXT  
    public static void writeToTxt(HttpServletRequest request, List list) {  
        FileOutputStream outSTr = null;  
        BufferedOutputStream Buff = null;  
        String path = request.getSession().getServletContext().getRealPath(  
                "upordown/down/model/magazinePub.txt");  
        String tab = "  ";  
        String enter = "\r
"; MagazineBean magazine; StringBuffer write ; try { outSTr = new FileOutputStream(new File(path)); Buff = new BufferedOutputStream(outSTr); for (int i = 0; i < list.size(); i++) { magazine = (MagazineBean) list.get(i); write = new StringBuffer(); write.append(" :" + tab); write.append(delNull(magazine.getTenet()) + enter); write.append(enter); Buff.write(write.toString().getBytes("UTF-8")); } Buff.flush(); Buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { Buff.close(); outSTr.close(); } catch (Exception e) { e.printStackTrace(); } } }

 ダウンロードされたコード:
//    
public ActionForward downFile(ActionMapping mapping, ActionForm form,  
        HttpServletRequest request, HttpServletResponse response)  
        throws Exception {  
    String name=request.getParameter("filename");  
    // TODO Auto-generated method stub  
    try {  
        String path = request.getSession().getServletContext().getRealPath(  
                "upordown/down/model/"+name);  
        File file = new File(path);  
        String filename = file.getName();  
  
        //         ext  
        String ext = filename.substring(filename.lastIndexOf(".") + 1)  
                .toUpperCase();  
  
        InputStream fis = new BufferedInputStream(new FileInputStream(path));  
        byte[] buffer = new byte[fis.available()];  
        fis.read(buffer);  
        fis.close();  
  
        response.reset();  
        response.addHeader("Content-Disposition", "attachment;filename="  
                + new String(filename.getBytes()));  
        response.addHeader("Content-Length", "" + file.length()); //            
        OutputStream toClient = new BufferedOutputStream(response  
                .getOutputStream()); //                   
        //              mime    
        if (ext.equals("xls"))  
            response.setContentType("application/msexcel");  
        else  
            response.setContentType("application/octet-stream"); //            
        toClient.write(buffer); //       
        toClient.flush();  
        toClient.close();  
    } catch (IOException ex) {  
        ex.printStackTrace();  
        return mapping.findForward("error");  
    }  
    return null;  
}  

クライアントコール
//  txt  
function  downTxt(){  
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');  
}    
//  txt  
function exportTxt(){  
    var queryForm=document.queryForm;  
    var minRow=queryForm.minRow.value;  
    var maxRow=queryForm.maxRow.value;  
    var totalCnt="${totalCnt}";  
    if(StringUtils.isBlank(totalCnt)){  
        totalCnt=0;  
        }  
 if(Validator.Validate(2)){   
         minRow=parseInt(minRow);  
         maxRow=parseInt(maxRow);         
     // if(maxRow-minRow+1>1000){  
     //     alert("        1000   ");  
     //     return ;  
     //     }  
            if(maxRow>totalCnt){  
                alert("               :"+totalCnt);  
            return ;  
            }   
            if(maxRow<minRow){  
                    alert("              ");  
                    return ;  
            }         
        req.setRequestMethod("post");  
        var url="${pageContext.request.contextPath}/business/magazineAction.do?method=doExportTxt&orderColumn=${orderColumn}&orderType=${orderType}&queryCondition="+encodeURIComponent('${queryCondition}')+"&maxRow="+maxRow+"&minRow="+minRow+"&isDecorator=false";  
        req.setRequestURL(url);  
        req.setAsync(true);  
        req.setMethodOnSuccess(displayMsg);  
        req.setRequestHeader("Content-Type","text/html;charset=gbk");  
        req.send(null);  
    }        
}