文件下载

public class CSVUtil {

	/**
	 * exportCSV
	 * @param response
	 * @param list 是装有字符串的
	 * @param csvName
	 */
	public static void exportCSV( HttpServletResponse response,List list,String csvName){
	
		try{
			response.reset();
			response.setContentType("application/csv;charset=GBK");
			response.setHeader("Content-Disposition", "inline;   filename=\""
					+ toUtf8String(csvName) + ".csv" );

			ServletOutputStream sos = response.getOutputStream();
			for(int i=0;i<list.size();i++)
			{
				String str = (String)list.get(i);		
				sos.println(str);
			}
		
			sos.close();
			sos.flush();
		}catch(Exception ex ){
			ex.printStackTrace();
		}
		


	}
	// toUtf8String()对中文进行转换
	// 下载为中文名不会出现乱码
	private static 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());
				}
			}
		}
		return sb.toString();
	}
}


action中代码
 
public ActionForward csvDown(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        
    	String startTime = request.getParameter("startTimeLog") + " 00:00:00";
    	String endTime = request.getParameter("endTimeLog") + " 23:59:59";
        
        SatLoginfoManager mgr = (SatLoginfoManager) getBean("satLoginfoManager");
        List dataList = mgr.selectbytime(startTime, endTime);
        
        //csv信息设置
        String csvName = "系统日志" + StringUtils.dateToString(new Date(),"yyyy-MM-dd");
        List csvLsit = new ArrayList();
        StringBuffer temp = new StringBuffer();
        temp.append("\"操作人员\",\"时间\",\"事项名称\",\"申请人\",\"操作类型\",\"备注\"");
        csvLsit.add(temp.toString());
        for(int i=0; i< dataList.size(); i++) {
        	SatLoginfo satLoginfo = (SatLoginfo)dataList.get(i);
        	temp.delete(0, temp.length());
        	temp.append("\"" + satLoginfo.getUserid() + "\",");
        	temp.append("\"" + satLoginfo.getTime() + "\",");
        	temp.append("\"" + satLoginfo.getItemname() + "\",");
        	temp.append("\"" + NulltoSapce(satLoginfo.getOwner()) + "\",");
        	temp.append("\"" + satLoginfo.getOpeatype() + "\",");
        	temp.append("\"" + NulltoSapce(satLoginfo.getOther()) + "\"");
        	csvLsit.add(temp.toString());
        }
        
        CSVUtil.exportCSV(response,csvLsit,csvName);

        return null;
    }
    
    private String NulltoSapce(String str){
    	if(str == null) {
    		str = "";
    	}
    	return str;
    }

你可能感兴趣的:(C++,c,C#,J#)