`
收藏列表
标题 标签 来源
Java 解压zip文件 java code
 public UnZip2(){  
         
	    }  
	    /** 
	     * 解压静态方法 
	     * @param zipFileName 
	     * @param outputDirectory 
	     * @throws Exception 
	     */  
	    public static void extract(String zipFileName,String outputDirectory) throws Exception{  
	        try {  
	            org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);  
	            java.util.Enumeration e = zipFile.getEntries();  
	            org.apache.tools.zip.ZipEntry zipEntry = null;  
	  
	            while (e.hasMoreElements()){  
	                zipEntry = (ZipEntry)e.nextElement();  
	                //System.out.println("unziping "+zipEntry.getName());  
	                if (zipEntry.isDirectory()){  
	                    String name=zipEntry.getName();  
	                    name=name.substring(0,name.length()-1);       
	                    mkDirs(outputDirectory+File.separator+name);                      
	                    //System.out.println("创建目录:"+outputDirectory+File.separator+name);  
	  
	                }else{  
	                    String name=zipEntry.getName();  
	                    String dir = name.substring(0,name.lastIndexOf("/"));  
	                    mkDirs(outputDirectory+File.separator+dir);                   
	                    //System.out.println("创建文件:"+outputDirectory+File.separator+name);                    
	                    File f=new File(outputDirectory+File.separator+zipEntry.getName());  
	                    f.createNewFile();  
	                    InputStream in = zipFile.getInputStream(zipEntry);  
	                    FileOutputStream out=new FileOutputStream(f);                     
	                    int c;  
	                    byte[] by=new byte[1024];  
	                    while((c=in.read(by)) != -1){  
	                        out.write(by,0,c);  
	                    }  
	                    out.close();  
	                    in.close();  
	                }  
	            }
	            zipFile.close();
	        }  
	        catch (Exception ex){  
	            System.out.println("解压文件异常"+ex.getMessage());  
	            ex.printStackTrace();  
	        }  
	    }  
	    /** 
	     * 创建目录,包括子目录 
	     * @param dir 
	     * @throws Exception 
	     */  
	    private static void mkDirs(String dir) throws Exception{  
	        if(dir == null || dir.equals("")) return;  
	        File f1 = new File(dir);  
	        if(!f1.exists())  
	            f1.mkdirs();  
	    }     
	    public static void unzip(String sourceZip,String destDir) throws Exception{     
	        try{     
	            Project p = new Project();     
	            Expand e = new Expand();     
	            e.setProject(p);     
	            e.setSrc(new File(sourceZip));     
	            e.setOverwrite(false);     
	            e.setDest(new File(destDir));     
	            /*   
	            ant下的zip工具默认压缩编码为UTF-8编码,   
	            而winRAR软件压缩是用的windows默认的GBK或者GB2312编码   
	            所以解压缩时要制定编码格式   
	            */    
	            e.setEncoding("GBK");     
	            e.execute();     
	        }catch(Exception e){     
	            throw e;     
	        }     
	    } 
	    
Java 上传文件 java code
<form action="../downFile/uploadFile" method="post" id="frm" enctype="multipart/form-data">
上传文件:	<input id="file" name="file" type="file" style="width: 200px"/>
<input type="button" value="上传" id="btnSub" class="l-button l-button-submit" onclick="checkFileType()" /></form>

// 上传项目文件
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public String uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 目标存储路径,服务器部署目录下
		String savePath = request.getRealPath(request.getContextPath())
				+ "\\upload\\";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件:
		MultipartFile file = multipartRequest.getFile("file");
		savePath += file.getOriginalFilename();
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;

		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(file.getInputStream());
			File outFile = new File(savePath);
			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(outFile));
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
			request.setAttribute("resultMessage", "上传文件成功");
			String path = request.getRealPath(request.getContextPath())
			+ "\\upload\\";// 设置路径
			queryUpgradeFile(request, response,path);
			this.getHistory(request, response);
			return "upload/upload";
		}
	}
Java 修改系统时间 java code
  一: //参数格式:dateString :YYYY-MM-DD HH:MI:SS
	 String dateString = request.getParameter("dateString");
		String[] dates = dateString.split(" ");
		System.out.println("1==="+dates[0]+"=2==="+dates[1]);
		try {
			String time = "cmd /c time "+dates[1];
			String date = "cmd /c date "+dates[0];
	    	java.lang.Runtime.getRuntime().exec(time);
	    	java.lang.Runtime.getRuntime().exec(date);
	    } catch (java.io.IOException e) 
	    {
	    	e.printStackTrace();           
	    }
  二:	//获取北京时间+系统时间
	@RequestMapping(value = "/getBJTime")
	public void getBJTime(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		URL url=new URL("http://www.bjtime.cn");//取得资源对象
	       URLConnection uc=url.openConnection();//生成连接对象
	       uc.connect(); //发出连接
	       long ld=uc.getDate(); //取得网站日期时间
	       Date date=new Date(ld); //转换为标准时间对象
	       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	       String dateString = formatter.format(date);
	       SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	       String xtsj = df.format(new Date());
	       String dates = dateString+","+xtsj;
	       response.getWriter().write(dates);
	}
java Dom 解析和生成XML文件(普通) java code
xml:
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<name>丁宏亮</name>
<sex>m</sex>
<age>30</age>
</employee>
</employees>

//一:解析
    public static void parserXml(String fileName) { 
	    	try { 
	    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
	    	DocumentBuilder db = dbf.newDocumentBuilder(); 
	    	Document document = db.parse(fileName); 
	    	NodeList employees = document.getChildNodes(); 
	    	for (int i = 0; i < employees.getLength(); i++) { 
	    	Node employee = employees.item(i); 
	    	NodeList employeeInfo = employee.getChildNodes(); 
	    	for (int j = 0; j < employeeInfo.getLength(); j++) { 
	    	Node node = employeeInfo.item(j); 
	    	NodeList employeeMeta = node.getChildNodes(); 
	    	for (int k = 0; k < employeeMeta.getLength(); k++) { 
	    	System.out.println(employeeMeta.item(k).getNodeName() 
	    	+ ":" + employeeMeta.item(k).getTextContent()); 
	    	} 
	    	} 
	    	} 
	    	System.out.println("解析完毕"); 
	    	} catch (FileNotFoundException e) { 
	    	System.out.println(e.getMessage()); 
	    	} catch (ParserConfigurationException e) { 
	    	System.out.println(e.getMessage()); 
	    	} catch (SAXException e) { 
	    	System.out.println(e.getMessage()); 
	    	} catch (IOException e) { 
	    	System.out.println(e.getMessage()); 
	    	} 
	    }



//二:生成xml
public static void createXml0(String fileName) throws ParserConfigurationException { 
	    	DocumentBuilderFactory factory = DocumentBuilderFactory 
	    	.newInstance();
	    	DocumentBuilder builder = factory.newDocumentBuilder(); 
	    	Document	document = builder.newDocument(); 
	    	Element root = document.createElement("employees"); 
	    	document.appendChild(root); 
	    	Element employee = document.createElement("employee"); 
	    	Element name = document.createElement("name"); 
	    	name.appendChild(document.createTextNode("丁宏亮")); 
	    	employee.appendChild(name); 
	    	Element sex = document.createElement("sex"); 
	    	sex.appendChild(document.createTextNode("m")); 
	    	employee.appendChild(sex); 
	    	Element age = document.createElement("age"); 
	    	age.appendChild(document.createTextNode("30")); 
	    	employee.appendChild(age); 
	    	root.appendChild(employee); 
	    	TransformerFactory tf = TransformerFactory.newInstance(); 
	    	try { 
	    	Transformer transformer = tf.newTransformer(); 
	    	DOMSource source = new DOMSource(document); 
	    	transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
	    	transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
	    	PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); 
	    	StreamResult result = new StreamResult(pw); 
	    	transformer.transform(source, result); 
	    	System.out.println("生成XML文件成功!"); 
	    	} catch (TransformerConfigurationException e) { 
	    	System.out.println(e.getMessage()); 
	    	} catch (IllegalArgumentException e) { 
	    	System.out.println(e.getMessage()); 
	    	} catch (FileNotFoundException e) { 
	    	System.out.println(e.getMessage()); 
	    	} catch (TransformerException e) { 
	    	System.out.println(e.getMessage()); 
	    	} 
	    	} 

 public static void crateXml() throws TransformerException{
    	 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
         DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			Document document = builder.newDocument();    
	         Element root = document.createElement("Languages");
	         root.setAttribute("cat", "IT");
	         Element lan1=document.createElement("lan");
	         lan1.setAttribute("id","1");
	         Element name1=document.createElement("name");
	         Element ide1=document.createElement("ide");
	         name1.setTextContent("Java");
	         ide1.setTextContent("Eclipse");
	         lan1.appendChild(name1);
	         lan1.appendChild(ide1);
	         
	         Element lan2=document.createElement("lan");
	         lan2.setAttribute("id","2");
	         Element name2=document.createElement("name");
	         Element ide2=document.createElement("ide");
	         name2.setTextContent("C#");
	         ide2.setTextContent("Xcode");
	         lan2.appendChild(name2);
	         lan2.appendChild(ide2);
	         
	         root.appendChild(lan1);
	         root.appendChild(lan2);
	         document.appendChild(root);
	         //----------------
	         System.out.println(document.toString());
	         // TransformerFactory: 将xml 转换成其他格式
	         TransformerFactory transformerFactory=TransformerFactory.newInstance();
	         Transformer transformer=transformerFactory.newTransformer();
	         StringWriter writer=new StringWriter();
             transformer.transform(new DOMSource(document), new StreamResult(writer));
             System.out.println(writer.toString());
             transformer.transform(new DOMSource(document), new StreamResult(new File("D:\\newXml.xml")));
	         
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
    }
java Dom 解析和生成XML文件 java code
//一:xml文件:该文件是C#的xml 配置文件
<?xml version="1.0"?>
<configuration>  
<startup useLegacyV2RuntimeActivationPolicy="true">    
<supportedRuntime version="v4.0"/>  
</startup>  
<appSettings>    
<add key="DBUri" value="Data Source=decodeDB.db;" />   
<add key="IP" value="172.16.2.36" />    
<add key="autoStart" value="false" />   
<add key="time" value="0:0:0" />  
</appSettings>
</configuration>

//二:读取xml文件
//Dom 从配置文件中读取 内容
	public static String getAutoTime() throws ParserConfigurationException,
			SAXException, IOException {
		String result = "";
		// 读取xml 文件
		DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
          	DocumentBuilder dombuilder = domfac.newDocumentBuilder(); //(2)从DOM工厂获得DOM解析器

		InputStream is = new FileInputStream(
				"D:\\decodeServer\\DecodingOnWallService.exe.config");//配置文件路径 //(3)把要解析的XML文档转化为输入流,以便DOM解析器解析它
		Document doc = dombuilder.parse(is); //(4)解析XML文档的输入流,得到一个Document
		Element root = doc.getDocumentElement(); //(5)得到XML文档的根节点
		NodeList books = root.getChildNodes();
		if (books != null) {
			for (int i = 0; i < books.getLength(); i++) {
				Node book = books.item(i);
				if (book.getNodeType() == Node.ELEMENT_NODE) {
					// (8)轮循子节点
					for (Node node = book.getFirstChild(); node != null; node = node
							.getNextSibling()) {
						if (node.getNodeType() == Node.ELEMENT_NODE) {
							if (node.getNodeName().equals("supportedRuntime")) {
								String elementData = node.getTextContent();
								String name = node.getNodeValue();
							}
							if (node.getNodeName().equals("add")) {
								if (node.getAttributes().getNamedItem("key")
										.getNodeValue().equals("autoStart")) {
									result += node.getAttributes()
											.getNamedItem("value")
											.getNodeValue()
											+ ";";
								}
								if (node.getAttributes().getNamedItem("key")
										.getNodeValue().equals("time")) {
									result += node.getAttributes()
											.getNamedItem("value")
											.getNodeValue();
								}
							}
						}
					}
				}
			}
		}
		return result;
	}

//三:生成 xml文件
 public static boolean createXml(String fileName,String ip,String autoStr,String timeStr) throws ParserConfigurationException { 
	    	DocumentBuilderFactory factory = DocumentBuilderFactory 
	    	.newInstance(); 
	    	DocumentBuilder builder = factory.newDocumentBuilder(); 
	    	Document	document = builder.newDocument(); 
	    	Element root = document.createElement("configuration"); 
	    	document.appendChild(root); 
	    	
	    	//startup
	    	Element startup = document.createElement("startup"); 
	    	startup.setAttribute("useLegacyV2RuntimeActivationPolicy","true");
	    	Element su=document.createElement("supportedRuntime");
	    	su.setAttribute("version", "v4.0");
	    	startup.appendChild(su); 
	    	root.appendChild(startup);
	
	    	//appSettings
	    	Element app=document.createElement("appSettings");
	    	Element add0=document.createElement("add");
	    	add0.setAttribute("key", "DBUri");
	    	add0.setAttribute("value","Data Source=decodeDB.db;");
	    	app.appendChild(add0);
	    	
	    	Element add1=document.createElement("add");
	    	add1.setAttribute("key", "IP");
	    	add1.setAttribute("value",ip);
	    	app.appendChild(add1);
	    	
	    	Element add2=document.createElement("add");
	    	add2.setAttribute("key", "autoStart");
	    	add2.setAttribute("value",autoStr);
	    	app.appendChild(add2);
	    	
	    	Element add3=document.createElement("add");
	    	add3.setAttribute("key", "time");
	    	add3.setAttribute("value",timeStr);
	    	app.appendChild(add3);
	    	
	    	root.appendChild(app);
	    	TransformerFactory tf = TransformerFactory.newInstance(); 
	    	try { 
	    	Transformer transformer = tf.newTransformer(); 
	    	DOMSource source = new DOMSource(document); 
//	    	transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312"); 
	    	transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
	    	PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); 
	    	StreamResult result = new StreamResult(pw); 
	    	transformer.transform(source, result); 
	    	pw.close();
	    	System.out.println("生成XML文件成功!"); 
	    	return true;
	    	} catch (TransformerConfigurationException e) { 
	    	System.out.println(e.getMessage()); 
	    	return false;
	    	} catch (IllegalArgumentException e) { 
	    	System.out.println(e.getMessage()); 
	    	return false;
	    	
	    	} catch (FileNotFoundException e) { 
	    	System.out.println(e.getMessage()); 
	    	return false;
	    	
	    	} catch (TransformerException e) { 
	    	System.out.println(e.getMessage()); 
	    	return false; 
	    	} 
	    	} 
java 判断某应用程序是否已启动 java code
public boolean getProcess() {
		boolean flag = false;
		try {
			Process p = Runtime.getRuntime().exec("cmd /c tasklist ");
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream os = p.getInputStream();
			byte b[] = new byte[256];
			while (os.read(b) > 0)
				baos.write(b);
			String s = baos.toString();
			if (s.indexOf("DecodingOnWallService.exe") >= 0) {//DecodingOnWallService.exe 应用程序名
				flag = true;
			} else {
				flag = false;
			}
		} catch (java.io.IOException ioe) {
		}
		return flag;
	}
java 查询某路径下 文件 java code
	String path = "D:\\decodeServer\\log";// 设置路径
		Pattern pat = Pattern.compile("[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}.log");// 设置文件名格式
		File file = new File(path);
		if(file.isDirectory()){
			File[] arr = file.listFiles();
			ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>();
			for (int i = 0; i < arr.length; i++) {
				Matcher mat = pat.matcher(arr[i].getName());
				if (mat.matches()) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("name", arr[i].getName());
					list.add(map);
				}
			}
			//log列表排序
	        Collections.sort(list, new Comparator<Map<String, String>>() {   	 
	            public int compare(Map<String, String> o1, Map<String, String> o2) {
	            	String a = o1.get("name");
	            	String b = o2.get("name");
	            	a=a.replace("-", "");
	            	a=a.replace(".log", "");
	            	b=b.replace("-", "");
	            	b=b.replace(".log", "");
	            	Integer map1value = Integer.valueOf(a) ;
	            	Integer map2value = Integer.valueOf(b);
	 
	                return map2value - map1value;
	            }
	        }); 
			request.setAttribute("fileList", list);
		}
Java删除文件夹和文件 java code http://kxjhlele.iteye.com/blog/323657
//一:验证传入路径是否为正确的路径名(Windows系统,其他系统未使用)
// 验证字符串是否为正确路径名的正则表达式
private static String matches = "[A-Za-z]:\\\\[^:?\"><*]*";
// 通过 sPath.matches(matches) 方法的返回值判断是否正确
// sPath 为路径字符串

//二:通用的文件夹或文件删除方法,直接调用此方法,即可实现删除文件夹或文件,包括文件夹下的所有文件
    /**
     *  根据路径删除指定的目录或文件,无论存在与否
     *@param sPath  要删除的目录或文件
     *@return 删除成功返回 true,否则返回 false。
     */
    public boolean DeleteFolder(String sPath) {
        flag = false;
        file = new File(sPath);
        // 判断目录或文件是否存在
        if (!file.exists()) {  // 不存在返回 false
            return flag;
        } else {
            // 判断是否为文件
            if (file.isFile()) {  // 为文件时调用删除文件方法
                return deleteFile(sPath);
            } else {  // 为目录时调用删除目录方法
                return deleteDirectory(sPath);
            }
        }
    }
//三:实现删除文件的方法
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public boolean deleteFile(String sPath) {
        flag = false;
        file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
//四:实现删除文件夹的方法
    /**
     * 删除目录(文件夹)以及目录下的文件
     * @param   sPath 被删除目录的文件路径
     * @return  目录删除成功返回true,否则返回false
     */
    public boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

//文件夹的复制
	/** 
     * 复制整个文件夹内容 
     * @param oldPath String 恢复文件夹存放路径
     * @param newPath String 要被覆盖的文件夹路径
     * @return boolean 
	 * @throws IOException 
     */ 
	boolean state=false;
   public void copyFolder(String oldPath, String newPath) throws IOException { 
       try { 
           (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 
           File a=new File(oldPath); 
           String[] file=a.list(); 
           File temp=null; 
           for (int i = 0; i < file.length; i++) { 
               if(oldPath.endsWith(File.separator)){ 
                   temp=new File(oldPath+file[i]); 
               } 
               else{ 
                   temp=new File(oldPath+File.separator+file[i]); 
               } 

               if(temp.isFile()){ 
                   FileInputStream input = new FileInputStream(temp); 

//                   FileOutputStream output = new FileOutputStream(newPath + "/" + 
//                           (temp.getName()).toString()); //有的系统出现错误
                   String fileName=newPath + "/" + (temp.getName()).toString();
                   File newFile0=new File(fileName);
                   if(newFile0.exists()){
                	   
                   }else{
                	   newFile0.createNewFile();
                   }
                   FileOutputStream output=new FileOutputStream(newFile0);                 byte[] b = new byte[1024 * 5]; 
                   int len; 
                   while ( (len = input.read(b)) != -1) { 
                       output.write(b, 0, len); 
                   } 
                   output.flush(); 
                   output.close(); 
                   input.close(); 
               } 
               if(temp.isDirectory()){//如果是子文件夹 
                   copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
               } 
           } 
           state=true;
       } 
       catch (Exception e) { 
    	   state=false;
           System.out.println("复制整个文件夹内容操作出错");
           e.printStackTrace(); 

       } 
   }
java 读写文件,jsp页面下载文件 java code
//一:java 读取文件
String filePath1="D:\\exePath.txt";
		String encoding = "UTF-8";
		File file = new File(filePath1);
		BufferedReader reader = null;
		String laststr = "";
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file), "UTF-8");
			reader = new BufferedReader(read);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				laststr = laststr + tempString;
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}else{
				
			}
		}
//java 写文件
String inputStr = "要写入文件的内容";
		try {
			String filePath="D:\\exePath.txt";
			File file=new File(filePath);
			if(!file.exists()){
				try {    
			        file.createNewFile();    
			    } catch (IOException e) {    
			        e.printStackTrace();    
			    }    
			}
			FileOutputStream out;
			out = new FileOutputStream(filePath);
			OutputStreamWriter osw;
			try {
				osw = new OutputStreamWriter(out, "UTF-8");
				try {
					osw.write(inputStr);
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
//三:jsp页面 下载文件
<%@ page contentType="application/x-msdownload" pageEncoding="utf-8"
	import="java.util.*" errorPage=""%>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="java.io.*"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
	//关于文件下载时采用文件流输出的方式处理:  
	//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;  
	/***
    //有错误
	response.reset();//可以加也可以不加  
	response.setContentType("application/x-download");
	String fileName=request.getParameter("name");
	String filedownload="F:\\log"; //获取的物理路径  
    fileName = URLEncoder.encode(fileName, "UTF-8");
	response.addHeader("Content-Disposition", "attachment;filename="
			+ fileName);
	java.io.OutputStream outp = null;
	java.io.FileInputStream in = null;
	try {
		outp = response.getOutputStream();
		in = new FileInputStream(filedownload);
		byte[] b = new byte[1024];
		int i = 0;
		while ((i = in.read(b)) > 0) {
			outp.write(b, 0, i);
		}
		outp.flush();   
		out.clear();
		out = pageContext.pushBody();
	} catch (Exception e) {
		System.out.println("Error!");
		e.printStackTrace();
	} finally {
		if (in != null) {
			in.close();
			in = null;
		}
	}
	*/
	
	response.setContentType("text/html");    
    OutputStream o = response.getOutputStream();  
    byte b[] = new byte[5000];  
    String fileName=request.getParameter("name");
    File fileLoad = new File("D:\\decodeServer\\log\\"+fileName);  
    response.setContentType("application/x-msdownload");  
  
    response.setHeader("content-disposition",  
            "attachment; filename="+fileName);  
    long fileLength = fileLoad.length();  
    String length1 = String.valueOf(fileLength);  
    response.setHeader("Content_Length", length1);  
    FileInputStream in = new FileInputStream(fileLoad);  
    int n;  
    while ((n = in.read(b)) != -1) {  
        o.write(b, 0, n);  
    }  
  
    in.close();  
    out.clear();  
    out = pageContext.pushBody();  
%>
ligerGrid的功能列表 extjs
一:

function initGrid() {
		$.post("../user/queryUserList", {}, function(data) {
		var userdata={Rows:[{"deptId":0,"flag":0,"isconfigUser":1,"orderby":0,"orgId":1,"paramOne":"","paramTwo":"","regDate":null,"regDateString":""}],Total:1};
			alert("userdata="+userdata);
			$("#maingrid4").ligerGrid({
				checkbox : true,
				columns : [ {
					display : 'userId',
					name : 'deptId',
					align : 'left',
					width : 120
				}, {
					display : '用户名',
					name : 'userName'
				},{
				 display:'deptId',
				 name:'userId'
				} ],
				pageSize : 30,
				data : userdata,
				width : '100%',
				height : '100%'
			});
			
			$("#pageloading").hide();
		});
	}

二:
function initGrid() {
		$.post("../user/queryUserList", {}, function(data) {
			var jsonObj = {};
			var user = eval(data);//解析从后台传递过来的json 字符串
			jsonObj.Rows = user;
			var columns = [ {
				display : '序号',
				width : 30,
				render : function(item, index) {
					return (index + 1);
				}
			}, {
				display : 'userId',
				name : 'deptId',
				align : 'left',
				width : 120
			}, {
				display : '用户名',
				name : 'userName'
			}, {
				display : 'deptId',
				name : 'userId'
			} ];
			$("#maingrid4").ligerGrid({
			    checkbox : true,
				columns : columns,
				data : jsonObj,
				
				width : '100%',
				height : '100%',
				 toolbar: { items: [
                { text: '增加', click: itemclick, icon: 'add' },
                { line: true },
                { text: '修改', click: itemclick, icon: 'modify' },
                { line: true },
                { text: '删除', click: itemclick, img: '<%=basePath%>resources/LigerUI/Source/lib/ligerUI/skins/icons/delete.gif' }
                ]
                }
			});
			$("#pageloading").hide();
		});
	}
ExtJs chart 图标组件 extjs
	 
	一: //饼状图
		 var dataStore=new Ext.data.JsonStore({
	  fields:['age','percentage','growing'],
	  data:[
	   {age:'小于30岁',percentage:10,growing:35},
	   {age:'30-40岁',percentage:40,growing:30},
	   {age:'40-50岁',percentage:30,growing:30},
	   {age:'大于50岁',percentage:20,growing:30}
	  ]
	 });
	 Ext.create('widget.panel',{
	  title:'员工年龄分布',
	  width:400,
	  height:400,
	  renderTo:'div3',
	  layout:'fit',
	  items:[{
	  xtype:'chart',
	  store:dataStore,
	  animate:true,//是否启用动画
	  legend:{
	  position:'bottom'//图例位置
	  },
	  shadow:true,
	  series:[{
	  type:'pie',//图标序列类型
	  field:'percentage',//对应饼状图角度的字段名
	  showInLegend:true,
	  colorSet:['#FFFF00','#669900','#FF6699','#66CCCC'],
	  label:{
	   field:'age',//标签字段名
	   contrast:true,
	   renderer:function(v){//自定义 标签渲染函数
	   return "["+v+"]";
	   },
	   display:'middle',//标签显示方式
	   font:'18px "Lucida Grande"'
	  },
	  highlight:{
	  segment:{
	   margin:10
	  }
	  },
	  tips:{
	   trackMouse:true,//是否启用鼠标跟踪
	   width:50,
	   height:28,
	   renderer:function(storeItem){
	   var title=storeItem.get('percentage')+'%';//自定义渲染函数
	   this.setTitle(title);
	   }
	  }
	  }]
	  }]
	 });
   二.//坐标轴组件
	 var dataStore0=new Ext.data.JsonStore({
	  fields:['name','percentage'],
	  data:[
	   {name:'小于30岁',percentage:2},
	   {name:'30-40岁',percentage:4},
	   {name:'40-50岁',percentage:3},
	   {name:'大于50岁',percentage:3}
	  ]
	 });
	 Ext.create('widget.panel',{
	  title:'员工年龄分布',
	  width:400,
	  height:400,
	  renderTo:'div4',
	  layout:'fit',
	  items:[{
	  xtype:'chart',
	  store:dataStore0,
	  axes:[{
	   type:'Numeric',//配置坐标轴类型为 数值类型
	   dashSize:10,//做标注前导线条长度,默认为3
	   position:'left',//配置坐标在左侧
	   fields:['percentage'],//指定坐标对应的字段
	   title:'百分比',//配置坐标轴标题
	   grid:{
	   //奇数行
	    odd:{
	    opacity:1,//不透明
	    fill:'#FFFF99',//表格线颜色
	    stroke:'#FF3300',
	    'stroke-width':0.5
	    },
	    even:{
	    opacity:0,//透明
	    stroke:'#6600CC',//表格线颜色
	    'stroke-width':0.5
	    }
	   },
	   majorTickSteps:10,//主区间数(坐标轴最大值与最小值之间的主区间数)
	   minorTickSteps:3//副区间数
	  },{
	   type:'Category',//配置做标注为目录坐标
	   position:'bottom',//配置坐标在左侧
	   fields:['name'],//指定坐标对应的字段
	   grid:true,// 启用表格
	   title:'年龄段'
	  }],
	  series:[{
	   type:'line',
	   axis:'left',
	   xField:'name',//横轴字段
	   yField:'percentage'//纵轴字段
	  }]
	  }]
	 });
 三: //仪表盘
	 var dataStore2=new Ext.data.JsonStore({
	 fields:['realValue'],
	 data:[{realValue:20}]
	 });
	 
	 Ext.create('Ext.panel.Panel',{
	  title:'数据仪表',
	  width:280,
	  height:230,
	  renderTo:Ext.getBody(),
	  layout:'fit',
	  items:[{
	   xtype:'chart',
	   store:dataStore2,
	   animate:{
	    easing:'elasticIn',
	    duration:1000
	   },
	   axes:[{
	    type:'gauge',//Ext.chart.axis.Gauge:仪表坐标轴
	    position:'gauge',
	    minimum:0,//仪表盘的最小值
	    maximum:100,//仪表盘的最大值
	    steps:10,//仪表盘步长
	    margin:-10
	   }],
	   series:[{
	    type:'gauge',//仪表图
	    angleField:'realValue',
	    donut:60,//仪表盘中心空白的半径
	    colorSet:['#F49D10','#ddd']
	   
	   }]
	  }],
	  buttons:[{
	   text:'随机数据',
	   handler:function(){
	    dataStore2.loadData([{
	     realValue:Math.random()*100
	    }]);
	   }
	  }]
	 });
 四://图表与表格交互实例
	 var gridDataStore=Ext.create('Ext.data.JsonStore',{
	  fields:['year','car','house','food'],
	  data:[
	  { year:'2007年',car:10,food:10,house:30,culture:5},
	  { year:'2008年',car:11,food:12,house:50,culture:8},
	  { year:'2009年',car:12,food:13,house:100,culture:10},
	  { year:'2010年',car:12,food:13,house:200,culture:8}
	  ]
	 });
	 var goodsGrid=Ext.create('Ext.grid.Panel',{
	  store:gridDataStore,
	  columnLines:true,
	  columnWidth:.5,
	  height:400,
	  columns:[
	  {header:'年份',dataIndex:'year',width:60},
	  {header:'汽车',dataIndex:'car',width:60},
	  {header:'住房',dataIndex:'house',width:60},
	  {header:'视频',dataIndex:'food',width:60},
	  {header:'文化',dataIndex:'culture',width:60}
	  ],
	  title:'产品销售利润统计表'
	 });
	 goodsGrid.getSelectionModel().on('select',function(sm,record,rowIndex){
	  chartDataStore.loadData([
	  {goods:'汽车',gain:record.get('car')},
	  {goods:'住房',gain:record.get('house')},
	  {goods:'食品',gain:record.get('food')},
	  {goods:'文化',gain:record.get('culture')}
	  ]);
	 });
	 var chartDataStore=Ext.create('Ext.data.JsonStore',{
	  fields:['goods','gain'],
	  data:[]
	 });
	 var goodsChart=Ext.create('Ext.chart.Chart',{
	  store:chartDataStore,
	  animate:true,
	  legend:{
	   position:'bottom'
	  },
	  height:400,
	  columnWidth:.5,
	  series:[{
	   type:'pie',
	   field:'gain',
	   showInLegend:true,
	   label:{
	    field:'goods',
	    contrast:true,
	    display:'moddle',
	    font:'18px "Lucida Grande"'
	   }
	  }]
	 });
	 Ext.create('Ext.panel.Panel',{
	  width:600,
	  height:400,
	  renderTo:Ext.getBody(),
	  layout:'column',
	  items:[goodsGrid,goodsChart]
	 });
ExtJS 矩形 动态变换 拖拽缩放 extjs
<script type="text/javascript">
	Ext.require([ '*' ]);
	Ext.onReady(function() {
	var gcmp=Ext.create('Ext.draw.Component',{
	  width:600,
	  height:400,
	  viewBox:false,
	  renderTo:Ext.getBody(),
	  items:[{
	   type:'rect',//矩形
	   x:50,
	   y:50,
	   height:150,
	   width:150,
	   stroke:'#CCFFFF',
	   fill:'#6600cc',
	   rotate:{//rotate:旋转配置项
	   degrees:45//旋转的角度
	   }
	  }]
	 });

	 Ext.get('btn').on('click',function(){
	 //获取第一个子画面对象
	  var sprite=gcmp.surface.items.first();
	  //获取子画面当前角度
	  var degree=sprite.attr.rotation.degrees;
	  
	  //获取子画面对象的x、y 坐标
	  var xc=sprite.attr.translation.x;
	  var yc=sprite.attr.translation.y;
	  
	  //获取子画面的缩放比
	  var xs=sprite.attr.scaling.x||1;
	  var ys=sprite.attr.scaling.y||1;
           //通过调用 sprite.setAttributes方法动态改变子画面属性实现
	 sprite.setAttributes({
	 //旋转
	  rotation:{
	  degrees:degree+10
	  },
	  translate:{
	   x:xc+10,
	   y:yc+10
	  },
	  //缩放
	  scale:{
	   x:xs*0.9,
	   y:ys*0.9
	  }
	 },true);
	 });

	 //拖拽缩放
	 var gcmp1=Ext.create('Ext.draw.Component',{
	  width:200,
	  height:200,
	  viewBox:true,//使图形充满容器
	  renderTo:'container',
	  resizable:{
	   dynamic:true,
	   pinned:true,
	   handles:'all'
	  },
	  items:[{
	   type:'rect',//矩形
	   x:20,
	   y:20,
	   height:150,
	   width:150,
	   stroke:'#CCFFFF',
	   fill:'#6600cc'
	   
	  }]
	 });
	});
</script>
Extjs ViewPort extjs
/***
Ext.container.Viewport:代表浏览器窗口的整个显示区域,将document body作为渲染对象,它会根据浏览器窗口的大小自动调整自身的尺寸,在一个页面中,只允许出现一个ViewPort实例,它没有提供对滚动条的支持,如果需要使用滚动条,应在其子面板中进行设置
*/
<script type="text/javascript">
	Ext.require([ '*' ]);
	Ext.onReady(function() {
	Ext.create('Ext.container.Viewport',{
	 layout:'border',
	 items:[{
	 title:'north Panel',
	 html:'上边',
	 region:'north',
	 height:100
	 },{
	 title:'West Panel',
	 html:'左边',
	 region:'west',
	 width:200
	 },{
	 xtype:'tabpanel',
	 // html:'中间',
	 html:'<h1>显示操作部分</h1>',
	 items:[
	 {title:'新闻管理'},
	 {title:'用户管理'}
	 ],
	  region:'center'
	 }]
	});
	});
</script>
Extjs tree 整体同步加载树节点 extjs
     //jsp 页面
		//整体同步加载树节点
		var store=Ext.create('Ext.data.TreeStore',{
		proxy:{
		type:'ajax',
		url:'<%=basePath%>user/getSyncTree'
		}
		});
		
		var tree=Ext.create('Ext.tree.Panel',{
		renderTo:'tree3',
		store:store,
		rootVisible:false,
		useArrows:true,
		frame:true,
		title:'整体同步加载树节点',
		width:200,
		height:300,
		columns:[{
		xtype:'treecolumn',
		text:'名称',
		dataIndex:'text'
		}] //columns:可去掉
		});

//java后台
	@RequestMapping(value="/getSyncTree")
	public void getSyncTree(HttpServletRequest request,HttpServletResponse response){
		String result="[{text:'总公司',expanded:true,children:[{text:'分公司一',leaf:false,children:[{text:'部门一',leaf:true},{text:'部门二',leaf:true}]},{text:'分公司二',leaf:true}]}]";
	    try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
Extjs tree 可拖拽 extjs
Ext.require([ '*' ]);
	Ext.onReady(function() {
		Ext.create('Ext.tree.Panel', {
			title : '树一',
			width : 200,
			height : 150,
			renderTo : 'tree1',
			root : {
				text : 'root',
				expanded : true,
				children : [ {
					text : '节点一',
					leaf : true
				}, {
					text : '节点二',
					leaf : true
				} ]
			},//end root
			viewConfig : {
				plugins : {
					ptype : 'treeviewdragdrop'//拖拽插件
				}
			}
		});

		Ext.create('Ext.tree.Panel', {
			title : '树二',
			width : 200,
			height : 150,
			renderTo : 'tree2',
			root : {
				text : '树根',
				expanded : true
			},//end root
			viewConfig : {
				plugins : {
					ptype : 'treeviewdragdrop'
				}
			}
		});

	});
Extjs tree 实例 extjs, tree
一:简单的树面板实例 
Ext.onready(function(){ 
  var tree=Ext.create('Ext.tree.Panel',{ 
    title:'树面板实例', 
    width:150, 
    height:100, 
    renderTo:Ext.getBody,//或者 div的Id 
    root:{ 
         text:'树根', 
         expanded:true,//默认展开根节点 
          children:[ 
          {
          text:'node1',//节点名称 
           leaf:true //是否是叶子 
           }, 
          {
          text:'node2',//节点名称 
           leaf:true 
          } 
        ] 
       } 
    }); 
}); 

二:多列树 
Ext.onready(function(){ 
    var tree=Ext.create('Ext.tree.Panel',{ 
        title:'多列树 实例', 
        width:200, 
        height:100, 
      renderTo:Ext.getBody,//或者 div的Id 
        fields:['name','description'], 
        columns:[ 
            { 
            xtype:'treecolumn',//树状表格列 
               text:'名称', 
        dataIndex:'name', 
            width:100, 
         sortable:true 
            }, 
            { 
            text:'描述', 
       dataIndex:'description', 
            flex:1, 
        sortable:true 
        } 
        ], 
       root:{ 
        name:'treeRoot', 
        description:'树根的描述', 
        expanded:true, 
        children:[ 
        { 
          name:'节点一', 
          description:'节点一的描述', 
          leaf:true 
          }, 
        { 
          name:'节点二', 
          description:'节点一的描述', 
          leaf:true 
          } 
    ] 
    } 
}); 
}); 

三:分级加载树节点 

Ext.onready(function(){ 
    //定义用户User模型
     Ext.regModel("OrgInfo",{
      fields:['orgId','name','count']
     });
     var myStore=new Ext.data.TreeStore({
       model:'orgInfo',
       nodeParam:'orgId',//指定节点参数名
        proxy:{
          type:'ajax',
          url:'treeServer.jsp',//url:后台访问路径
            reader:'json'
       },
        autoLoad:true,
        root:{//根节点
           name:'根节点',
          id:'-1'
        }
     });
     var tree=Ext.create('Ext.tree.Panel',{
          title:'异步加载树', 
          renderTo:'tree',//Ext.getBody()
          width:250,
          height:150,
          columns:[{
            xtype:'treecolumn',//树状表格列 
               text:'公司名称', 
        dataIndex:'name', 
            width:100, 
         sortable:true
           },{
                text:'员工人数', 
        dataIndex:'count', 
            flex:1, 
         sortable:true 
           }],
	 store:myStore,
	 rootVisible:true,
	 listeners:{//添加事件
	  afterrender:function(tree){
	  //展开一级节点
	  setTimeout(function(){
           var rootNode=tree.getRootNode(); rootNode.expand(); },10);
           //展开到某一节点 :expPath: "/根Id/一级节点Id/.....
"	  var expPath="${sessionScope.focusEquipId}";
      if(expPath!=null && expPath!=""){
	  tree.expandPath(expPath);
	  }
	  }
	 }
     }); 
}); 

treeServer.jsp:返回JSON对象
<%
 String result="";
result="[{name:'总公司1',count:100,id:1001},{name:'总公司2',count:200,id:1002}]":
response.getWriter().write(result);
%>










Extjs tree 异步加载 节点 extjs
//一:jsp 页面

<%@ page contentType="text/html; charset=UTF-8" language="java"
	import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="com.luguang.model.*"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
    <HEAD>
    <base href="<%=basePath%>">
		<title>组织树</title>
        	
		<script LANGUAGE="JavaScript">
		  Ext.require(['*']);
		Ext.onReady(function(){
	//分级异步加载节点实例
	//定义数据模型
	Ext.regModel("orgInfo0",{
	fields:['orgId','text']
	});
	var myOrgStore=new Ext.data.TreeStore({
	model:'orgInfo0',
	nodeParam:'orgId',//指定节点参数名
	proxy:{
	type:'ajax',
	url:'<%=basePath%>/org/showOrgTreeExtJsTree',
	reader:'json'
	},
	autoLoad:true,
	root:{
	 text:'${sessionScope.parOrgName}',
	 id:'org_${sessionScope.parOrgId}'
	}
	});
	function tree_itemclick0(node,event){
	var nodeId=event.data.id;
	var nodeText=event.data.text;
	
	if(nodeId.indexOf("org")>=0){
			nodeId=nodeId.substring(4,nodeId.length);
			$("#orgName0").val(nodeText);
			$("#orgId0").val(nodeId);
			}
	}
	
	var orgPointTree=Ext.create('Ext.tree.Panel',{
	renderTo:'pointOrgTree',
	 dataIndex:'text',
	 sortable:true,
	store:myOrgStore,
	rootVisible:true,
	listeners:{
	itemclick:tree_itemclick0,
  afterrender:function(orgPointTree){
	     setTimeout(function(){var rootNode=orgPointTree.getRootNode(); rootNode.expand(); },10);
	   }
	}
	});
		});
	    </script>
	</head>
	<body style="border-bottom-width:thin">
	<div id="pointOrgTree"></div>
	</body>
</html>

//二:后台代码 org/showOrgTreeExtJsTree:方法
public void showOrgTreeExtJsTree(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String result="";
		String orgId=request.getParameter("orgId");
		String[] oIds=orgId.split("_");
		String rId=request.getSession().getAttribute("rId0").toString();
		if(rId!=null && !rId.equals("")){
			if(oIds.length==2){
				if(oIds[0].equals("org")){
					int oid=Integer.parseInt(oIds[1].toString());
					//子组织
					String sql="select org.ORG_NAME ,org.ORG_ID  from lgvmp_org org,lgvmp_role_org_relation roleOrg where org.PARENT_ID="+oid+" and org.ORG_ID=roleOrg.ORG_ID and roleOrg.ROLE_ID="+rId+" order by org.ORDER_BY";
					Session sess= this.getEntityDao().getHibernateTemplate().getSessionFactory().openSession();
					ArrayList<Object[]> orgArr=(ArrayList<Object[]>) sess.createSQLQuery(sql).list();
					sess.close();
					result="[";
					for(Object[] obArr:orgArr){
						result=result+"{text:'"+obArr[0].toString()+"',id:'org_"+Integer.parseInt(obArr[1].toString())+"'},";
					}
					if(result.endsWith(",")){
						result=result.substring(0,result.length()-1);
					}
					result+="]";
				}
			}
			
		}
		response.getWriter().write(result);
	}
Java 获取计算机信息 java,计算机硬件信息
package com.luguang.terInformation.control;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInfo;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NfsFileSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SysInfo;

/**
 *
 * @author k02
 */
public class LocalInfoCollection {

    Sigar sigar;

    /**
     * Construction Method
     */
    public LocalInfoCollection() {
        sigar = new Sigar();
    }
    //获取IP地址
    public String getIPAddress() throws SigarException {
        NetInterfaceConfig nic = sigar.getNetInterfaceConfig();
        return nic.getAddress();
    }
    //获取Mac地址
    public String getMacAddress() throws SigarException {
        NetInterfaceConfig nic = sigar.getNetInterfaceConfig();
        return nic.getHwaddr();
    }
  //获取网卡信息
    public String getDescription() throws SigarException {
        NetInterfaceConfig nic = sigar.getNetInterfaceConfig();
        return nic.getDescription();
    }
    //获取机器名
    public String getHostname() throws SigarException {
        NetInfo ni = sigar.getNetInfo();
        return ni.getHostName();
    }
    //获取系统信息
    public String getOSInfo() throws SigarException {
        SysInfo si = new SysInfo();
        si.gather(sigar);
        return si.getDescription() + " " + si.getPatchLevel() + " " + si.getArch();
    }
    //获取进程数量
    public int getProcessCount() throws SigarException {
        long[] proList = sigar.getProcList();
        return proList.length;
    }
    //获取CPU类型
    public String getCPUModels() throws SigarException {
        CpuInfo[] infos = sigar.getCpuInfoList();
        CpuInfo info = infos[0];
        return info.getVendor() + " " + info.getModel() + " " + info.getMhz() / 1000.0 + "Mhz";
    }
    //获取CPU使用率
    public String getCPUUsage() throws SigarException {
        CpuPerc usage = sigar.getCpuPerc();
        return CpuPerc.format(usage.getCombined());
    }
    //获取内存大小
    public String getMemSize() throws SigarException {
        Mem m = sigar.getMem();
        String mStr = new Long(m.getTotal() /1024/1024).toString();
        return mStr + "M";
    }
    //获取内存使用率
    public String getMemUsage() throws SigarException {
        Mem m = sigar.getMem();
        String mStr = new Double(m.getUsedPercent()).toString();
        return mStr.substring(0, 5) + "%";
    }
    //获取硬盘大小
    public String getDiskTotalSize() throws SigarException {
        String diskSize="";
        long diskTotalSizeL = 0;
        FileSystem[] fslist = null;
        try {
            fslist = sigar.getFileSystemList();
        } catch (SigarException se) {
            se.printStackTrace();
        }
        for (int i = 0; i < fslist.length; i++) {
            diskTotalSizeL+=getEachPartSize(fslist[i]);
        }
        diskSize=Sigar.formatSize(diskTotalSizeL).trim();
        return diskSize;
    }
  //获取硬盘空闲大小
    public String getDiskFreeSize() throws SigarException {
        String diskSize="";
        long diskTotalSizeL = 0;
        FileSystem[] fslist = null;
        try {
            fslist = sigar.getFileSystemList();
        } catch (SigarException se) {
            se.printStackTrace();
        }
        for (int i = 0; i < fslist.length; i++) {
            diskTotalSizeL+=getEachPartFreeSize(fslist[i]);
        }
        diskSize=Sigar.formatSize(diskTotalSizeL).trim();
        return diskSize;
    }
    //获取硬盘分区大小
    private long getEachPartSize(FileSystem fs) {
        long total;
        try {
            FileSystemUsage usage;
            if (fs instanceof NfsFileSystem) {
                NfsFileSystem nfs = (NfsFileSystem) fs;
                if (!nfs.ping()) {
                    return 0;
                }
            }
            usage = sigar.getFileSystemUsage(fs.getDirName());
            total = usage.getTotal() * 1024;
        } catch (SigarException e) {
            //if there is no cd in the drive.
            total = 0;
        }
        return total;
    }
  //获取硬盘分区空闲大小
    private long getEachPartFreeSize(FileSystem fs) {
        long free;
        try {
            FileSystemUsage usage;
            if (fs instanceof NfsFileSystem) {
                NfsFileSystem nfs = (NfsFileSystem) fs;
                if (!nfs.ping()) {
                    return 0;
                }
            }
            usage = sigar.getFileSystemUsage(fs.getDirName());
            free = usage.getFree() * 1024;
        } catch (SigarException e) {
            //if there is no cd in the drive.
        	free = 0;
        }
        return free;
    }
    
    //获取网络信息
    public List getEthernetInfo() { 
    	Sigar sigar = null; 
    	ArrayList<Map> list = new ArrayList<Map>();
    	  try { 
    	   sigar = new Sigar(); 
    	   String[] ifaces = sigar.getNetInterfaceList(); 
    	   for (int i = 0; i < ifaces.length; i++) { 
    	    NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]); 
    	    if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) 
    	      || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0 
    	      || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) { 
    	     continue; 
    	    } 
    	    HashMap<String , String> map = new HashMap<String , String>(); 
    	    map.put("ip", cfg.getAddress());
    	    map.put("mac", cfg.getHwaddr());
    	    map.put("broadcast", cfg.getBroadcast());
    	    map.put("netmask", cfg.getNetmask());
    	    map.put("description", cfg.getDescription());
    	    map.put("type", cfg.getType());
    	    map.put("name", cfg.getName());
    	    list.add(map);
    	   } 
    	   return list;
    	  } catch (Exception e) { 
    	   System.out.println("Error while creating GUID" + e); 
    	   return list;
    	  } finally { 
    	   if (sigar != null) 
    	    sigar.close(); 
    	  } 
    	} 
    
    //取到当前机器的IP地址 
    public String getDefaultIpAddress() { 
      String address = null; 
      try { 
       address = InetAddress.getLocalHost().getHostAddress(); 
       // 没有出现异常而正常当取到的IP时,如果取到的不是网卡循回地址时就返回 
       // 否则再通过Sigar工具包中的方法来获取 
       if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) { 
        return address; 
       } 
      } catch (Exception e) { 
       // hostname not in DNS or /etc/hosts 
      } 
      Sigar sigar = new Sigar(); 
      try { 
       address = sigar.getNetInterfaceConfig().getAddress(); 
      } catch (SigarException e) { 
       address = NetFlags.LOOPBACK_ADDRESS; 
      } finally { 
       sigar.close(); 
      } 
      return address; 
    } 
  //取到当前机器的子网掩码
    public String getDefaultNetmask() throws IOException { 
    	String netmask = null;
    	String os = System.getProperties().getProperty("os.name");	//得到操作系统 xp
		Process pro = Runtime.getRuntime().exec("ipconfig");
		BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
		List<String> rowList = new ArrayList();
		String temp;
		while((temp = br.readLine()) != null){
			rowList.add(temp );
		}
		for (String string : rowList) {
			String sm=  os.equals("Windows XP") ? "Subnet Mask" : "子网掩码" ; //这里只判断了win7个xp
			if(string.indexOf(sm) != -1){
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
					netmask = mc.group();
					System.out.println("子掩码:" + mc.group());
				}else{
					netmask = "";
					System.out.println("子掩码为空");
				}
			};
			};
			return netmask;
		} 

    //取到当前机器默认网关
    public String getDefaultGeteway() throws IOException { 
    	String gateway = null;
    	String os = System.getProperties().getProperty("os.name");	//得到操作系统 xp
		Process pro = Runtime.getRuntime().exec("ipconfig");
		BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
		List<String> rowList = new ArrayList();
		String temp;
		while((temp = br.readLine()) != null){
			rowList.add(temp );
		}
		for (String string : rowList) {
			String dg =  os.equals("Windows XP") ? "Default Gateway" : "默认网关" ; //这里只判断了win7个xp 
			if(string.indexOf(dg) != -1){
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
					gateway = mc.group();
					System.out.println("默认网关:" + mc.group());
					break;
				}else{
					gateway = "";
					System.out.println("默认网关为空");
				}
			};
			};
			return gateway;
		} 
   
    ///取到当前机器DNS
    public static String getDefaultDNS() throws IOException { 
    	String DNS = null;
    	String os = System.getProperties().getProperty("os.name");	//得到操作系统 xp
		Process pro = Runtime.getRuntime().exec("ipconfig -all");
		BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
		List<String> rowList = new ArrayList();
		String temp;
		while((temp = br.readLine()) != null){
			rowList.add(temp );
		}
		boolean state=false;
		for (String string : rowList) {
			String dg =  os.equals("Windows XP") ? "DNS Servers" : "DNS 服务器" ; //这里只判断了win7个xp 
			if(string.indexOf(dg) != -1 || state){
				
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
					System.out.println("DNS:" + mc.group());
					if(state){
						DNS =DNS+","+mc.group();
						state=false;
					}else{
						state=true;
						DNS = mc.group();
					}
					
					//break;
				}else{
				}
			};
			};
			return DNS;
		} 
	//取到当前网络信息存入LIST
    public static List getNetList() throws IOException { 
    	ArrayList<Map> list = new ArrayList<Map>();
		String s = getNet();
		String[] b = s.split("\\|");
		for(int i=0;i<b.length;i++){
			HashMap<String , String> map = new HashMap<String , String>(); 
			if(b[i].length()>4){
				String[] c = b[i].split(",");
				for(int i1=0;i1<c.length;i1++){
					String[] d = c[i1].split(":");
					for(int i11=0;i11<d.length;i11++){
						map.put(d[0], d[1]);
					}
				}
			}
			if(b[i].length()>4){
				list.add(map);
			}
		}
		System.out.println("list.size()===="+list.size());
		for(int j=0;j<list.size();j++){
			System.out.println(j+"---list.get(j)==="+list.get(j));
		}
		return list;
    }
    
	//取到当前机器网络连接信息
    public static String getNet() throws IOException { 
    	ArrayList<Map> list = new ArrayList<Map>();
    	String DNS = null;
    	String name =null;
    	String xx =null;
    	String os = System.getProperties().getProperty("os.name");	//得到操作系统 xp
		Process pro = Runtime.getRuntime().exec("ipconfig -all");
		BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream(),"GBK"));  
		List<String> rowList = new ArrayList();
		String temp;
		while((temp = br.readLine()) != null){
			rowList.add(temp );
		}
		boolean state=false;
		for (String string : rowList) {
			String dg =  os.equals("Windows XP") ? "DNS Servers" : "DNS 服务器" ; //这里只判断了win7个xp 
			String dg1 =  os.equals("Windows XP") ? "Ethernet adapter" : "以太网适配器" ; //这里只判断了win7个xp 
			String dg8 =  os.equals("Windows XP") ? "" : "隧道适配器" ; //这里只判断了win7个xp 
			String dg2 =  os.equals("Windows XP") ? "Description" : "描述" ; //这里只判断了win7个xp 
			String dg4 =  os.equals("Windows XP") ? "Physical Address" : "物理地址" ; //这里只判断了win7个xp 
			String dg5 =  os.equals("Windows XP") ? "IP Address" : "IPv4 地址" ; //这里只判断了win7个xp 
			String dg6 =  os.equals("Windows XP") ? "Subnet Mask" : "子网掩码" ; //这里只判断了win7个xp 
			String dg7 =  os.equals("Windows XP") ? "Default Gateway" : "默认网关" ; //这里只判断了win7个xp 
			String dg3 =  os.equals("Windows XP") ? "                    " : "                   " ; //这里只判断了win7个xp
			if(string.indexOf(dg1) != -1 || state){	
				if(os.equals("Windows XP")){
					System.out.println("连接名:"+string.substring(17, string.length()-1));
					xx=xx+"|join:"+string.substring(17, string.length()-1);
				}else{
					System.out.println("连接名:"+string.substring(7, string.length()-1));
					xx=xx+"|join:"+string.substring(7, string.length()-1);
				}
				state=false;
			};
			
			if(string.indexOf(dg2) != -1 || state){	
				System.out.println("网卡描述:"+string.substring(string.indexOf(":")+2, string.length()));
				xx=xx+","+"description:"+string.substring(string.indexOf(":")+2, string.length());
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
					if(state){
						name =name+","+mc.group();
						state=false;
					}else{
						state=true;
						name = mc.group();
					}
					
					//break;
				}else{
				}
			};
			
			if(string.indexOf(dg4) != -1 || state){	
				xx=xx+","+"mac:"+string.substring(string.indexOf(":")+2, string.length());
				System.out.println("物理地址:"+string.substring(string.indexOf(":")+2, string.length()));
			};
			
			if(string.indexOf(dg5) != -1 || state){	
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
						xx=xx+","+"ip:"+mc.group();
						state=false;
						System.out.println("IP地址:"+mc.group());
					//break;
				}else{
				}
			};
			
			if(string.indexOf(dg6) != -1 || state){	
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
						xx=xx+","+"netmask:"+mc.group();
						state=false;
						System.out.println("子网掩码:"+mc.group());
					//break;
				}else{
				}
			};
			
			if(string.indexOf(dg7) != -1 || state){	
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
						xx=xx+","+"getway:"+ mc.group();
						state=false;
						System.out.println("默认网关:"+mc.group());
					//break;
				}else{
				}
			};
			
			if(string.indexOf(dg) != -1 || state){	
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
						xx=xx+","+"dns1:"+ mc.group();
						state=false;
						DNS = mc.group();
						System.out.println("首选DNS:"+mc.group());
					//break;
				}else{
				}
			};
			
			if(string.indexOf(dg3) != -1 || state){	
				Matcher mc = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher(string);
				if(mc.find()){
						xx=xx+","+"dns2:"+mc.group();
						state=false;
						DNS =DNS+","+mc.group();
						System.out.println("备用DNS:"+mc.group());
					//break;
				}else{
				}
			};
			};
			return xx;
		} 
    
    public String toString(){
        String localDataStr="";
        //Wait modify
        return "";
    }
}

//设置计算机IP 地址
private void setIP(HttpServletRequest request,
			HttpServletResponse response) throws IOException  {
		String join = request.getParameter("join");
		String newip = request.getParameter("newip");
		String netmask = request.getParameter("netmask");
		String geteway = request.getParameter("geteway");
		String dns1 = request.getParameter("dns1");
		String dns2 = request.getParameter("dns2");
		System.out.println("更换系统连接名称为--"+join+"--更换系统IP为"+newip+"  子网掩码为"+netmask+"  默认网关为"+geteway+"  首选DNS为"+dns1+"  备用DNS为"+dns2);
			String cmdResult="";
			String cmdResult1="";
			String cmdResult2="";
			try{
				String str=null;
				String str1=null;
				String str2=null;
				String cmd="netsh    interface    ip    set    addr    "+join+"    static    "
					+ newip + "  "+ netmask + "  "+ geteway + "   1";
				Process pc=Runtime.getRuntime().exec(cmd);
				InputStreamReader is=new InputStreamReader(pc.getInputStream());
				LineNumberReader line=new LineNumberReader(is);
				while((str=line.readLine())!=null){
					cmdResult+=str;
				}
				line.close();
				
				if (dns1 != null && !dns1.equals("")) {
					String cmd1 = "netsh interface ip set dns "+join+" static "
							+ dns1;
					Process pc1 = Runtime.getRuntime().exec(cmd1);
					InputStreamReader is1 = new InputStreamReader(
							pc1.getInputStream());
					LineNumberReader line1 = new LineNumberReader(is1);
					while ((str1 = line1.readLine()) != null) {
						cmdResult1 += str1;
					}
					line1.close();
				}

				if (dns2 != null && !dns2.equals("")) {
					String cmd2 = "netsh interface ip add dns "+join+" addr="
							+ dns2 + "  index=2";
					Process pc2 = Runtime.getRuntime().exec(cmd2);
					InputStreamReader is2 = new InputStreamReader(
							pc2.getInputStream());
					LineNumberReader line2 = new LineNumberReader(is2);
					while ((str2 = line2.readLine()) != null) {
						cmdResult2 += str2;
					}
					line2.close();
				}
				System.out.println("更换IP情况:"+cmdResult);
				System.out.println("更换首选DNS情况:"+cmdResult1);
				System.out.println("更换备用DNS情况:"+cmdResult2);
			}catch(Exception e){
				cmdResult=e.toString();
			}
		    if(cmdResult.indexOf("确定")>-1||cmdResult.equals("")){
		    	if(cmdResult1.indexOf("确定")>-1||cmdResult1.equals("")){
		    		if(cmdResult2.indexOf("确定")>-1||cmdResult2.equals("")){
			    		response.getWriter().write("true");
			    	}else{
			    		response.getWriter().write("更换备用DNS:"+cmdResult2);
			    	}
		    	}else{
		    		response.getWriter().write("更换首选DNS情况DNS:"+cmdResult1);
		    	}
		    }else{
		    	response.getWriter().write("更换IP情况:"+cmdResult);
		    }
	}
C# WPF openFileDialog的使用 上传Excel c# wpf openfiledialog
//一:浏览文件:(Excel) 
private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            //Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "Excel Files|*.xlsx;*.xls";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = ofd.FileName;
            }
            else {
                txtPath.Text = "";
            }
        }

//二:上传Excel到数据库
  string filename = txtPath.Text;
                        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                        Microsoft.Office.Interop.Excel.Workbook workbook;
                        Microsoft.Office.Interop.Excel.Worksheet worksheet;
                        object oMissing = System.Reflection.Missing.Value;//相当于null
                        workbook = excel.Workbooks.Open(filename, oMissing, oMissing, oMissing,oMissing,oMissing);
                        worksheet = (Worksheet)workbook.Worksheets[1];
                        int rowCount = worksheet.UsedRange.Rows.Count;
                        int colCount = worksheet.UsedRange.Columns.Count;
                        Microsoft.Office.Interop.Excel.Range range1;
                                                
                        for (int j = 1; j < rowCount; j++)
                        {
                            dutyInfo duty = new dutyInfo();
                            for (int i = 0; i < colCount; i++)
                            {
                                range1 = worksheet.Range[worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]];
                                try
                                {
                                    if (range1 != null)
                                    {
                                        switch (i)
                                        {
                                            case 0://日期格式
                                                if (range1.Value2 != null) {
                                                    duty.dutyTime = DateTime.FromOADate(double.Parse(range1.Value2.ToString()));
                                                }
                                                break;
                                            case 1:
                                                if (range1.Value2 != null) {
                                                    duty.dutyLeader = range1.Value2.ToString();
                                                }
                                                break;
                                            case 2:
                                                if (range1.Value2 != null) {
                                                    duty.dutyMan = range1.Value2.ToString();
                                                }
                                                break;
                                            case 3:
                                                if (range1.Value2 != null) {
                                                    duty.weatherImg = range1.Value2.ToString();
                                                }
                                                break;
                                            case 4://图片格式
                                                range1.Select();
                                                //将单元格复制到剪贴板中  xlBitmap Bitmap (.bmp, .jpg, .gif).  xlPicture  picture (.png, .wmf, .mix). 
                                                range1.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);//COPY到内存 .bmp, .jpg, .gif
                                                //MessageBox.Show("copy 到 内存 bitmap" + System.Windows.Forms.Clipboard.ContainsImage());
                                                if (System.Windows.Forms.Clipboard.ContainsImage())
                                                {
                                                    System.Drawing.Image image = System.Windows.Forms.Clipboard.GetImage();
                                                    //保存到对象中
                                                    MemoryStream ms = new MemoryStream();
                                                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                                                    byte[] imgByte = ms.ToArray();
                                                    duty.leaderImg = imgByte;
                                                }
                                                else {
                                                    range1.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlPicture);//COPY到内存 .png, .wmf, .mix
                                                    //MessageBox.Show("copy 内存 Pic " + System.Windows.Forms.Clipboard.ContainsImage());
                                                    if (System.Windows.Forms.Clipboard.ContainsImage()) {
                                                        System.Drawing.Image image = System.Windows.Forms.Clipboard.GetImage();
                                                        //保存到对象中
                                                        MemoryStream ms = new MemoryStream();
                                                        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                                                        byte[] imgByte = ms.ToArray();
                                                        duty.leaderImg = imgByte;
                                                    }
                                                }

                                                break;
                                        }
                                    }
                                }
                                catch (Exception e0)
                                {
                                    MessageBox.Show(e0.Message);
                                    throw new Exception(e0.Message);
                                }
                            }
                            //addDutyList.Add(duty);

                            int id = dutyBll.GetMaxId();
                            duty.ID = id;
                            try
                            {
                                dutyBll.add(duty, duty.leaderImg);
                            }
                            catch (Exception addE) {
                                MessageBox.Show(addE.Message);
                            }
                           
                        }
                        excel.Quit();
C# WPF datagrid 使用 c# wpf datagrid
xaml页面:
<Page x:Class="onwpf.dutyPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:assembly="clr-namespace:System;assembly=mscorlib"
      xmlns:local="clr-namespace:onwpf"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
	Title="dutyPage">
    <Page.Background>
        <ImageBrush ImageSource="/onwpf;component/images/comImg/背景bg.jpg"></ImageBrush>
    </Page.Background>
        <Page.Resources>
          <ObjectDataProvider x:Key="weatherEnum" MethodName="GetValues" 
                            ObjectType="{x:Type assembly:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:WeatherOpt"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Page.Resources>
<DataGrid AutoGenerateColumns="False" Grid.Row="4"  Grid.Column="1"  ColumnWidth="100"  Name="dataGrid1" CanUserResizeColumns="False" CanUserAddRows="False"  Opacity="0.75" FontSize="36"  FontFamily="Adobe Fangsong Std" Foreground="Red" FontWeight="Bold" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
            <!--
            表头居中
            -->
            <DataGrid.ColumnHeaderStyle>
                <Style TargetType="DataGridColumnHeader">
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="FontSize" Value="32" />
                    <Setter Property="FontWeight" Value="Bold"></Setter>
                </Style>
            </DataGrid.ColumnHeaderStyle>

            <DataGrid.Columns>
                <DataGridTextColumn Width="2*"  Header="值班日期" Binding="{Binding dutyTime ,StringFormat='yyyy-MM-dd'}" IsReadOnly="True"/>
                <DataGridTextColumn Width="2*" Header="值班领导" Binding="{Binding dutyLeader}" IsReadOnly="True" />
                <DataGridTextColumn Width="2*" Header="值班人"  Binding="{Binding dutyMan}" IsReadOnly="True" />
              
                <!--下拉列表-->
                <DataGridTemplateColumn Width="2*" Header="天气" x:Uid="Moshi">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox Tag="{Binding ID}" x:Name="cbxList" 
                                       Text="{Binding weatherImg}" 
                                        ItemsSource="{Binding Source={StaticResource weatherEnum}}" SelectionChanged="cbxList_SelectionChanged" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
</page>

cs:
//下拉列表中的值:
 public enum WeatherOpt { 晴, 多云, 阴, 阵雨, 雷阵雨, 雨夹雪, 小雨, 中雨, 大雨, 暴雨, 大暴雨, 特大暴雨, 阵雪, 小雪, 中雪, 大雪, 暴雪, 雾, 冻雨, 沙尘暴, 小雨转中雨, 中雨转大雨, 大雨转暴雨, 暴雨转大暴雨, 大暴雨转特大暴雨, 小雪转中雪, 中雪转大雪, 大雪暴雪, 浮尘, 扬沙, 强沙尘暴 };
   List<Maticsoft.Model.dutyInfo> listdi = di.GetModelList(conStr);
   dataGrid1.ItemsSource = listdi;


C# WPF window 动态添加TabItem wpf,tabcontrol,tabitem
Main.xaml:
<Window x:Class="onwpf.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowStyle="None" Icon="/onwpf;component/images/comImg/menu.png" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Background="#FF00004B">
    <Window.Resources>
    </Window.Resources>
    <TabControl   Name="tc" Padding="0">
        <TabItem Header="值班系统主页" Name="tabItemMain">
             <Button Height="180" HorizontalAlignment="Left" Margin="60,60,0,0" Name="btn_Duty" VerticalAlignment="Top" Width="190" Style="{StaticResource buttonTemplate}" Click="btn_Duty_Click" />
               
        </TabItem>
    </TabControl>
</Window>

Main.xaml.cs
 private void btn_Duty_Click(object sender, RoutedEventArgs e)
        {
            try {
                bool isExist = false;
                TabItem t = null;
                foreach (TabItem ti in tc.Items)
                {
                    if (ti.Header.ToString().Equals("值班管理"))
                    {
                        isExist = true;
                        t = ti;
                    }
                }
                if (isExist)
                {
                    tc.SelectedItem = t;
                }
                else
                {
                    TabItem tb = new TabItem();
                    tb.Header = "值班管理";
                    Frame f = new Frame();
                    f.Source = new Uri("dutyPage.xaml", UriKind.Relative);////dutyPage.xaml 是新建的page
                    tb.Content = f;
                    tc.Items.Add(tb);
                    tc.SelectedItem = tb;
                }
            }catch(Exception e0){
                MessageBox.Show(e0.Message);
            }
        }
C# WPF 基础知识- 窗口全屏 c#,winform 全屏
 public static class ExpendMethod
    {
        private static Window _fullWindow;
        private static WindowState _windowState;
        private static WindowStyle _windowStyle;
        private static bool _windowTopMost;
        private static ResizeMode _windowResizeMode;
        private static Rect _windowRect;

        /// <summary>
        /// 进入全屏    
        /// </summary>
        /// <param name="window"></param>
        public static void GoFullscreen(this Window window)
        {
            //已经是全屏 
            if (window.IsFullscreen()) return;

            //存储窗体信息       
            _windowState = window.WindowState;
            _windowStyle = window.WindowStyle;
            _windowTopMost = window.Topmost;
            _windowResizeMode = window.ResizeMode;
            _windowRect.X = window.Left;
            _windowRect.Y = window.Top;
            _windowRect.Width = window.Width;
            _windowRect.Height = window.Height;


            //变成无边窗体 
            window.WindowState = WindowState.Normal;//假如已经是Maximized,就不能进入全屏,所以这里先调整状态 
            window.WindowStyle = WindowStyle.None;
            window.ResizeMode = ResizeMode.NoResize;
            window.Topmost = true;//最大化后总是在最上面 

            //获取窗口句柄 
            var handle = new WindowInteropHelper(window).Handle;
            //获取当前显示器屏幕
            Screen screen = Screen.FromHandle(handle);

            //调整窗口最大化,全屏的关键代码就是下面3句 
            window.MaxWidth = screen.Bounds.Width;
            window.MaxHeight = screen.Bounds.Height;
            window.WindowState = WindowState.Maximized;

            //解决切换应用程序的问题
            window.Activated += new EventHandler(window_Activated);
            window.Deactivated += new EventHandler(window_Deactivated);
            //记住成功最大化的窗体 
            _fullWindow = window;
        }
        static void window_Deactivated(object sender, EventArgs e)
        {
            var window = sender as Window;
            window.Topmost = false;
        }
        static void window_Activated(object sender, EventArgs e)
        {
            var window = sender as Window;
            window.Topmost = true;
        }

        /// <summary>
        /// 退出全屏
        /// </summary>
        /// <param name="window"></param>
        public static void ExitFullscreen(this Window window)
        {
            //已经不是全屏无操作 
            if (!window.IsFullscreen()) return;
            //恢复窗口先前信息,这样就退出了全屏 
            window.Topmost = _windowTopMost;
            window.WindowStyle = _windowStyle;
            window.ResizeMode = ResizeMode.CanResize;//设置为可调整窗体大小 
            window.Left = _windowRect.Left;
            window.Width = _windowRect.Width;
            window.Top = _windowRect.Top;
            window.Height = _windowRect.Height;
            window.WindowState = _windowState;//恢复窗口状态信息 
            window.ResizeMode = _windowResizeMode;//恢复窗口可调整信息 
            //移除不需要的事件 
            window.Activated -= window_Activated;
            window.Deactivated -= window_Deactivated;
            _fullWindow = null;
        }

        /// <summary>
        /// 窗体是否在全屏状态
        /// </summary>
        /// <param name="window"></param>
        /// <returns></returns>
        public static bool IsFullscreen(this Window window)
        {
            if (window == null)
                throw new ArgumentNullException("window");
            return _fullWindow == window;
        }
}

二:通过设置winForm的属性,使Form 全屏
WindowStyle 设置边框样式:None(边界不不出现),Single borderWindow(只显示上面的边界),ThreeDBorderWindow、ToolWindow

应用:
 public partial class Main : System.Windows.Window
    {
        public Main()
        {
            InitializeComponent();
            ExpendMethod.GoFullscreen(this);
            AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);

            string conStr = string.Format("Data Source={0}\\dutyDB.db3;Version=3;", AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
           //连接数据库,绝对路径
            Maticsoft.DBUtility.DbHelperSQLite.connectionString = conStr;  
        }

        //按Esc 键退出全屏
        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                 ExpendMethod.ExitFullscreen(this);
            }
        }
}
JS 时间 加减一时间段 时间 date
function getOpenBidEndDate(){
	        var sDate=document.getElementById("openbidStartTimeString").value;
	        if(sDate==null || sDate==""){
	         alert("请先填写开标开始时间");
	         document.getElementById("openbidEndureTime").value="";
	         return ;
	        }
	        var sDate1=sDate.replace(/-/ig,'/');
		    var sDate2=new Date(sDate1);
		    
		    var evalDuring=document.getElementById("openbidEndureTime").value;
		     sDate2.setMinutes(sDate2.getMinutes()+evalDuring*60);
		     var MM=sDate2.getMonth()+ 1;
		     var dd=sDate2.getDate();
		     var hh=sDate2.getHours();
		     var mm=sDate2.getMinutes();
		     
		     if(MM.toString().length==1){
		      MM="0"+MM;
		     }
		     if(dd.toString().length==1){
		      dd="0"+dd;
		     }
		     if(hh.toString().length==1){
		      hh="0"+hh;
		     }
		     if(mm.toString().length==1){
		      mm="0"+mm;
		     }
		    var endDate=sDate2.getYear()+"-"+MM+"-"+dd+" "+hh+":"+mm;
		    document.getElementById("openbidEndTimeString").value=endDate; 
	      } 

页面:
 <input id="openbidStartTimeString"  name="openbidStartTimeString"   size="30" onclick="<%="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'})"%>"  onPropertyChange="getPushTime()" /> 	
		
		持续时间: <input type="text" id="openbidEndureTime" name="openbidEndureTime" size="5"  onkeyup="clearNoNum(this)" onblur="getOpenBidEndDate()"/>(H)
		 <s:hidden id="openbidEndTimeString"  name="openbidEndTimeString" theme="simple"></s:hidden>
js 只能输入数字、小数 js代码
1、function clearNoNum(obj){
 	      obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
 	      obj.value = obj.value.replace(/^\./g,"");  //验证第一个字符是数字而不是.
  	     obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.
  	     obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	    }
<input type="text" id="openbidEndureTime" name="openbidEndureTime" size="5" class='required' onkeyup="clearNoNum(this)" ></input>
2、//只能输入整数
function onlyNum() 
		  { 
		  if(!(event.keyCode==46)&&!(event.keyCode==8)&&!(event.keyCode==37)&&!(event.keyCode==39)) 
		  if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105))) 
		  event.returnValue=false; 
		  } 

  <input type="text" id="openbidEndureTime" name="openbidEndureTime" onKeyDown="onlyNum();"></input>
SSH 连接多个数据库 并且能够动态切换 spring 动态切换数据库
/**
* 在项目中,有时遇到连接多个数据库的情况,并且根据用户的操作不同,连接不同的数据库,这时,就要动态切换数据库。环境:SSH(利用到了Hibernate 注解)。
*Spring2.x的版本中采用Proxy模式,就是我们在方案中实现一个虚拟的数据源,并且用它来封装数据源选择逻辑,这样*就可以有效地将数据源选择逻辑从Client中分离出来。Client提供选择所需的上下文(因为这是Client所知道的),**由虚拟的DataSource根据Client提供的上下文来实现数据源的选择。 
*具体的实现就是,虚拟的DataSource仅需继承AbstractRoutingDataSource实现
*determineCurrentLookupKey()在其中封装数据源的选择逻辑。  步骤如下:
*/
//动态配置多数据源(用类表示)
public class DataSourceConst {
public static final String Admin="admin";//admin和配置文件中的<entry value-ref="adminDataSource" key="admin"></entry> 对应
public static final String User="user";//user和配置文件中的 <entry value-ref="userDataSource" key="user"></entry> 对应
}

 /**
 * 建立一个获得和设置上下文环境的类,主要负责改变上下文数据源的名称
 * */
public class DataSourceContextHolder {
	private static final ThreadLocal contextHolder = new ThreadLocal();// 线程本地环境
	// 设置数据源类型
	public static void setDataSourceType(String dataSourceType) {
		contextHolder.set(dataSourceType);
	}
	// 获取数据源类型
	public static String getDataSourceType() {
		return (String) contextHolder.get();
	}
	// 清除数据源类型
	public static void clearDataSourceType() {
		contextHolder.remove();
	}
}

/**
 * 建立动态数据源类,返回一个Object,一般是返回字符串
 * */
public class DynamicDataSource extends AbstractRoutingDataSource {
	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceContextHolder.getDataSourceType();
	}
}

//编写spring的配置文件配置多个数据源 applicationContext.xml 部分代码

<!-- 读取并设置数据库相关属性 -->
 <bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>   <!--连接数据库的信息(数据库信息已固定)-->
				<value>classpath:db.properties</value>
				<value>classpath:newdb.properties</value>
			</list>
		</property>
	</bean>
<!-- 配置多个数据源 -->
<!-- 数据源相同部分 -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="parentDataSource">
<property name="driverClassName" value="${drivers}" />
</bean>
<!-- 198上的数据库 -->
<bean parent="parentDataSource" id="adminDataSource">
<property name="url" value="${DefaultDBUrl.url}" />
<property name="username" value="${DefaultDBUrl.user}" />
<property name="password" value="${DefaultDBUrl.password}" />
</bean>
<!-- 199 上的数据库 -->
<bean parent="parentDataSource" id="userDataSource">
<property name="url" value="${newDBUrl.url}" />
<property name="username" value="${newDBUser.user}" />
<property name="password" value="${newDBPassword.password}" />
</bean>
<!-- 编写spring配置文件 配置多数据源映射关系 -->
<bean class="DyDataSource.DynamicDataSource" id="dataSource">
<property name="targetDataSources">
 <map key-type="java.lang.String">
  <entry value-ref="adminDataSource" key="admin"></entry>
  <entry value-ref="userDataSource" key="user"></entry>
 </map>
</property>
<property name="defaultTargetDataSource" ref="adminDataSource"></property>
</bean>
<!-- sessionFactory 配置 -->
<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory">
<property name="dataSource">
 <ref local="dataSource"></ref>
</property>
<!-- 为sessionFactory设置Hibernate属性 -->
	<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					<!-- SQLServer:org.hibernate.dialect.SQLServerDialect -->
					<!-- MySql -->
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<!-- 如果做了下面的配置,将影响事务配置,servcie中事务不会回滚, -->
				<!--<prop key="hibernate.connection.release_mode">
					after_transaction
				</prop>-->
			</props>
		</property>
		<property name="packagesToScan">
			<list>
				<value>com.luguang.model</value>
			</list>
		</property>
</bean>
//在应用程序中,动态切换数据库
     ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    DataSourceContextHolder.setDataSourceType(DataSourceConst.Admin);
    LgispUser user0=new LgispUser();
    user0.setUserAlias("AdminDB 000user");
    user0.setOrgId(1);
    this.lgispUserService.getEntityDao().save(user0);
    DataSourceContextHolder.setDataSourceType(DataSourceConst.User);
    this.lgispUserService.getEntityDao().save(user0);
于UDP协议的网络编程(使用DatagramSocket发送接收数据) udp网络编程 (datagramsocket)
package socketServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/***
 * UDP 协议传输数据(服务器)
 **/
public class UdpServer {
	public static final int PORT = 30001;
	// 定义每个数据报的最大大小为4K
	public static final int DATA_LEN = 4096;
	// 定义该服务器使用的DatagramSocket
	private DatagramSocket socket = null;
	// 定义接收网络数据的字节数组
	byte[] inBuff = new byte[DATA_LEN];
	// 以指定字节数组组建准备接受数据的DatagramPacket对象
	private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
	// 定义一个用于发送的DatagramPacket
	private DatagramPacket outPacket;
	// 定义一个字符串数组,服务器发送该数组的元素
	String[] books = new String[] { "轻量级J2EE企业应用实战", "基于J2EE的Ajax宝典",
			"Struts2权威指南", "ROR敏捷开发最佳实践" };

	public void init() throws IOException {
		try {
			// 创建DatagramSocket 对象
			socket = new DatagramSocket(PORT);
			for (int i = 0; i < 1000; i++) {
				// 读取Socket中的数据,读到的数据放在inPacket 所封装的字节数组里
				socket.receive(inPacket);
				// 判断inPacket.getData()和inBuff是否是同一个数组
				System.out.println("---判断inPacket.getData()和inBuff是否是同一个数组 -----------" + inBuff == inPacket
						.getData() + "--------------");
				// 将接收到的内容转成字符串后输出
				System.out.println("服务器端显示客户端输入的内容:"+new String(inBuff, 0, inPacket.getLength()));
				// 从字符串数组中取出一个元素作为发送数据
				byte[] sendData = books[i % 4].getBytes();
				// 以指定字节数组作为发送数据,以刚接受到的DatagramPacket的源SocketAddress作为目标SocketAddress
				// 创建DatagramPacket
				outPacket = new DatagramPacket(sendData, sendData.length,
						inPacket.getSocketAddress());
				// 发送数据
				socket.send(outPacket);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} finally {
			if (socket != null) {
				socket.close();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		new UdpServer().init();
	}
}

package socketClient;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class UdpClient {

	/**
	 *  UDP 协议传输数据(客户端)
	 */
	//定义发送数据报的目的地
	public static final int DEST_PORT=30001;
	public static final String DEST_IP="127.0.0.1";
	private static final int DATA_LEN=4096;
	//定义该客户端使用的DatagramSocket
	private DatagramSocket socket=null;
	//定义接收网络数据的字节数据
	byte[] inBuff=new byte[DATA_LEN];
	//以指定字节数组准备接受数据的DatagramPacket对象
	private DatagramPacket inPacket=new DatagramPacket(inBuff,inBuff.length);
	private DatagramPacket outPacket=null;
	
	public void init() throws IOException{
		try {
			//使用随机端口
			socket=new DatagramSocket();
			//初始化发送用的DatagramPacket
			outPacket=new DatagramPacket(new byte[0], 0,InetAddress.getByName(DEST_IP),DEST_PORT);
			//键盘输入流
			Scanner scan=new Scanner(System.in);
			while(scan.hasNextLine()){
				//将输入的一行字符串转换为字节数组
				byte[] buff=scan.nextLine().getBytes();
				//填充发送用的数据
				outPacket.setData(buff);
			     // 发送数据报
				socket.send(outPacket);
				//读取socket中的数据,读到的数据放在inPacket所封装的字节数据里面
				socket.receive(inPacket);
				System.out.println("-------服务器返回的数据:"+new String(inBuff,0,inPacket.getLength())+"------");
			}	
		} catch (SocketException e) {
			e.printStackTrace();
		}finally{
			if(socket!=null){
				socket.close();
			}
		}	
	}
	public static void main(String[] args) throws IOException {
		new UdpClient().init();
	}
}
/**注:
 * 客户端和服务器端的代码基本相似。客户端和服务器端的唯一区别在于:服务器所在IP地址和端口号是固定的,
 * 所以客户端可以直接将该数据报发送给服务器,而服务器则需要根据接收到的数据库来决定将反馈数据报的目的地。
 */
java 利用URL下载网络资源 url 网络资源 (java疯狂讲义)
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.RandomAccess;

import javax.swing.plaf.basic.BasicScrollPaneUI.HSBChangeListener;

/**
 * 定义下载从start到end的内容的线程
 * */
public class DownThread  extends Thread{
    //定义字节数组的长度
	private final int BUFF_LEN=32;
	private long start;//定义下载的起始点
	private long end;//定义下载的结束点
	private InputStream is;//下载资源对应的输入流
	private RandomAccessFile raf;//将下载到字节输出到raf
	public DownThread(long start,long end,InputStream is,RandomAccessFile raf){
		System.out.println(start+"-------->"+end);
		this.start=start;
		this.end=end;
		this.is=is;
		this.raf=raf;
	}
	public void run(){
		try {
			is.skip(start);
			raf.seek(start);
			//定义读取输入流内容的缓存数组
			byte[] buff=new byte[BUFF_LEN];
			//本线程负责下载资源的大小
			long contentLen=end-start;
			//定义最多需要读取几次就可以完成本线程的下载
			long times=contentLen/BUFF_LEN+4;
			//实际读取的字节数
			int hasRead=0;
			for(int i=0;i<times;i++){
				hasRead=is.read(buff);
				if(hasRead<0){
					break;
				}
				raf.write(buff,0,hasRead);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try{
				if(is!=null){
					is.close();
				}
				if(raf!=null){
					raf.close();
				}
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}		
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MutilDown {
public static void main(String[] args) throws IOException{
	final int DOWN_THREAD_NUM=4;
	final String OUT_FILE_NAME="down.jpg";
	InputStream[] isArr=new InputStream[DOWN_THREAD_NUM];
	RandomAccessFile[] outArr=new RandomAccessFile[DOWN_THREAD_NUM];
	try {
		//创建一个URL对象
		URL url=new URL("http://images.china-pub.com/ebook35001-40000/35850/shupi.jpg");
	    //以此URL对象打开第一个输入流
		isArr[0]=url.openStream();
		long fileLen=getFileLength(url);
		System.out.println("--------------网络资源的大小:"+fileLen+"------------");
		//以输出文件名创建第一个RandomAccessFile 输出流
		outArr[0]=new RandomAccessFile(OUT_FILE_NAME,"rw");
		//创建一个与下载资源相同大小的空文件
		for(int i=0;i<fileLen;i++){
			outArr[0].write(0);
		}
		//每线程应该下载的字节数
		long numPerThred=fileLen/DOWN_THREAD_NUM;
		//整个资源整除后剩下的余数
		long left=fileLen%DOWN_THREAD_NUM;
		for(int i=0;i<DOWN_THREAD_NUM;i++){
			//为每个线程打开一个输入流、一个RandomAccessFile 对象
			//让每个线程分别负责下载资源的不同部分
			if(i!=0){
				//以URL打开多个输入流
				isArr[i]=url.openStream();
				outArr[i]=new RandomAccessFile(OUT_FILE_NAME, "rw");
			}
			//分别启动多个进程创建多个RandomAccessFile 对象
			if(i==DOWN_THREAD_NUM-1){
				//最后一个线程下载指定numPerThred+left个字节
				new DownThread(i*numPerThred, (i+1)*numPerThred+left, isArr[i],outArr[i]).start();
			}else{
				//每个线程负责下载一个的字节
				new DownThread(i*numPerThred, (i+1)*numPerThred, isArr[i],outArr[i]).start();
			}
			}
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
// 定义获取指定网络资源的长度的方法
private static long getFileLength(URL url) {
	long length=0;
	try {
		//打开盖URL对应的URLConnection(URLConnection表示应用程序和URL之间的通信链接。
		//程序可以通过URLConnection实例向该URL发送请求,读取URL引用的资源)
		URLConnection con=url.openConnection();
		//获取连接URL资源的长度
		long size=con.getContentLength();
		length=size;
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return length;
}
}
java 获取系统当前时间 timestamp calendar simpledateformat
//一:获取系统当前时间:
  Timestamp ts=new Timestamp(System.currentTimeMillis());
//或者
  SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
  String startTime=format.format(new Date());
//二:获取系统当前时间(或者前一天、后一天时间)
  Calendar c=Calendar.getInstance();
  c.add(Calendar.DAY_OF_MONTH,-1);//前一天(1:后一天)
  SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");//日期格式(2012-10-16):yyyy-MM-dd HH:mm:ss
  String time=format.format(c.getTime());
  
  
读取Excel 数据,添加到数据库 excel数据 添加到数据库
//一:jsp页面 :表单
<form id="form1" action="<%=path%>/custInfo/readReport"method="post" enctype="multipart/form-data">
上传文件:<input id="fileExl" class="inputbox" type="file" name="file" size="200" />	 <input type="submit" class="btn" value="上传" name="btnSave"onClick="return limitAttach()" />
</form>
//后台 代码 
Controller 中:
// 读取Excel中的数据,插入数据库
	@RequestMapping(value = "/readReport", method = RequestMethod.POST)
	public ModelAndView getReadRepost(@RequestParam MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Custinfo custinfo = new Custinfo();
		try {
			List<Custinfo> list = this.custinfoService.readReport(file
					.getInputStream());
			this.custinfoService.insertCustinfo(list);
			request.setAttribute("resultMessage0", "导入数据成功!");
		} catch (IOException e) {
			request.setAttribute("resultMessage0", "导入数据失败!可能是Excel表格数据不正确");
		} catch (Exception ex) {
			request.setAttribute("resultMessage0", "导入数据失败!可能是Excel表格数据不正确");
		}
		return new ModelAndView("custInfo/addCustInfo", "custinfo", custinfo);
	}

Service 中:

    /**
	 * 读取报表
	 */
	public List<Custinfo> readReport(InputStream inp) {
		List<Custinfo> custList = new ArrayList<Custinfo>();
		try {
			Workbook wb = WorkbookFactory.create(inp);
			Sheet sheet = wb.getSheetAt(0);// 取得第一个sheets
			// 从第 yi行开始读取数据
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Custinfo cust = new Custinfo();
				Custinfo custAdd = new Custinfo();
				Row row = sheet.getRow(i);
				if (row == null) {
					// row 为空,不处理
					continue;
				}
				for (int j = 0; j < row.getLastCellNum(); j++) {
					Cell cell = row.getCell(j);// 获得单元格(cell)对象
					// 转换接收的单元格
					String cellStr = null;
					cellStr = ConvertCellStr(cell, cellStr);
					// 将一个单元格的数据添加至一个对象
					custAdd = addingCust(j, cust, cellStr);
				}
				custList.add(custAdd);
			}

		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inp != null) {
				try {
					inp.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("没有数据流!");
			}
		}
		return custList;
	}

	/**
	 * 把单元格内的类型转换至String类型
	 */
	private String ConvertCellStr(Cell cell, String cellStr) {
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			// 读取String
			cellStr = cell.getStringCellValue().toString();
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			// 得到Boolean对象的方法
			cellStr = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_NUMERIC:
			// 先看是否是日期格式
			if (DateUtil.isCellDateFormatted(cell)) {
				// 读取日期格式
				// cellStr = cell.getDateCellValue().toString();
				long year = cell.getDateCellValue().getYear();
				long mon = cell.getDateCellValue().getMonth()+1;
				long day = cell.getDateCellValue().getDate();
				long hour = cell.getDateCellValue().getHours();
				long min = cell.getDateCellValue().getMinutes();
				int s = cell.getDateCellValue().getSeconds();
				year = 1900 + year;
				cellStr = year + "-" + mon + "-" + day + " " + hour + ":" + min
						+ ":" + s;
			} else {
				// 读取数字
				cellStr = String.valueOf(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_FORMULA:
			// 读取公式
			cellStr = cell.getCellFormula().toString();
			break;
		}
		return cellStr;
	}

	/**
	 * 读取报表的数据后批量插入
	 */
	public void insertCustinfo(List<Custinfo> list) {
		this.custinfoDao.saveAll(list);
	}

	/**
	 * 获得单元格的数据添加至Custinfo
	 * 
	 * @param j
	 *            列数
	 * @param Custinfo
	 *            添加对象
	 * @param cellStr
	 *            单元格数据
	 * @return
	 */
	private Custinfo addingCust(int j, Custinfo cust, String cellStr) {
		switch (j) {
		case 0:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setCustname(cellStr);
			}
			break;
		case 1:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setIdentitycard(cellStr);
			}
			break;
		case 2:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setRprno(cellStr);
			}
			break;
		case 3:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setBankacc(cellStr);
			}
			break;
		case 4:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setBankname(cellStr);
			}
			break;
		case 5:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setAddress(cellStr);
			}
			break;
		case 6:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setAggregate(BigDecimal.valueOf(Double
						.parseDouble(cellStr)));
			}
			break;
		case 7:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setIntegall(BigDecimal.valueOf(Double.parseDouble(cellStr)));
			}
			break;
		case 8:
			if (cellStr != null && !cellStr.equals("")) {
				cust.setFoodsubsidy(BigDecimal.valueOf(Double
						.parseDouble(cellStr)));
			}
			break;

		case 9:
			if (cellStr != null && !cellStr.equals("")) {
				SimpleDateFormat df1 = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				Date date;
				try {
					date = df1.parse(cellStr);
					Timestamp ts = new Timestamp(date.getTime());
					cust.setCashtme(ts);

				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		}
		return cust;
	}
注:读取excel 数据添加到数据库中,和excel 的格式有关!!!
JFreeChart 报表 jfreechart 报表 柱状和圆饼状
1、饼状图:
 DefaultPieDataset dataset=new DefaultPieDataset();//填充饼状图的数据 集合
 ConnectionProvider cp=((SessionFactoryImplementor)this.lgispEquipmentService.getEntityDao().getHibernateTemplate().getSessionFactory()).getConnectionProvider();
    try{
//sql 语句
 String pointSql=" select count(*) as count,point.point_type from lgisp_point as point , lgisp_equipment as equip, lgisp_terminal as ter  where point.equipment_id=equip.EQUIPMENT_ID and equip.terminal_id=ter.terminal_id group by point.point_type";
     Statement smt=cp.getConnection().createStatement();
     ResultSet rs=smt.executeQuery(pointSql);//查询获得结果集
      double equipCount=0;//设备总数目
      HashMap hashMap=new HashMap();
     while(rs.next()){
      double count=Double.parseDouble(rs.getString(1));
      int type=Integer.parseInt(rs.getString(2));
      equipCount+=count;
      hashMap.put(type, count);
     }
     List<TerManuFacturer> equipManuList=(List<TerManuFacturer>) request.getSession().getAttribute("pointManuList");
     for(TerManuFacturer equip:equipManuList){
      double rate=Double.parseDouble((hashMap.get(equip.getId())).toString())/ equipCount;
            dataset.setValue(equip.getManuName(), rate);
     }// 以上的代码是为生成图的dataset 准备数据

     //通过工厂类生成JFreeChart对象
     JFreeChart chart=ChartFactory.createPieChart("设备——厂家分配图", dataset, true, false, false);
     PiePlot piePlot=(PiePlot)chart.getPlot();
     //防止乱码,多标题重新设备字体(乱码问题借鉴http://chengyue2007.iteye.com/blog/424954 得到解决)
     TextTitle textTitle=chart.getTitle();
     textTitle.setFont(new Font("黑体",Font.PLAIN,20));
     piePlot.setLabelFont(new Font("宋体",0,12));  
     //没有数据时显示的内容
     piePlot.setNoDataMessage("无数据显示");
     piePlot.setCircular(false);
     piePlot.setLabelGap(0.02D);
     OutputStream ostream=response.getOutputStream();
     ChartUtilities.writeChartAsJPEG(ostream, chart,500, 500);
     ostream.flush();
     ostream.close();
    return "输出图的页面";

2、柱状图
 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 
 ConnectionProvider cp =((SessionFactoryImplementor)this.reportService.getEntityDao().getHibernateTemplate().getSessionFactory()).getConnectionProvider();
  try{
   Statement smt = cp.getConnection().createStatement();
   ResultSet rs = smt.executeQuery("sql 语句);
   while(rs.next()){    
    dataset.addValue(Double.parseDouble(rs.getString(1)),rs.getString(2), "") ;
   }
     JFreeChart chart = ChartFactory.createBarChart3D( 
             "图标测试", // 图表标题 
             "班级", // 目录轴的显示标签 
             "分数", // 数值轴的显示标签 
             dataset, // 数据集 
             PlotOrientation.VERTICAL, // 图表方向:水平、垂直 
             true, // 是否显示图例(对于简单的柱状图必须是false) 
             false, // 是否生成工具 
             false // 是否生成URL链接 
             ); 
     OutputStream ostream = response.getOutputStream(); 
     //设定图片的宽为400,高为300,并输出至ostream      
     ChartUtilities.writeChartAsJPEG(ostream, chart, 800, 600); 
     ostream.flush(); 
     ostream.close(); 
    return"输出图的页面;

Global site tag (gtag.js) - Google Analytics