`
inewzone
  • 浏览: 9519 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

java操作excel实现从数据库导入导出(三)

阅读更多
这篇文章继续讲关于java操作excel实现数据库导入导出,这篇涉及关于工具类的设计与,数据工具类的涉及,第一篇文章我有提起,关于这个操作我们可以使用多种方式去描述,第一properties这个格式描述,或者另外一种形式使用xml形式去描述!在这个设计中我也做了一些实验,对于xml的解析,我们这边主要采用DOM4J,我们主要导入DOM4J-1.6.1.jar,xstream-1.3.1.jar还有一个javaxen-1.1-beta-6.jar。
package xls.util;

import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * @author panming
 * @since 2008-5-6
 */
public final class Dom4jUtil {

	/**
     * 取锟斤拷Root锟节碉拷
     * @param document
     * @return
     */
	public static Element getRootElement(Document document) {
        return document.getRootElement();
    }
	
	/**
     * 锟斤拷锟斤拷锟街凤拷芨锟绞斤拷锟絰ml锟斤拷锟斤拷
     * @param document
     * @return
     */
	public String getStringDocument(Document document) {
		 String xmlContent = null;
		 if(document != null){
			 xmlContent = document.asXML();
		 }
		 return xmlContent;   
	}   

    /**
	 * 锟斤拷锟截节碉拷路锟斤拷
	 * @param rootNodeName(锟斤拷诘锟斤拷锟斤拷)
	 * @param childNodeName(锟接节碉拷锟斤拷锟�
	 * @return String(锟斤拷式锟斤拷锟矫碉拷xPath锟斤拷锟�
	 */
	public static String getNodePath(String rootNodeName, String childNodeName) {
		String result = null;
		if (rootNodeName == "" || rootNodeName == null || childNodeName == ""
				|| childNodeName == null) {
			return result;
		}
		result = getNodePath(rootNodeName, childNodeName, null);
		return result;
	}

	/**
	 * 锟斤拷锟截节碉拷路锟斤拷
	 * @param rootNodeName (锟斤拷诘锟斤拷锟斤拷)
	 * @param childNodeName (锟接节碉拷锟斤拷锟�
	 * @param childAttributeName (锟斤拷锟斤拷锟斤拷锟�
	 * @return String (锟斤拷式锟斤拷锟矫碉拷xPath锟斤拷锟�
	 */
	public static String getNodePath(String rootNodeName, String childNodeName,
			String childAttributeName) {
		String result = null;
		if (rootNodeName == "" || rootNodeName == null || childNodeName == ""
				|| childNodeName == null) {
			return result;
		}
		String dima = "/";
		StringBuffer nodePath = new StringBuffer();
		nodePath.append(rootNodeName);
		nodePath.append(dima).append(childNodeName);
		if (childAttributeName != null && childAttributeName != "") {
			nodePath.append(dima).append("@");
			nodePath.append(childAttributeName);
		}
		result = nodePath.toString();
		return result;
	}
	
    /**
	 * 取锟斤拷Document锟斤拷指锟斤拷锟节碉拷锟铰碉拷锟斤拷锟叫节点集锟斤拷
	 * @param document (document锟斤拷锟斤拷)
	 * @param nodeName (锟斤拷式锟斤拷锟矫碉拷xPath锟斤拷锟� "/books/book/@show"
	 * @return List
	 */
    public static List<?> getListByDocument(Document document, String nodeName) {
		if (document == null || nodeName == null || nodeName == "") {
			return null;
		}
		List<?> list = null;
		list = document.selectNodes(nodeName);
		return list;
	}
    
	/**
	 * 取锟矫节点集锟斤拷 
	 * @param filePathAndName(xml锟侥硷拷)
	 * @param nodePath(锟节碉拷xpath锟斤拷锟�
	 * @return List(锟节碉拷锟叫憋拷)
	 * @throws DocumentException
	 */
	public static List<?> getNodeList(String filePathAndName, String nodePath)
			throws DocumentException {
		List<?> list = null;
		if (filePathAndName == null || filePathAndName == ""
				|| nodePath == null || nodePath == "") {
			return list;
		}
		list = getListByDocument(readXMLFile(filePathAndName), nodePath);
		return list;
	}
	
	/**
	 * @param list 
     * @param isAttribute
     * @return String (锟节碉拷锟斤拷锟斤拷锟斤拷缘锟街�
     */  
    public static String getNodeValue(Document document,String nodePath, boolean isAttribute) {
    	List<?> list = document.selectNodes(nodePath);
		if (list != null && !list.isEmpty()) {
			if (isAttribute) {
				return ((Attribute) list.iterator().next()).getText();
			} else {
				return ((Element) list.iterator().next()).getText();
			}
		}
		return null;
	}
    
    /**
	 * @param key
	 * @param value
	 * @throws IOException
	 */  
    public static void setNodeValue(Document document, String nodePath, String value,
			boolean isAttribute) {
		if (isAttribute) {
			List<?> list = document.selectNodes(nodePath);
			((Attribute) list.iterator().next()).setValue(value);
		} else {
			List<?> list = document.selectNodes(nodePath);
			((Element) list.iterator().next()).setText(value);
		}
	}
    
    /**  
     * @param key
     * @param value  
     * @throws IOException  
     */  
    public static void deleteNode(Document document, String parentNodePath, String nodePath) {
		List<?> list = document.selectNodes(parentNodePath);
		if(list != null && !list.isEmpty()){
			Element element = (Element) list.iterator().next();
			List<?> childList = document.selectNodes(parentNodePath + "/" + nodePath);
			if(childList != null && !childList.isEmpty()){
				Element childElement = (Element) childList.iterator().next();
				element.remove(childElement);
			}
		}
	}
    
    /**  
     * @param key  
     * @param value  
     * @throws IOException  
     */  
    public static void deleteAttribute(Document document, String nodePath, String attributeName) {
		List<?> list = document.selectNodes(nodePath);
		if(list != null && !list.isEmpty()){
			Element element = (Element) list.iterator().next();
			List<?> attributeList = document.selectNodes(nodePath + "/@" + attributeName);
			if(attributeList != null && !attributeList.isEmpty()){
                Attribute attribute = (Attribute) attributeList.iterator()   
                        .next();   
                element.remove(attribute); 
			}
		}
	}
    
    /**  
     * @param key  
     * @param stringArray  
     * @param isAttribute  
     * @throws IOException  
     */ 
    public static Element insertNode(Document document, String nodePath,
			String[] stringArray, boolean isAttribute) {
		Element element = null;
		List<?> list = document.selectNodes(nodePath);
		if(list != null && !list.isEmpty()){
			element = (Element) list.iterator().next();
			if(stringArray != null && stringArray.length >= 0){
				if (isAttribute) {
						element = element.addAttribute(stringArray[0], stringArray[1]);
				} else {
					element = element.addElement(stringArray[0]);
					element.setText(stringArray[1]);
				}
			}
		}
		return element;
	}
    
    /**  
     * @param document
     * @param nodePath  xpath锟节碉拷路锟斤拷
     * @param attributeName  锟斤拷锟斤拷锟斤拷锟�     * @param attributeValue 锟斤拷锟斤拷值
     * @return element
     */ 
    public static Element findNodeByAttribute(Document document,
			String nodePath, String attributeName,
			String attributeValue) {
		Element elementTarget = null;
		List<?> list = document.selectNodes(nodePath);
		if(list != null && !list.isEmpty()){
			for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
				Element element = (Element) iterator.next();
				String str = element.attribute(attributeName).getText();
				if (str != null && str.equals(attributeValue)) {
					elementTarget = element;
					break;
				}
			}
		}
		return elementTarget;
	}
    
    /**  
     * @param document  
     * @param nodePath  xpath锟节碉拷路锟斤拷
     * @param attributeArray锟斤拷锟斤拷,0为锟斤拷锟斤拷锟斤拷锟�1为锟斤拷锟斤拷值  
     * @return element
     */ 
    public static Element findNodeByAttribute(Document document,
			String nodePath, String[] attributeArray) {
		Element elementTarget = null;
		List<?> list = document.selectNodes(nodePath);
		if(list != null && !list.isEmpty() && attributeArray != null){
			for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
				Element element = (Element) iterator.next();
				String str = element.attribute(attributeArray[0]).getText();
				if (str != null && str.equals(attributeArray[1])) {
					elementTarget = element;
					break;
				}
			}
		}
		return elementTarget;
	}
    
    /**  
     * @param document
     * @param nodePath  xpath锟节碉拷路锟斤拷
     * @param childNoteValue 锟斤拷锟斤拷值
     * @return element 锟较硷拷锟节碉拷
     */ 
    public static Element findNodeByChild(Document document,
			String nodePath, String childNoteValue) {
		Element elementTarget = null;
		List<?> list = document.selectNodes(nodePath);
		if(list != null && !list.isEmpty()){
			for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
				Element element = (Element) iterator.next();
				String str = element.getText();
				if (str != null && str.equals(childNoteValue)) {
					elementTarget = element.getParent();
					break;
				}
			}
		}
		return elementTarget;
	}
    
    /** 
     * 锟斤拷锟斤拷诘锟�     * @param element
     */ 
    public static void treeWalk(Element element) {
        for (int i = 0, size = element.nodeCount(); i < size; i++) {   
            Node node = element.node(i);   
            if (node instanceof Element) {   
                treeWalk((Element) node);   
            } else {  
            }   
        }   
    }
    
    /**
	 * 锟斤拷锟斤拷XMLWriter
	 * @param filePathAndName
	 * @return XMLWriter
	 * @throws IOException
	 */
    private static XMLWriter getXMLWriter(String fileName)
			throws IOException {
		XMLWriter writer = null;
		writer = new XMLWriter(new FileWriter(new File(fileName)));
		return writer;
	}

	/**
	 * 锟斤拷锟斤拷XMLWriter
	 * @param filePathAndName
	 * @param outputFormat
	 * @return XMLWriter
	 * @throws IOException
	 */
    private static XMLWriter getXMLWriter(String filePathAndName,
			OutputFormat outputFormat) throws IOException {
		XMLWriter writer = null;
		writer = new XMLWriter(new FileWriter(new File(filePathAndName)),outputFormat);
		return writer;
	}
	
    /**
	 * 锟斤拷GBK锟斤拷式锟斤拷写锟侥硷拷
	 * @param filePathAndName
	 * @param document
	 * @return boolean
     * @throws IOException 
	 */
	public static boolean writeXMLFileByGBKFormat(String filePathAndName,
			Document document) throws IOException {
		boolean result = false;
		result = writeXMLFileByFormat(filePathAndName, document, "GBK");
		return result;
	}

	/**
	 * 锟斤拷式锟斤拷写锟侥硷拷
	 * @param filePathAndName
	 * @param document
	 * @param encoding
	 * @return boolean
	 * @throws IOException 
	 */
	public static boolean writeXMLFileByFormat(String filePathAndName,
			Document document, String encoding) throws IOException {
		boolean result = false;
		XMLWriter writer = null;
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding(encoding);
		writer = getXMLWriter(filePathAndName, format);
		writeXMLFile(writer, document);
		writer.close();
		result = true;
		return result;
	}

	/**
	 * 锟斤拷锟絰ml锟侥硷拷
	 * @param filePathAndName
	 * @param document
	 * @return boolean
	 * @throws IOException
	 */
	public static boolean writeXMLFile(String filePathAndName, Document document)
			throws IOException {
		boolean result = false;
		XMLWriter writer = getXMLWriter(filePathAndName);
		writeXMLFile(writer, document);
		writer.close();
		result = true;
		return result;
	}
	
	/**
	 * 锟斤拷锟絰ml锟侥硷拷
	 * @param filePathAndName
	 * @param document
	 * @return boolean
	 * @throws IOException
	 */
	public static boolean writeXMLFileByFormat(String filePathAndName, Document document)
			throws IOException {
		boolean result = false;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = getXMLWriter(filePathAndName, format);
		writeXMLFile(writer, document);
		writer.close();
		result = true;
		return result;
	}
	
	/**
	 * 锟斤拷锟絰ml锟侥硷拷
	 * @param xmlWriter
	 * @param document
	 * @return boolean
	 * @throws IOException
	 */
	private static boolean writeXMLFile(XMLWriter xmlWriter, Document document)
			throws IOException {
		boolean result = false;
		xmlWriter.write(document);
		xmlWriter.flush();
		xmlWriter.close();
		result = true;
		return result;
	}
    
    /**
     *  锟斤拷取xml,锟斤拷锟斤拷Document
     * @param filename
     * @return Document
     * @throws DocumentException
     */
    public static Document readXMLFile(String filename) throws DocumentException {
		Document document = null;
		if (filename == null || filename == "") {
			return document;
		}
		SAXReader saxReader = new SAXReader();
		document = saxReader.read(new File(filename));
		return document;
	}
    
    /**
     * 锟斤拷锟斤拷XML锟侥硷拷锟斤拷式
     * @return
     */
    public static Document createDocument() {
    	
		Document document = DocumentHelper.createDocument();
		
		Element booksElement = document.addElement("books");
		booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
		
		Element bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "yes");
		Element titleElement = bookElement.addElement("id");
		titleElement.setText("1");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Dom4j Tutorials");
		titleElement = bookElement.addElement("author");
		titleElement.setText("panming");
		titleElement = bookElement.addElement("date");
		titleElement.setText("2008-3-31");
		
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "yes");
		titleElement = bookElement.addElement("id");
		titleElement.setText("2");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene Studing");
		titleElement = bookElement.addElement("author");
		titleElement.setText("panming");
		titleElement = bookElement.addElement("date");
		titleElement.setText("2008-3-31");
		
		bookElement = booksElement.addElement("book");
		bookElement.addAttribute("show", "no");
		titleElement = bookElement.addElement("id");
		titleElement.setText("3");
		titleElement = bookElement.addElement("title");
		titleElement.setText("Lucene in Action");
		titleElement = bookElement.addElement("author");
		titleElement.setText("panming");
		titleElement = bookElement.addElement("date");
		titleElement.setText("2008-3-31");

		Element ownerElement = booksElement.addElement("owner");
		ownerElement.setText("O'Reilly");
		
        return document;
    }
	
    public static String nodeText(Element element){
    	if(element.isTextOnly()){
    		System.out.println(element.getName()+":"+element.getText());
    	}else{
    		for(Iterator<?> iterator = element.elementIterator();iterator.hasNext();){
    			Element element1 = (Element)iterator.next();
    			nodeText(element1);
    		}
    	}
    	return null;
    }
    
    /**
     * 
     * @param list 锟斤拷菘锟斤拷取锟斤拷锟斤拷锟侥硷拷录锟斤拷
     * @param filePath 锟斤拷锟斤拷xml锟斤拷锟侥硷拷锟斤拷路锟斤拷
     * @param fileName  锟斤拷锟斤拷锟絰ml锟侥硷拷锟斤拷
     * @return 锟斤拷锟斤拷xml锟斤拷路锟斤拷锟斤拷
     */
    public static boolean dataToXml(List<?> list, String filePath, String fileName)
			throws DocumentException, IOException {
		boolean status = false;
		XStream xstream = new XStream();
		String xml = xstream.toXML(list);
		Document document = DocumentHelper.parseText(xml);
		if (!IOUtil.FileExists(filePath)) {
			IOUtil.newFile(filePath);
		}
		status = Dom4jUtil.writeXMLFileByFormat(fileName, document);
		return status;

	}
    
    /**
     * 
     * @param list 锟斤拷菘锟斤拷取锟斤拷锟斤拷锟侥硷拷录锟斤拷
     * @param filePath 锟斤拷锟斤拷xml锟斤拷锟侥硷拷锟斤拷路锟斤拷
     * @param fileName  锟斤拷锟斤拷锟絰ml锟侥硷拷锟斤拷
     * @param clazz  要转锟斤拷为xml锟斤拷锟斤拷
     * @param alias  转锟斤拷为xml锟斤拷谋锟斤拷锟�     * @return 锟斤拷锟斤拷xml锟斤拷路锟斤拷锟斤拷
     */
    public static boolean dataToXml(List<?> list, String filePath,
			String fileName, Class<?> clazz, String alias)
			throws DocumentException, IOException {
		boolean status = false;
		XStream xstream = new XStream();
		xstream.alias(alias + "s", List.class);
		xstream.alias(alias, clazz);
		String xml = xstream.toXML(list);
		Document document = DocumentHelper.parseText(xml);
		if (!IOUtil.FileExists(filePath)) {
			IOUtil.newFile(filePath);
		}
		status = Dom4jUtil.writeXMLFileByFormat(fileName, document);
		return status;
	}
    
    public static String dataToXmls(List<?> list, Class<?> clazz, String alias) {
		XStream xstream = new XStream();
		xstream.alias(alias + "s", List.class);
		xstream.alias(alias, clazz);
		String xml = xstream.toXML(list);
//		Document document = DocumentHelper.parseText(xml);
//		document.asXML();            document锟侥硷拷转锟斤拷为xml
//		if (!IOUtil.FileExists(filePath)) {
//			IOUtil.newFile(filePath);
//		}
//		status = Dom4jUtil.writeXMLFileByFormat(fileName, document);
		return xml;
	}
    
    public static String objectToXmls(Object object, Class<?> clazz, String alias) {
		XStream xstream = new XStream();
		xstream.alias(alias, clazz);
		String xml = xstream.toXML(object);
		return xml;
	}
    /**
     * 
     * @param receiveXml 要转锟斤拷锟斤拷xml源锟侥硷拷
     * @return 锟斤拷锟斤拷锟斤拷锟叫憋拷
     */
    public static List<?> xmlToData(String receiveXml) {
		XStream xstream = new XStream(new DomDriver());
		List<?> list = (List<?>) xstream.fromXML(receiveXml);
		return list;
	}
    
    /**
     * 
     * @param receiveXml 要转锟斤拷锟斤拷xml源锟侥硷拷
     * @param alias  转锟斤拷为xml锟斤拷谋锟斤拷锟�     * @param clazz  xml转锟斤拷锟斤拷锟斤拷锟斤拷锟�     * @return 锟斤拷锟斤拷锟斤拷锟叫憋拷
     */
    public static List<?> xmlToData(String receiveXml, Class<?> clazz, String alias) {
		XStream xstream = new XStream(new DomDriver());
		xstream.alias(alias + "s", List.class);
		xstream.alias(alias, clazz);
		List<?> list = (List<?>) xstream.fromXML(receiveXml);
		return list;
	}
    
    public static Object xmlToObject(String receiveXml, Class<?> clazz, String alias) {
		XStream xstream = new XStream(new DomDriver());
		xstream.alias(alias, clazz);
		Object object = (Object) xstream.fromXML(receiveXml);
		return object;
	}
    
    /**
	 * @param xmlPath
	 * @param xsdPath
	 * @return
	 */
	public static boolean validateXMLByXS(String xmlPath, String xsdPath) {
		String xmlFileName = xmlPath;
		String xsdFileName = xsdPath;

		try {
			XMLErrorHandler errorHandler = new XMLErrorHandler();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setValidating(true);
			factory.setNamespaceAware(true);
			SAXParser parser = factory.newSAXParser();
			SAXReader xmlReader = new SAXReader();
			Document xmlDocument = (Document) xmlReader.read(new File(
					xmlFileName));
			parser.setProperty(
					"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
					"http://www.w3.org/2001/XMLSchema");
			parser.setProperty(
					"http://java.sun.com/xml/jaxp/properties/schemaSource",
					"file:" + xsdFileName);
			SAXValidator validator = new SAXValidator(parser.getXMLReader());
			validator.setErrorHandler(errorHandler);
			validator.validate(xmlDocument);
			XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
			if (errorHandler.getErrors().hasContent()) {
				writer.write(errorHandler.getErrors());
				return false;
			} else {
				return true;
			}
		} catch (SAXNotRecognizedException e) {
			e.printStackTrace();
		} catch (SAXNotSupportedException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}
	
	public static void base64Decode(String base64code, String filePath,
			String fileNameh) {
		sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
		InputStream stream = null;
		DataOutputStream out = null;
		try {
			stream = new ByteArrayInputStream(decoder.decodeBuffer(base64code));
			File outputfile = new File(filePath, fileNameh);
			out = new DataOutputStream(new FileOutputStream(outputfile));
			byte[] buffer = new byte[65535];
			while (stream.read(buffer) > 0) {
				out.write(buffer);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}



package xls.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/***
 * @author panming
 * @since 2010-04-01
 */
public class IOUtil {

	public static File newFile(String filename) throws IOException {
		if (filename == null || filename.equals("")) {
			return null;
		} else {
			filename = StringUtil.formatPath(filename);
			File file = new File(filename);
			if (!file.exists()) {
				file.mkdirs();
			}
			return file;
		}
	}

	public static boolean FileExists(String filename) throws IOException {
		if (filename == null || filename.equals("")) {
			return false;
		} else {
			filename = StringUtil.formatPath(filename);
			File file = new File(filename);
			return file.exists();
		}
	}

	public static boolean renameFile(String filename, String filename1)
			throws IOException {
		boolean _bln = false;
		if ((filename == null || filename.equals(""))
				|| ((filename1 == null || filename1.equals("")))) {
			return false;
		} else {
			filename = StringUtil.formatPath(filename);
			filename1 = StringUtil.formatPath(filename1);
			File _file = new File(filename);
			File _file1 = new File(filename1);
			if (_file.exists()) {
				_bln = _file.renameTo(_file1);
			}
			return _bln;
		}
	}

	public static boolean deleteFile(String filename) throws IOException {
		if (filename == null || filename.equals("")) {
			return false;
		} else {
			filename = StringUtil.formatPath(filename);
			File _file = new File(filename);
			if (_file.exists()) {
				_file.delete();
			}
			return true;
		}
	}

	public static void deleteAllFile(String filePath) throws IOException {
		if (filePath != null && !filePath.equals("")) {
			File file = new File(filePath);
			if (file.exists()) {
				File[] fileList = file.listFiles();
				String dirPath = null;
				if (fileList != null)
					for (int i = 0; i < fileList.length; i++) {
						if (fileList[i].isFile())
							fileList[i].delete();
						if (fileList[i].isDirectory()) {
							dirPath = fileList[i].getPath();
							deleteAllFile(dirPath);
						}
					}
				file.delete();
			}
		}
	}

	public static synchronized String readFile(String fileName)
			throws IOException {
		String fileContent = "";
		if (StringUtil.checkString(fileName)) {
			File file = new File(fileName);
			if (file.exists()) {
				FileInputStream htmlinputstream = new FileInputStream(fileName);
				int ContentByte = htmlinputstream.available();
				byte htmlByte[] = new byte[ContentByte];
				htmlinputstream.read(htmlByte);
				htmlinputstream.close();
				fileContent = new String(htmlByte);
			}
		}
		return fileContent;
	}

	/***
	 * 读取文本文件内容
	 * 
	 * @param filePathAndName
	 *            带有完整绝对路径的文件名
	 * @param encoding
	 *            文本文件打开的编码方式
	 * @return 返回文本文件的内容
	 */
	public static synchronized String readFile(String fileName, String encoding)
			throws IOException {
		encoding = encoding.trim();
		StringBuffer str = new StringBuffer("");
		String st = null;

		FileInputStream fs = new FileInputStream(fileName);
		InputStreamReader isr;
		if (encoding != null && encoding.equals("")) {
			isr = new InputStreamReader(fs);
		} else {
			isr = new InputStreamReader(fs, encoding);
		}

		String data = null;
		BufferedReader br = new BufferedReader(isr);
		while ((data = br.readLine()) != null) {
			str.append(data + " ");
		}
		st = str.toString();
		return st;
	}

	// 保存修改内容
	public static synchronized void saveFile(String outputContent,
			String fileName) throws IOException {
		if (StringUtil.checkString(outputContent)
				&& StringUtil.checkString(fileName)) {
			File file = new File(fileName);
			// if (file.exists()) {
			// file.delete();
			// }
			FileOutputStream fileoutputstream = new FileOutputStream(file);
			byte htmlByte[] = outputContent.getBytes();
			fileoutputstream.write(htmlByte);
			fileoutputstream.close();
		}
	}

	/***
	 * 复制单个文件
	 * 
	 * @param oldPathFile
	 *            准备复制的文件源
	 * @param newPathFile
	 *            拷贝到新绝对路径带文件名
	 */
	public static void copyFile(String oldPathFile, String newPathFile)
			throws IOException {
		int bytesum = 0;
		int byteread = 0;
		File oldfile = new File(oldPathFile);
		if (oldfile.exists()) { // 文件存在时
			InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
			int ContentByte = inStream.available();
			FileOutputStream fs = new FileOutputStream(newPathFile);
			byte[] buffer = new byte[ContentByte];
			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread; // 字节数 文件大小
				fs.write(buffer, 0, byteread);
			}
			inStream.close();
		}
	}

	/***
	 * 新建目录
	 * 
	 * @param folderPath
	 *            目录
	 */
	public static void createFolder(String folderPath) throws IOException {
		File myFilePath = new File(folderPath);
		if (!myFilePath.exists()) {
			myFilePath.mkdir();
		}
	}

	/***
	 * 多级目录创建
	 * 
	 * @param folderPath
	 *            准备要在本级目录下创建新目录的目录路径 例如 c:myf
	 * @param paths
	 *            无限级目录参数,各级目录以单数线区分 例如 a|b|c
	 */
	public static void createFolders(String folderPath, String paths)
			throws IOException {
		String txt;
		StringTokenizer st = new StringTokenizer(paths, "|");
		for (int i = 0; st.hasMoreTokens(); i++) {
			txt = st.nextToken().trim();
			if (folderPath.lastIndexOf(File.separator) != -1) {
				createFolder(folderPath + txt);
			} else {
				createFolder(folderPath + txt + File.separator);
			}
		}
	}

	public static void createNewFile(String directory, String filename)
			throws IOException {
		if (directory != null && !directory.equals("") && filename != null
				&& filename.equals("")) {
			File file = new File(directory, filename);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
		}
	}

	public static void main(String[] args) {
		try {
			System.out.println(IOUtil.FileExists("c://log.txt"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}



package xls.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;

/***
 * @author panming
 */
public class StringUtil {

	// 检查字符窜是否为空,假如为空的话就返回false,否则返回true
	public static boolean checkString(String str) {
		boolean isnull = false;
		if (str == null || str.equals("") || str.equals("null")
				|| str.equals("NULL")) {
			isnull = false;
		} else {
			isnull = true;
		}
		return isnull;
	}

	// 校验字符窜是否为空,假如不为空就返回true
	public static boolean validateStrNotNull(String str) {
		boolean _isNull = false;
		if (str == null || str.equals("") || str.equals("null")
				|| str.equals("NULL")) {
			_isNull = false;
		} else {
			_isNull = true;
		}
		return _isNull;
	}

	// 获取文件的扩展名
	public static String getFileExt(String fileName) {
		String fileExt = null;
		if (fileName == null || fileName.equals("")) {
			fileExt = "";
			return fileExt;
		} else {
			if (fileName.lastIndexOf(".") > 0) {
				fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
				if (fileExt == null || fileExt.equals("")) {
					fileExt = "";
					return fileExt;
				} else {
					return fileExt;
				}
			} else {
				fileExt = "";
				return fileExt;
			}
		}
	}

	// 获取除开扩展名后的其他字符窜
	public static String getFileWithoutExt(String fileName) {
		String fileWithoutExt = null;
		if (fileName == null || fileName.equals("")) {
			fileWithoutExt = "";
			return fileWithoutExt;
		} else {
			if (fileName.lastIndexOf(".") > 0) {
				fileWithoutExt = fileName.substring(0, fileName
						.lastIndexOf("."));
				if (fileWithoutExt == null || fileWithoutExt.equals("")) {
					fileWithoutExt = "";
					return fileWithoutExt;
				} else {
					return fileWithoutExt;
				}
			} else {
				fileWithoutExt = "";
				return fileWithoutExt;
			}
		}
	}

	// 判断在指定的字符窜中是否存在着特定的字符窜
	public static boolean getStrExists(String fileName, String str) {
		boolean isExist = false;
		if ((fileName == null || fileName.equals(""))
				|| (str == null || str.equals(""))) {
			return isExist;
		} else {
			int i = fileName.indexOf(str);
			if (i >= 0) {
				isExist = true;
			} else {
				isExist = false;
			}
			return isExist;
		}
	}

	// 标准格式化路径
	public static String formatPath(String path) {
		if (path == null || path.equals("")) {
			path = "";
			return path;
		} else {
			path = replaceAll(path, "\\", File.separator);
			path = replaceAll(path, "/", File.separator);
			return path;
		}
	}

	public static String formatHtml(String strHtml) {
		if (strHtml == null || strHtml.equals("")) {
			strHtml = "";
		} else {
			strHtml = replaceAll(strHtml, "\"", "'");
		}
		return strHtml;
	}

	// 字符窜替换函数
	public static String replaceAll(String s, String s1, String s2) {
		StringBuffer stringbuffer = new StringBuffer();
		String str_stringbuffer = null;
		int i = 0;
		int j = 0;
		int k = 0;
		int l = 0;
		if ((s == null || s.equals("")) || (s1 == null || s1.equals(""))) {
			if (s == null) {
				s = "";
			}
			return s;
		} else {
			i = s.length();
			j = s1.length();
			for (k = 0; (l = s.indexOf(s1, k)) >= 0; k = l + j) {
				stringbuffer.append(s.substring(k, l));
				stringbuffer.append(s2);
			}
			if (k < i)
				stringbuffer.append(s.substring(k));
			str_stringbuffer = stringbuffer.toString();
			stringbuffer = new StringBuffer();
			return str_stringbuffer;
		}
	}

	// 字符窜根据特定的标记来返回数组
	public static String[] strToArray(String dataStr, String tokenizer) {
		String[] arr = null;
		StringTokenizer st = new StringTokenizer(dataStr, tokenizer);
		arr = new String[st.countTokens()];
		for (int i = 0; st.hasMoreTokens() && i < arr.length; i++) {
			arr[i] = st.nextToken();
		}
		return arr;
	}

	// 格式化成UTF-8编码
	public static String formatStrUTF8(String str) {
		if (str == null || str.equals("")) {
			return "";
		}
		try {
			return (new String(str.getBytes("ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
			return "";
		}
	}

	// 格式化成gb2312编码
	public static String formatStrGB2312(String str) {
		if (str == null || str.equals("")) {
			return "";
		}
		try {
			return (new String(str.getBytes("ISO-8859-1"), "GB2312"));
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
			return "";
		}
	}

	// 判断在字符中是否包含特定的字符
	public static boolean validateValueInstr(String value, String str) {
		boolean isTrue = false;
		if (value == null || str == null) {
			return false;
		} else {
			String[] arr = null;
			arr = StringUtil.strToArray(str, ",");
			for (int i = 0; i < arr.length; i++) {
				if (value.equals(arr[i])) {
					isTrue = true;
				}
			}
		}
		return isTrue;
	}

	// 返回特定的分隔符号所分割的数据
	public static String subLastStringWithTokenizer(String s, String s1,
			boolean _bln) {
		String _s = null;
		String[] arr = null;
		if ((s == null || s.equals("")) || (s1 == null || s1.equals(""))) {
			_s = "";
		} else {
			arr = strToArray(s, s1);
			if (_bln) {
				_s = arr[0];
			} else {
				_s = arr[arr.length - 1];
			}
		}
		return _s;
	}

	// 将输入的系统字符替换成等价的html字符
	public static String textFormatHtml(String str) {
		if (str != null && !str.equals("")) {
			str = str.replaceAll("&", "&amp;");
			str = str.replaceAll("<", "&lt;");
			str = str.replaceAll(" ", "&nbsp;&nbsp;");
			str = str.replaceAll(">", "&gt;");
			str = str.replaceAll("\r\n", "<br>");
		}
		return str;
	}

	// 将html字符替换成等价的系统字符
	public static String htmlFormatText(String str) {
		if (str != null && !str.equals("")) {
			str = str.replaceAll("&amp;", "&");
			str = str.replaceAll("&lt;", "<");
			str = str.replaceAll("&nbsp;&nbsp;", " ");
			str = str.replaceAll("&gt;", ">");
			str = str.replaceAll("<br>", "\r\n");
		}
		return str;
	}

	public static String[] split(String list, String seperators) {
		return split(list, seperators, false);
	}

	/***
	 * 第一个参数,传入的是要截的中英文字符串,第二个参数,要截取的长度。
	 * 
	 * @param str
	 * @param subBytes
	 * @return str
	 */
	public static String subString(String str, int subBytes) {
		int bytes = 0; // 用来存储字符串的总字节数
		for (int i = 0; i < str.length(); i++) {
			if (bytes == subBytes) {
				return str.substring(0, i);
			}
			char c = str.charAt(i);
			if (c < 256) {
				bytes += 1; // 英文字符的字节数看作1
			} else {
				bytes += 2; // 中文字符的字节数看作2
				if (bytes - subBytes == 1) {
					return str.substring(0, i);
				}
			}
		}
		return str;
	}

	/***
	 * 第一个参数,传入的是要截的中英文字符串,第二个参数,要截取的长度。
	 * 
	 * @param str
	 * @param subBytes
	 * @return str
	 */
	public static String subString2(String str, int subBytes) {
		int bytes = 0; // 存储字符串的总字节数
		if (str.getBytes().length <= subBytes)
			return str;
		for (int i = 0; i < str.length(); i++) {
			String s = str.charAt(i) + "";
			int bytenumber = s.getBytes().length;
			if (bytenumber == 2)
				bytes += 2;
			else
				bytes += 1;
			if (bytes >= subBytes)
				return str.substring(0, i);

		}
		return str;
	}

	public static String[] split(String list, String seperators, boolean include) {
		StringTokenizer tokens = new StringTokenizer(list, seperators, include);
		String[] result = new String[tokens.countTokens()];
		int i = 0;
		while (tokens.hasMoreTokens()) {
			result[i++] = tokens.nextToken();
		}
		return result;
	}

	public static String getFileNameByLastIndex(String url, String separator) {
		int lastIndex = url.lastIndexOf(separator);
		if (lastIndex == -1) {
			return null;
		}
		return url.substring(lastIndex + 1, url.length());
	}
}


以上是对xml的解析的工具类[size=large][/size][align=center][/align]
接一下来讲一下数据库的工具类的设计
/**
 * 
 */
package xls.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * @author zouqh
 *TODO
 *上午09:08:36
 */
public class ConnectionFactory {

	/**
	   * default datasource jndi name
	   */
	  public final static String DEFAULT_DATASOURCE_JNDI="dsWangll";  //^_^ my honey  
	  
	  public final static String TYPE_DRIVER_MANAGER  =  "DriverManager";
	  public final static String TYPE_DATA_SOURCE     =  "DataSource";
	  
	  public final static int CONN_DATESOURCE          = 1; 
	  public final static int CONN_DATESOURCE_LOGIN    = CONN_DATESOURCE+1; 
	  public final static int CONN_DRIVERMANAGER       = CONN_DATESOURCE_LOGIN+1; 
	  public final static int CONN_DRIVERMANAGER_LOGIN = CONN_DRIVERMANAGER+1;
	  public final static int CONN_DEFAULT             = CONN_DRIVERMANAGER_LOGIN+1;
	  
	  /** ConnectionFactory private constructor*/
	  private ConnectionFactory(){}
	  
	  public static Connection getConnection(String url)
	  throws SQLException
	  {
	    if(url==null || url.trim().length()==0)
	    {
	      throw new SQLException("Database connection string must not be null .");
	    }
	    
	    return DriverManager.getConnection(url);
	  }
	  
	  public static Connection getConnection(String url,String user,String pwd)
	  throws SQLException
	  {   
	    if(url==null || url.trim().length()==0)
	    {
	      throw new SQLException("Database connection string must not be null .");
	    }
	    System.out.println("url"+url+"  "+user+"mima"+pwd);
	    return DriverManager.getConnection(url,user,pwd);
	  } 
	  
	  public static Connection getConnectionByJDNI(String name)
	  throws SQLException
	  {
	    if(name==null || name.length()==0)
	    {
	      throw new SQLException("DataSource JNDI name must not be null .");
	    }
	    
	    DataSource ds =null;    
	    try
	    { 
	      InitialContext ctx=InitialCtxFactory.getInitialContext();
	      ds = (DataSource)ctx.lookup(name);
	    }
	    catch(Exception ex)
	    {
	      throw new SQLException(ex.toString());
	    }
	    
	    return ds.getConnection();
	  } 
	   
	  public static Connection getConnectionByJDNI(String name,String user,String pwd)
	  throws SQLException
	  {
	    if(name==null || name.length()==0)
	    {
	      throw new SQLException("DataSource JNDI name must not be null .");
	    }
	    
	    DataSource ds =null;    
	    try
	    { 
	      Context ctx= InitialCtxFactory.getInitialContext();
	      ds = (DataSource)ctx.lookup(name);
	    }
	    catch(Exception ex)
	    {
	      throw new SQLException(ex.toString());
	    }

	    return ds.getConnection(user,pwd);
	  }
	}

	class InitialCtxFactory
	{
	  private static InitialContext initialCtx = null;
	    
	  public static synchronized InitialContext getInitialContext() 
	  throws NamingException
	  {
	    if(initialCtx!=null) 
	    {
	      return initialCtx;
	    }
	    else 
	    {
	      initialCtx = new InitialContext();
	      return initialCtx;
	    }
	  }


/**
 * 
 */
package xls.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author zouqh
 *TODO
 *上午09:05:57
 */
public class ConnUtils {

	public static Connection getConnection(StoreConfig storeConfig)
	  throws SQLException
	  {    
	    int  cMethod=getConnectionMethod(storeConfig);
	      
	    String cString=storeConfig.getURL();      
	    String cUserName=storeConfig.getUserName();
	    String cPassword=storeConfig.getPassword();
	    String cDriver=storeConfig.getDriverClass();
	      
	    if(cDriver!=null)
	    {
	       try
	       {            
	         Class.forName(cDriver);
	       }
	       catch(Exception ex0)
	       {
	          throw new SQLException("["+ConnUtils.class.getName()+"] Can not load the database jdbc driver."+cDriver+"");
	       } 
	    }
	      
	    switch(cMethod)
	    {       
	       case ConnectionFactory.CONN_DATESOURCE :
	         return ConnectionFactory.getConnectionByJDNI(cString); 
	           
	       case ConnectionFactory.CONN_DATESOURCE_LOGIN :
	         return ConnectionFactory.getConnectionByJDNI(cString,cUserName,cPassword);
	          
	       case ConnectionFactory.CONN_DRIVERMANAGER :
	         return ConnectionFactory.getConnection(cString);
	          
	       case ConnectionFactory.CONN_DRIVERMANAGER_LOGIN :
	         return ConnectionFactory.getConnection(cString,cUserName,cPassword);
	                
	      default:
	         return ConnectionFactory.getConnectionByJDNI(ConnectionFactory.DEFAULT_DATASOURCE_JNDI);          
	    }
	  }

	//--------------------------------------------------------------------------
	// 释放数据库连接  zosatapo 2003-10-17 13:11
	//--------------------------------------------------------------------------   
	  public static void cleanupNoThrow(Statement stmt)
	  {
	    if(stmt!=null)
	    {
	      try{stmt.close();}catch(SQLException ex){}
	    }
	  }
	  
	  public static void cleanupNoThrow(PreparedStatement pstmt)
	  {
	    if(pstmt!=null)
	    {
	      try{pstmt.close();}catch(SQLException ex){}
	    }
	  }
	  
	  public static void cleanupNoThrow(Connection conn)
	  {
	    if(conn!=null)
	    {
	      try{conn.close();}catch(SQLException ex){}
	    }
	  }
	  
	  public static void cleanupNoThrow(Connection conn,Statement stmt)
	  {
	    if(stmt!=null)
	    {
	      try{stmt.close();}catch(SQLException ex){}
	    }
	    
	    if(conn!=null)
	    {
	      try{conn.close();}catch(SQLException ex){}
	    }
	  }
	  
	  public static void cleanupNoThrow(Connection conn,PreparedStatement pstmt)
	  {
	    if(pstmt!=null)
	    {
	      try{pstmt.close();}catch(SQLException ex){}
	    }
	    
	    if(conn!=null)
	    {
	      try{conn.close();}catch(SQLException ex){}
	    }
	  }
	  
	  public static void cleanupThrow(Statement stmt)
	  throws SQLException
	  {
	    if(stmt!=null){stmt.close();}
	  }
	  
	  public static void cleanupThrow(PreparedStatement pstmt)
	  throws SQLException
	  {
	    if(pstmt!=null){pstmt.close();}
	  }
	  
	  public static void cleanupThrow(Connection conn)
	  throws SQLException
	  {
	    if(conn!=null){conn.close(); }
	  }
	  
	  public static void cleanupThrow(Connection conn,Statement stmt)
	  throws SQLException
	  {
	    if(stmt!=null){stmt.close();}
	    if(conn!=null){conn.close(); }
	  }
	  
	  public static void cleanupThrow(Connection conn,PreparedStatement pstmt)
	  throws SQLException
	  {
	    if(pstmt!=null){pstmt.close();}
	    
	    if(conn!=null){conn.close(); }
	  }
	     
	  private static int getConnectionMethod(StoreConfig storeConfig)
	  {
	    if(storeConfig==null)
	    {
	      return ConnectionFactory.CONN_DEFAULT;
	    }
	      
	    String connType=storeConfig.getType();
	    String connString=storeConfig.getURL();
	    String connUserName=storeConfig.getUserName();
	    String connPassword=storeConfig.getPassword();       
	      
	    int result=ConnectionFactory.CONN_DEFAULT;
	      
	    String dataSource=ConnectionFactory.TYPE_DATA_SOURCE;
	    String ddriverManager=ConnectionFactory.TYPE_DRIVER_MANAGER;  
	      
	    if(dataSource.equalsIgnoreCase(connType))
	    {
	      if(connString==null)
	      {
	        result=ConnectionFactory.CONN_DEFAULT;
	      }
	      else
	      {
	        if(connUserName==null || connPassword==null)
	        {
	          result=ConnectionFactory.CONN_DATESOURCE;
	        }
	        else
	        {
	          result=ConnectionFactory.CONN_DATESOURCE_LOGIN;       
	        }//end if(connUserName==null || connPassword==null)
	          
	      }//~end if(connString==null)
	             
	    }
	    else if(ddriverManager.equalsIgnoreCase(connType))
	    {
	      if(connUserName==null || connPassword==null)
	      {
	        result=ConnectionFactory.CONN_DRIVERMANAGER;
	      }
	      else
	      {
	        result=ConnectionFactory.CONN_DRIVERMANAGER_LOGIN;       
	      }//end if(connUserName==null || connPassword==null)
	    }
	    else
	    {
	      result=ConnectionFactory.CONN_DEFAULT;
	    } 
	    return result;
	  }
}



package xls.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

public class DateUtils {

	public static String toString(java.util.Date date) {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		formatter.setTimeZone(TimeZone.getDefault());
		return formatter.format(date);
	}

	public static String toString(java.sql.Date date) {
		// yyyy-mm-dd
		return date.toString();
	}

	public static String toString(java.sql.Time date) {
		// hh:mm:ss
		return date.toString();
	}

	public static String toString(java.sql.Timestamp date) {
		// yyyy-mm-dd hh:mm:ss
		String dateString = date.toString();
		int posIndex = dateString.lastIndexOf(".");
		return dateString.substring(0, posIndex);
	}

	// -----------------------------------------------------------------
	// -----------------------------------------------------------------
	public static java.sql.Date toDate(double xlsDate) {
		// System.err.println("[DateUtils#toDate]"+dateString);
		java.util.Date javaDate = HSSFDateUtil.getJavaDate(xlsDate);
		java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
		return sqlDate;
	}

	@SuppressWarnings("deprecation")
	public static java.sql.Date toDate(String dateString) {
		dateString = dateString.trim();

		java.sql.Date resultDate = null;
		try {
			// try yyyy-mm-dd --> Date
			resultDate = java.sql.Date.valueOf(dateString);
		} catch (IllegalArgumentException ex) {
			try {
				// try yyyy/mm/dd --> Date
				int year;
				int month;
				int day;
				int firstDash;
				int secondDash;
				firstDash = dateString.indexOf('/');
				secondDash = dateString.indexOf('/', firstDash + 1);
				if ((firstDash > 0) & (secondDash > 0)
						& (secondDash < dateString.length() - 1)) {
					year = Integer.parseInt(dateString.substring(0, firstDash)) - 1900;
					month = Integer.parseInt(dateString.substring(
							firstDash + 1, secondDash)) - 1;
					day = Integer
							.parseInt(dateString.substring(secondDash + 1));
				} else {
					throw new java.lang.IllegalArgumentException();
				}
				resultDate = new java.sql.Date(year, month, day);
			} catch (IllegalArgumentException ex0) {
				// try yyyymmdd --> Date
				int year;
				int month;
				int day;
				year = Integer.parseInt(dateString.substring(0, 4)) - 1900;
				month = Integer.parseInt(dateString.substring(4, 6)) - 1;
				day = Integer.parseInt(dateString.substring(6, 8));
				resultDate = new java.sql.Date(year, month, day);
			}
		}
		return resultDate;
	}

	public static java.sql.Time toTime(String dateString) {
		java.sql.Time resultDate = java.sql.Time.valueOf(dateString.trim());
		return resultDate;
	}

	public static java.sql.Timestamp toTimestamp(String dateString) {
		java.sql.Timestamp resultDate = java.sql.Timestamp.valueOf(dateString
				.trim());
		return resultDate;
	}

	public static java.sql.Date toDate(java.sql.Timestamp ts) {
		return new java.sql.Date(ts.getTime());
	}

	public static java.sql.Time toTime(java.sql.Timestamp ts) {
		return new java.sql.Time(ts.getTime());
	}
}


package xls.util;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import xls.core.Cell;
import xls.core.Column;
import xls.core.CoreException;
import xls.core.Schema;
import xls.core.Type;

public class IoUtils {

	/**
	 * XLS Type<--------->Standard Type
	 * 
	 * public final static Type VARCHAR = new Type("VARCHAR");//字符串保存 public
	 * final static Type INTEGER = new Type("INTEGER");//字符串保存 public final
	 * static Type FLOAT = new Type("FLOAT");//字符串保存 public final static Type
	 * DATE = new Type("DATE"); public final static Type TIME = new
	 * Type("TIME"); public final static Type TIMESTAMP = new Type("TIMESTAMP");
	 * 
	 * @see Type
	 */
	public static Object formatXlsValue(Object value, Type dstType) {
		if (value == null) {
			// System.err.println("[formatXlsValue] "+dstType+",value=null");
			return value;
		}
		// System.err.println("[formatXlsValue] "+dstType+",value.class="+value.getClass().getName());
		if (Type.VARCHAR.equals(dstType) || Type.INTEGER.equals(dstType)
				|| Type.FLOAT.equals(dstType)) {
			return value;
		} else if (Type.DATE.equals(dstType)) {
			java.util.Date javaDate = HSSFDateUtil.getJavaDate(Float
					.parseFloat(value.toString()));
			return DateUtils.toDate(DateUtils.toString(javaDate));
		} else if (Type.TIME.equals(dstType)) {
			java.util.Date javaDate = HSSFDateUtil.getJavaDate(Float
					.parseFloat(value.toString()));
			return new java.sql.Time(javaDate.getTime());
		} else if (Type.TIMESTAMP.equals(dstType)) {
			java.util.Date javaDate = HSSFDateUtil.getJavaDate(Float
					.parseFloat(value.toString()));
			return new java.sql.Timestamp(javaDate.getTime());
		}
		return value;
	}

	public static Object readCell(HSSFCell cell, Type srcType, Type dstType) {
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		int type = TypeUtils.column2Xls(srcType);
		Object value = null;
		try {
			switch (type) {
			case HSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				if (Type.DATE.equals(dstType) || Type.DATE.equals(dstType)
						|| Type.DATE.equals(dstType)) {
					value = String.valueOf(DateUtils.toDate(
							cell.getNumericCellValue()).getTime());
				} else {
					value = String.valueOf(cell.getNumericCellValue());
				}
				break;
			default:
				break;
			}
		} catch (NumberFormatException ex) {
			// 1.试着解析数据来源本身的类型设置
			type = cell.getCellType();
			// 2.试着修改schema提供的类型设置
			// srcType = srcType.copy();
			srcType.reset(TypeUtils.xls2Column(type));
			switch (type) {
			case HSSFCell.CELL_TYPE_ERROR:
				value = String.valueOf(cell.getErrorCellValue());
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				if (Type.DATE.equals(dstType) || Type.TIME.equals(dstType)
						|| Type.TIMESTAMP.equals(dstType)) {
					value = String.valueOf(DateUtils.toDate(
							cell.getNumericCellValue()).getTime());
				} else {
					value = String.valueOf(cell.getNumericCellValue());
				}
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN:
				value = String.valueOf(cell.getBooleanCellValue() ? "1" : "0");
				break;
			default:
				value = cell.getStringCellValue();
				break;
			}
		}
		Object xlsObject = formatXlsValue(value, srcType);
		Object stdObject = formatValue(xlsObject, srcType, dstType);
		return stdObject;
	}

	public static Object readCell(ResultSet rs, int colNum, Type srcType,
			Type dstType) throws SQLException {
		Object value = null;
		if (Type.INTEGER.equals(srcType)) {
			value = String.valueOf(rs.getInt(colNum));
		}
		if (Type.FLOAT.equals(srcType)) {
			value = String.valueOf(rs.getFloat(colNum));
		} else if (Type.DATE.equals(srcType)) {
			value = rs.getDate(colNum);
		} else if (Type.TIMESTAMP.equals(srcType)) {
			value = rs.getTimestamp(colNum);
		} else {
			value = rs.getString(colNum);
		}
		return formatValue(value, srcType, dstType);
	}

	/**
	 * Standard Type<--------->Standard Type
	 * 
	 * public final static Type VARCHAR = new Type("VARCHAR");//字符串保存 public
	 * final static Type INTEGER = new Type("INTEGER");//字符串保存 public final
	 * static Type FLOAT = new Type("FLOAT");//字符串保存 public final static Type
	 * DATE = new Type("DATE"); public final static Type TIME = new
	 * Type("TIME"); public final static Type TIMESTAMP = new Type("TIMESTAMP");
	 * 
	 * @see Type
	 */
	public static Object formatValue(Object value, Type srcType, Type dstType) {
		if (value == null) {
			return value;
		}
		if (srcType.equals(dstType)) {
			return value;
		}
		boolean formatted = false;
		// --------------------------------------------------
		if (Type.VARCHAR.equals(srcType)) // java.lang.String
		{
			if (Type.INTEGER.equals(dstType) || Type.FLOAT.equals(dstType)) {
				return value;
			} else if (Type.DATE.equals(dstType)) {
				return DateUtils.toDate(value.toString());
			} else if (Type.TIME.equals(dstType)) {
				return DateUtils.toTime(value.toString());
			} else if (Type.TIMESTAMP.equals(dstType)) {
				return DateUtils.toTimestamp(value.toString());
			}
		}
		if (Type.INTEGER.equals(srcType)) // java.lang.String
		{
			if (Type.VARCHAR.equals(dstType) || Type.FLOAT.equals(dstType)) {
				return value;
			} else if (Type.DATE.equals(dstType)) {
				return DateUtils.toDate(value.toString());
			} else if (Type.TIME.equals(dstType)) {
				return DateUtils.toTime(value.toString());
			} else if (Type.TIMESTAMP.equals(dstType)) {
				return DateUtils.toTimestamp(value.toString());
			}
		}
		if (Type.FLOAT.equals(srcType)) // java.lang.String
		{
			if (Type.VARCHAR.equals(dstType) || Type.INTEGER.equals(dstType)) {
				return value;
			} else if (Type.DATE.equals(dstType)) {
				return new java.sql.Date((long) Float.parseFloat(value
						.toString()));
			} else if (Type.TIME.equals(dstType)) {
				return new java.sql.Time((long) Float.parseFloat(value
						.toString()));
			} else if (Type.TIMESTAMP.equals(dstType)) {
				return new java.sql.Timestamp((long) Float.parseFloat(value
						.toString()));
			}
		}
		if (Type.DATE.equals(srcType)) // java.sql.Date
		{
			if (Type.VARCHAR.equals(dstType)) {
				return DateUtils.toString((java.sql.Date) value);
			} else if (Type.INTEGER.equals(dstType)) {
				java.sql.Date date = (java.sql.Date) value;
				return String.valueOf(date.getTime()); // milliseconds
			} else if (Type.FLOAT.equals(dstType)) {
				java.sql.Date date = (java.sql.Date) value;
				return String.valueOf(date.getTime()); // milliseconds
			} else if (Type.TIMESTAMP.equals(dstType)) {
				return DateUtils.toTimestamp(DateUtils
						.toString((java.sql.Date) value) + " 00:00:00.000");
			}
		}
		if (Type.TIME.equals(srcType)) // java.sql.Time
		{
			if (Type.VARCHAR.equals(dstType)) {
				return DateUtils.toString((java.sql.Time) value);
			} else if (Type.INTEGER.equals(dstType)) {
				java.sql.Time date = (java.sql.Time) value;
				return String.valueOf(date.getTime()); // milliseconds
			} else if (Type.FLOAT.equals(dstType)) {
				java.sql.Time date = (java.sql.Time) value;
				return String.valueOf(date.getTime()); // milliseconds
			}
		}
		if (Type.TIMESTAMP.equals(srcType)) // java.sql.Timestamp
		{
			if (Type.VARCHAR.equals(dstType)) {
				return DateUtils.toString((java.sql.Timestamp) value);
			} else if (Type.INTEGER.equals(dstType)) {
				java.sql.Timestamp date = (java.sql.Timestamp) value;
				return String.valueOf(date.getTime()); // milliseconds
			} else if (Type.FLOAT.equals(dstType)) {
				java.sql.Timestamp date = (java.sql.Timestamp) value;
				return String.valueOf(date.getTime()); // milliseconds
			} else if (Type.TIME.equals(dstType)) {
				return DateUtils.toTime((java.sql.Timestamp) value);
			} else if (Type.DATE.equals(dstType)) {
				return DateUtils.toDate((java.sql.Timestamp) value);
			}
		}
		if (!formatted) {
			throw new RuntimeException("Can not foramt " + value + " from '"
					+ srcType + "' to '" + dstType + "'");
		}
		return value;
	}

	public static Object formatDefaultValue(String value, Type dstType) {
		Object defValue = null;
		if (Type.VARCHAR.equals(dstType) || Type.INTEGER.equals(dstType)
				|| Type.FLOAT.equals(dstType)) {
			defValue = value;
		} else if (Type.DATE.equals(dstType)) {
			defValue = DateUtils.toDate(value);
		} else if (Type.TIME.equals(dstType)) {
			defValue = DateUtils.toTime(value);
		} else if (Type.TIMESTAMP.equals(dstType)) {
			defValue = DateUtils.toTimestamp(value + ".000");
			;
		}
		return defValue;
	}

	public static void writeTitle(HSSFRow row, int cellIndex, String title) {
		HSSFCell cell = row.createCell((short) cellIndex);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		// cell.setEncoding(HSSFCell.ENCODING_COMPRESSED_UNICODE);
		// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(title);
	}

	public static void writeCell(HSSFWorkbook workBook, HSSFRow row,
			int cellIndex, Cell cellObject) {
		Schema schema = cellObject.getSchema();
		Column column = schema.getColumn(cellObject.getColumnIndex());
		Type dstType = column.getOutType();
		Type colType = column.getType();
		Object value = cellObject.getValue();
		if (value == null) {
			return;
		}
		value = IoUtils.formatValue(value, colType, dstType);
		int xlsType = TypeUtils.column2Xls(dstType);
		HSSFCell cell = row.createCell((short) cellIndex);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		switch (xlsType) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			writeXlsCell(workBook, cell, value, dstType, xlsType);
			break;
		case HSSFCell.CELL_TYPE_FORMULA:
			cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
			writeXlsCell(workBook, cell, value, dstType, xlsType);
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			cell.setCellType(HSSFCell.CELL_TYPE_BOOLEAN);
			writeXlsCell(workBook, cell, value, dstType, xlsType);
			break;
		case HSSFCell.CELL_TYPE_ERROR:
			cell.setCellType(HSSFCell.CELL_TYPE_ERROR);
			writeXlsCell(workBook, cell, value, dstType, xlsType);
			break;
		default:
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			writeXlsCell(workBook, cell, value, dstType, xlsType);
			break;
		}
	}

	private static void writeXlsCell(HSSFWorkbook workBook, HSSFCell cell,
			Object value, Type outType, int xlsType) {
		HSSFCellStyle cs = null;
		boolean formatted = false;
		if (Type.VARCHAR.equals(outType) || Type.INTEGER.equals(outType)
				|| Type.FLOAT.equals(outType)) {
			switch (xlsType) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				cell.setCellValue(Double.parseDouble(valueOf(value, "0")));
				return;
			case HSSFCell.CELL_TYPE_BOOLEAN:
				cell.setCellValue((Integer.parseInt(valueOf(value, "0")) == 0) ? false
						: true);
				return;
			case HSSFCell.CELL_TYPE_STRING:
				cell.setCellValue(valueOf(value, ""));
				return;
			}
		} else if (Type.DATE.equals(outType)) {
			switch (xlsType) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				cs = workBook.createCellStyle();
				cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
				cell.setCellStyle(cs);
				cell.setCellValue(((java.util.Date) value));
				return;
			case HSSFCell.CELL_TYPE_STRING:
				cell.setCellValue(DateUtils.toString((Date) value));
				return;
			}
		} else if (Type.TIME.equals(outType)) {
			switch (xlsType) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				cs = workBook.createCellStyle();
				cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm:ss"));
				cell.setCellStyle(cs);
				cell.setCellValue((java.util.Date) value);
				return;
			case HSSFCell.CELL_TYPE_STRING:
				cell.setCellValue(DateUtils.toString((Time) value));
				return;
			}
		} else if (Type.TIMESTAMP.equals(outType)) {
			switch (xlsType) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				cs = workBook.createCellStyle();
				cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
				cell.setCellStyle(cs);
				cell.setCellValue(((java.util.Date) value));
				return;
			case HSSFCell.CELL_TYPE_STRING:
				cell.setCellValue(DateUtils.toString((Timestamp) value));
				return;
			}
		}
		if (!formatted) {
			throw new RuntimeException("Can not foramt " + value + " from '"
					+ outType + "' to '" + xlsType + "'");
		}
	}

	public static void writeCell(PreparedStatement pstmt, Cell cell,
			int paramIndex) throws SQLException, CoreException {
		Schema cellSchema = cell.getSchema();
		Column column = cellSchema.getColumn(cell.getColumnIndex());
		if (cellSchema.isValidating()) {
			if (!cell.validate()) {
				throw new CoreException("validation falied.{" + cell + "}");
			}
		}
		Type colType = column.getType();
		Type dstType = column.getOutType();
		Object value = cell.getValue();
		value = IoUtils.formatValue(value, colType, dstType);
		if (Type.INTEGER.equals(dstType)) {
			pstmt.setInt(paramIndex, Integer.parseInt(valueOf(value, "0")));
		} else if (Type.FLOAT.equals(dstType)) {
			pstmt.setFloat(paramIndex, Float.parseFloat(valueOf(value, "0")));
		} else if (Type.DATE.equals(dstType)) {
			pstmt.setDate(paramIndex, (Date) value);
		} else if (Type.TIME.equals(dstType)) {
			pstmt.setTime(paramIndex, (Time) value);
		} else if (Type.TIMESTAMP.equals(dstType)) {
			pstmt.setTimestamp(paramIndex, (Timestamp) value);
		} else {
			pstmt.setString(paramIndex, valueOf(value, ""));
		}
	}

	public static String valueOf(Object obj, String defValue) {
		if (obj == null || obj.toString().length() == 0) {
			return defValue;
		} else {
			return obj.toString();
		}
	}
}



package xls.util;

public class StoreConfig {
	
	public final static String TYPE_DRIVER_MANAGER = "DriverManager";
	public final static String TYPE_DATA_SOURCE = "DataSource";

	public final static String STORE_TYPE = "schema.connection.type";
	public final static String STORE_URL = "schema.connection.url";
	public final static String STORE_DRIVER = "schema.connection.driver";
	public final static String STORE_USERNAME = "schema.connection.userName";
	public final static String STORE_PASSWORD = "schema.connection.password";

	private String strType;
	private String strURL;
	private String strDriverClass;
	private String strUserName;
	private String strPassword;

	public StoreConfig() {
		
	}

	public StoreConfig(String storeType, String storeURL, String userName,
			String password, String driverClass) {
		if (!isAvailableType(storeType)) {
			throw new IllegalArgumentException("Storetype[" + storeType
					+ "] not supported.");
		}
		this.strType = storeType;
		this.strURL = storeURL;
		this.strDriverClass = driverClass;
		this.strUserName = userName;
		this.strPassword = password;
	}

	public String getType() {
		return strType;
	}

	public void setType(String storeType) {
		if (!isAvailableType(storeType)) {
			throw new IllegalArgumentException("Storetype[" + storeType
					+ "] not supported.");
		}
		this.strType = storeType;
	}

	public String getURL() {
		return strURL;
	}

	public void setURL(String storeURL) {
		this.strURL = storeURL;
	}

	public String getUserName() {
		return strUserName;
	}

	public void setUserName(String userName) {
		this.strUserName = userName;
	}

	public String getPassword() {
		return strPassword;
	}

	public void setPassword(String password) {
		this.strPassword = password;
	}

	public String getDriverClass() {
		return strDriverClass;
	}

	public void setDriverClass(String driverClass) {
		this.strDriverClass = driverClass;
	}

	public String toString() {
		StringBuffer sb = new StringBuffer("StoreConfig[type=");
		sb.append(this.strType);
		sb.append(",url=");
		sb.append(strURL);
		sb.append(",userName=");
		sb.append(strUserName);
		sb.append(",driverClass=");
		sb.append(strDriverClass);
		sb.append("]");
		return (sb.toString());
	}

	private boolean isAvailableType(String type) {
		if (TYPE_DRIVER_MANAGER.equals(type) || TYPE_DATA_SOURCE.equals(type)) {
			return true;
		}
		return false;
	}
}


package xls.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import xls.core.Type;

public class TypeUtils {

// Column to JAVA and EXCEL
private static final Map<String, ColumnTypeMapper> colWrappers = new HashMap<String, ColumnTypeMapper>();

// JAVA to Column
private static final Map<Class<?>, Type> java2Columns = new HashMap<Class<?>, Type>();

// Excel to Column
private static final Map<Serializable, Type> xls2Columns = new HashMap<Serializable, Type>();

private static synchronized void populateWrappers() {
colWrappers.put(Type.VARCHAR.tag(), new ColumnTypeMapper(Type.VARCHAR,
java.lang.String.class, HSSFCell.CELL_TYPE_STRING));
colWrappers.put(Type.INTEGER.tag(), new ColumnTypeMapper(Type.INTEGER,
java.lang.String.class, HSSFCell.CELL_TYPE_NUMERIC));
colWrappers.put(Type.FLOAT.tag(), new ColumnTypeMapper(Type.FLOAT,
java.lang.String.class, HSSFCell.CELL_TYPE_NUMERIC));
colWrappers.put(Type.DATE.tag(), new ColumnTypeMapper(Type.DATE,
java.sql.Date.class, HSSFCell.CELL_TYPE_NUMERIC));
colWrappers.put(Type.TIME.tag(), new ColumnTypeMapper(Type.TIME,
java.sql.Time.class, HSSFCell.CELL_TYPE_NUMERIC));
colWrappers.put(Type.TIMESTAMP.tag(), new ColumnTypeMapper(
Type.TIMESTAMP, java.sql.Timestamp.class,
HSSFCell.CELL_TYPE_NUMERIC));

// =======================================================================
java2Columns.put(java.lang.String.class, Type.VARCHAR);
java2Columns.put(Character.TYPE, Type.VARCHAR);
// java2Columns.put(Byte.TYPE,Type.INTEGER);
// java2Columns.put(TYPE,Type.INTEGER);
java2Columns.put(Integer.TYPE, Type.INTEGER);
// java2Columns.put(Long.TYPE,Type.INTEGER);

java2Columns.put(Float.TYPE, Type.FLOAT);
// java2Columns.put(Double.TYPE,Type.FLOAT);

java2Columns.put(java.sql.Date.class, Type.DATE);
java2Columns.put(java.util.Date.class, Type.DATE);

java2Columns.put(java.sql.Time.class, Type.TIME);

java2Columns.put(java.sql.Timestamp.class, Type.TIMESTAMP);

// =======================================================================
xls2Columns.put(new Integer(HSSFCell.CELL_TYPE_STRING), Type.VARCHAR);
xls2Columns.put(new Integer(HSSFCell.CELL_TYPE_BLANK), Type.VARCHAR);
xls2Columns.put(new Integer(HSSFCell.CELL_TYPE_BOOLEAN), Type.VARCHAR);
xls2Columns.put(new Integer(HSSFCell.CELL_TYPE_FORMULA), Type.VARCHAR);

xls2Columns.put(new Integer(HSSFCell.CELL_TYPE_NUMERIC), Type.FLOAT);
xls2Columns.put(java.lang.Double.TYPE, Type.FLOAT);
}

static {
populateWrappers();
}

// ------------------------------------------------------------------------
public static Class<?> column2Java(Type columnType) {
ColumnTypeMapper ctWrapper = (ColumnTypeMapper) colWrappers
.get(columnType);
Class<?> clazz = ctWrapper.getJavaClass();
return clazz;
}

public static int column2Xls(Type columnType) {
ColumnTypeMapper ctWrapper = (ColumnTypeMapper) colWrappers
.get(columnType.tag());
// System.err.println("ctWrapper="+ctWrapper+",columnType="+columnType);
int xlsFormat = ctWrapper.getXlsFormat();
return xlsFormat;
}

public static Type xls2Column(int format) {
Type type = (Type) xls2Columns.get(new Integer(format));
// fix me!!!
type = (type == null) ? Type.VARCHAR : type;
return type;
}

public static Type java2Column(Class<?> clazz) {
Type type = (Type) java2Columns.get(clazz);
// fix me!!!
type = (type == null) ? Type.VARCHAR : type;
return type;
}

public static class ColumnTypeMapper {

private Type columnType;
private Class<?> toJavaClazz;
private int toExcelFormat;

public ColumnTypeMapper(Type columnType, Class<?> javaClazz,
int excelFormat) {
this.columnType = columnType;
this.toJavaClazz = javaClazz;
this.toExcelFormat = excelFormat;
}
public Type getColumnType() {
return columnType;
}
public Class<?> getJavaClass() {
return toJavaClazz;
}
public int getXlsFormat() {
return toExcelFormat;
}
}
}










其实到现在我们这个模块已经做的七七八八了
接下来我们可以写两个测试类一个是导入的
package xls;

import java.io.FileInputStream;
import java.sql.Connection;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import xls.core.LinkDB;
import xls.core.Record;
import xls.core.Schema;
import xls.io.SQLWriter;
import xls.io.XlsReader;
import xls.util.ConnUtils;

/**
 * @author zouqh TODO 下午05:50:36
 */
public class XmlTest2 {

	public final static String filePath = "D://project/excelUtil/conf_file/test2.xls";
	public final static String xmlPath = "D://excelUtil/conf_file/";
	public final static String xmlName = "test.xml";

	public static String pathname = "D://project/excelUtil/conf_file/xls2sql.properties";
	private static Record record = null;

	public void defaultValue() {
	}

	public void difStyle() {
	}

	public void insertData() {
	}

	public static void main(String args[]) throws Exception {

		Schema schema = new Schema(xmlPath,xmlName);
		//schema.setPathname(pathname);
		//schema.setFilePath(xmlPath);
		//schema.setFileName(xmlName);
		///schema.opendatabase();
		schema.open();
		LinkDB link=new LinkDB(pathname);
		link.open();
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
		HSSFWorkbook book = new HSSFWorkbook(fs);
		HSSFSheet sheet = book.getSheetAt(0);
		XlsReader reader = new XlsReader(schema, sheet);
		
		Connection conn = ConnUtils.getConnection(link.getStoreConfig());
		SQLWriter writer = new SQLWriter(schema, conn);
		while (reader.hasNext()) {
			record = reader.next();
			System.out.println(record);
			writer.write(record);
			System.err.println(record);
			System.out.println("返回SQL语句" + writer.generateSQL(record));
		}
	}
}

一个导出的
/**
 * 
 */
package xls;

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import xls.core.Column;
import xls.core.LinkDB;
import xls.core.Schema;
import xls.io.SQLReader;
import xls.io.XlsWriter;
import xls.util.ConnUtils;
import xls.util.TypeUtils;

/**
 * @author zouqh TODO 下午05:24:27
 */
public class Test4 {
	private static String outfile="D://project/excelUtil/conf_file/test1.xls";
	private static void configSchema(Schema schema, ResultSetMetaData metaData)
			throws SQLException, ClassNotFoundException {
		int sizeColumn = metaData.getColumnCount();
		String columnName = null;
		String columnClass = null;
		Class<?> clazz = null;
		for (int i = 1; i <= sizeColumn; ++i) {
			columnName = metaData.getColumnName(i);
			columnClass = metaData.getColumnClassName(i);
			// System.err.println("fgffgfgfgf:" + columnName);
			clazz = Class.forName(columnClass);
			schema.addColumn(new Column(i - 1, TypeUtils.java2Column(clazz),
					TypeUtils.java2Column(clazz), TypeUtils.java2Column(clazz),
					columnName));
		}
	}

	public static void main(String args[]) throws Exception {
		Schema schema = new Schema("你的文件的位置","叫什么名");
		LinkDB linkdb=new LinkDB("");
		schema.open();
		linkdb.open();
		Connection conn = ConnUtils.getConnection(linkdb.getStoreConfig());
		Statement stm = conn.createStatement();
		ResultSet rs = null;
		String strSQL = schema.getQueryString().get(0);
		System.out.println(strSQL);
		if (strSQL == null) {
			if (schema.getTableName() != null) {
				strSQL = "select * from " + schema.getTableName();
			}
		}
		if (strSQL != null) {
			// System.err.println("你需要执行的SQL语句" + strSQL);
		}
		rs = stm.executeQuery(strSQL);
		ResultSetMetaData rsm = rs.getMetaData();
		configSchema(schema, rsm);
		SQLReader reader = new SQLReader(schema, rs);
		FileOutputStream fout=new FileOutputStream(outfile);
		XlsWriter writer=new XlsWriter(schema,fout);
	
		while (reader.hasNext()) {
			writer.write(reader.next());
		}
		reader.close();
		writer.close();
		conn.close();

	}
}



  • 描述: 导入数据库的excel的数据
  • 大小: 32.9 KB
  • 描述: 需要的jar
  • 大小: 17.6 KB
  • 大小: 131.3 KB
  • 描述: properties的配置文件
  • 大小: 115.7 KB
  • 描述: xml的配置文件
  • 大小: 71 KB
分享到:
评论
1 楼 pure2004 2012-07-10  
谢谢这位仁兄,太有用了,就是还差个xls.core.LinkDB类,要是全了就太好了。

相关推荐

    Java实现excel文档数据导入数据库、导出excel

    总结,Java通过Apache POI库处理Excel文档,结合JDBC进行数据库操作,实现了数据的导入导出。在实际应用中,可能还需要处理异常、优化性能,以及考虑并发和多线程等问题。理解并掌握这些技术,可以极大地提高Java...

    excel表导入数据库 数据库导出excel(idea平台)

    在这个主题中,我们将深入探讨如何使用Java技术栈,特别是基于IDEA开发环境,来实现在JSP和Servlet中进行Excel与数据库之间的数据导入和导出。 首先,我们需要了解Java中用于处理Excel文件的库,如Apache POI。...

    Java实现Excel导入导出数据库的方法示例

    Java实现Excel导入导出数据库的方法示例主要介绍了Java实现Excel导入导出数据库的方法,结合实例形式分析了java针对Excel的读写及数据库操作相关实现技巧。该示例中,主要讲解了如何将Excel文件导入到数据库中,并...

    java实现Excel数据导入到数据库

    本篇文章将深入探讨如何使用Java实现这两个功能,主要涉及的技术栈包括Apache POI库用于操作Excel,以及JDBC(Java Database Connectivity)用于与MySQL数据库进行交互。 首先,我们需要了解Apache POI库。这是一个...

    JAVA实现数据库数据导入导出到Excel(POI)所需jar包

    在Java开发中,有时我们需要将数据库中的数据导出到Excel文件,或者从Excel文件导入数据到数据库。Apache POI是一个流行的API,专为处理Microsoft Office格式的文件,如Excel(.xlsx, .xls)。本教程将详细介绍如何...

    asp将EXCEL导入导出数据库原程序

    这个"asp将EXCEL导入导出数据库原程序"提供了一个解决方案,能够方便地将Excel中的数据存入MSSQL数据库,同时也能将数据库中的数据导出到Excel文件。 首先,我们需要了解如何使用ASP连接MSSQL数据库。通常,这涉及...

    最新java实现Excel导入导出

    用Java实现的Excel的导入导出,简洁明了,高质量代码。

    java实现mysql数据库的表导出到excel文件

    本文将详细讲解如何使用Java实现从MySQL数据库的表导出到Excel文件的过程,以及涉及到的关键技术和工具。 首先,我们需要了解的是Java与数据库交互的基础——JDBC(Java Database Connectivity)。JDBC是Java API,...

    java解析Excel文件并把数据存入数据库和导出数据为excel文件SpringBoot代码示例

    2、java读取数据库数据,并导出为excel文件。 3、README.md中有详细的操作步骤示例。 使用说明: 1. 先使用postman导入:other/excel相关.postman_collection.json 2. 导入sql到数据库:other/excel.sql 3. idea导入...

    spring boot+mybatis plus+easy poi实现数据库导出成excel和excel导入到数据库.zip

    在本项目中,"spring boot+mybatis plus+easy poi实现数据库导出成excel和excel导入到数据库",开发者利用了Spring Boot、MyBatis Plus和EasyPoi库来实现了一个功能强大的数据交互系统,允许用户将数据库中的数据...

    SpringBootMybatis+poi+Thymeleaf实现excel文件数据导入到数据库以及从数据库将数据导出成excel.zip

    总的来说,这个项目展示了如何在Java环境中,结合Spring Boot的便利性,利用MyBatis进行数据库操作,借助Apache POI处理Excel文件,以及Thymeleaf生成动态页面,实现数据的导入导出功能。这是一个综合性的Java Web...

    Java操作Excel之Poi模板导入导出

    在"Java操作Excel之Poi模板导入导出"这个主题中,我们将深入探讨如何使用POI库来处理Excel模板,并进行数据的导入和导出。 首先,了解Excel模板的基本概念。模板通常包含预定义的样式、格式和计算,开发人员可以...

    POI实现Excel导入导出并附带加载进度条

    总之,这个项目是一个完整的Java解决方案,用于处理Excel文件的导入导出,同时具备用户友好的进度条显示。它利用了Apache POI的强大功能,结合maven的依赖管理,以及可能的GUI组件,提供了高效且直观的数据操作体验...

    将Excel文件导入到数据库中或将数据库中文件导出Excel中

    总的来说,熟练掌握Excel和数据库之间的数据导入导出技巧,对于提升工作效率,进行数据分析,甚至开发数据驱动的应用程序都至关重要。在实际操作中,我们还需要考虑数据的安全性、隐私保护以及性能优化等问题,确保...

    使用poi从数据库导出excel表的示例

    总结起来,"使用poi从数据库导出excel表的示例"是一个结合了Struts1 MVC框架和Apache POI库的Java编程任务,它涉及数据库连接、SQL查询、Excel文件生成以及Web应用响应。这个过程不仅有助于数据的高效管理和分享,也...

    Java--Excel根据数据库导入,导出

    本主题主要关注如何使用Java将数据库中的数据导出到Excel,以及如何从Excel文件导入数据到数据库。以下是一些关键知识点的详细说明: 1. **Java与Excel的交互**:Java中处理Excel文件最常用的库是Apache POI,它...

    java编写的数据库导入和导出工具

    本项目"java编写的数据库导入和导出工具"旨在简化这个过程,支持对SQL Server和MySQL数据库进行数据的便捷操作。下面我们将详细探讨相关的Java编程知识点、数据库操作以及可能涉及的库和框架。 1. **Java编程基础**...

    使用Springboot实现excel的导入导出

    在Spring Boot中实现Excel的导入导出可以通过POI库来实现,POI是一个开源的Java库,用于处理Microsoft Office格式文件,包括Excel。一个简单的示例,演示如何在Spring Boot项目中使用POI来实现Excel的导入导出功能。...

    java实现Excel数据导入到mysql数据库.zip

    总结来说,这个项目涵盖了Java编程、文件操作(尤其是Excel处理)、数据库连接与操作(通过JDBC和SQL)以及数据导入导出策略等多个IT核心技能。对于学习和提升这些技能,这个项目提供了一个很好的实践平台。

    excel通过配置实现导入导出和校验

    综上所述,通过配置文件实现Excel的导入导出和校验是一种高效且灵活的解决方案,它可以提升开发效率,简化代码,同时确保数据的质量。在实际项目中,我们可以结合具体的编程语言和库,根据配置文件来定制化我们的...

Global site tag (gtag.js) - Google Analytics