读写 excel 和 xml

一、新建一个excel表格 

 

 二、新建一个java 工程导入 jxl-2.6.12.jar (用来解析excel的api)

三、新建一个相应的实体类 user

package cn.rebuild;

import java.util.ArrayList;
import java.util.List;

public class User {
	//定义实体集合
	public static List<User> list = new ArrayList<User>();
	
	private String name;
	private String age;
	private String address;
	private String phone;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	@Override
	public String toString() {
		return "[ name = " + name + ", age = " + age + ", address = " + address + ", phone = " + phone + " ]";
	}
}

  

 

四、建一个读excel文件内容的类ReadFromExcel

package cn.rebuild;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

public class ReadFromExcel {
		public static void readExcelFile(String filePath) {  
			try {
				InputStream is = new FileInputStream(filePath);
				Workbook rwb = Workbook.getWorkbook(is);
				// 获得总的Sheets,得到sheet的层数
				Sheet[] sheets = rwb.getSheets();
				int sheetLen = sheets.length;
				// 获得第一个Sheets 的结果
				jxl.Sheet rs = rwb.getSheet(0);
				int num_row = rs.getRows();
				int num_column = rs.getColumns();
				for (int j = 0; j < num_row; j++) {
					User user = new User();
					// 得到第j行的所有值
					Cell[] cell = rs.getRow(j);
					for (int column_index = 0; column_index < num_column; column_index++) {
						// 得到第j行,第column_indexs列的值
						String value = cell[column_index].getContents();
						System.out.print(value + " ");
						//从第二行开始将值存入到实体里面并添加到list中
						if (j >= 1) {
							String columnValue = rs.getRow(j)[column_index].getContents();
							switch(column_index){
								case 1 : user.setName(columnValue);;break;
								case 2 : user.setAge(columnValue);;break;
								case 3 : user.setAddress(columnValue);;break;
								case 4 : user.setPhone(columnValue);;break;
								default : System.out.print("");break;
								}
						}
					}
					System.out.println("");
					if (j >= 1) {
						User.list.add(user);
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
}

  

 五、将excel文件中的内容写入到xml文件中

package cn.rebuild;

import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import cn.excel.test.Main;
import cn.rebuild.ReadFromExcel;

public class CreateXML {
	
	public static DocumentBuilderFactory dbf = null;
	public static DocumentBuilder db = null;
	public static Document doc = null;
	public static TransformerFactory tff = null;
	public static Transformer tf = null;
	public static Source in = null;
	public static Result out = null;
	public static String xmlpath = null;

	public static void init() throws Exception {
		dbf = DocumentBuilderFactory.newInstance();// 实例化工厂类
		dbf.setValidating(false);// 不进行有效性检查
		dbf.setNamespaceAware(true);
		db = dbf.newDocumentBuilder();// 实例化DocumentBuilder类
		doc = (Document) db.newDocument();// 实例化Document类
		tff = TransformerFactory.newInstance();
		tf = tff.newTransformer();
		in = new DOMSource((Node) doc);
	}

	/**
	 * 生成xml 文件
	 * @param axmlpath
	 */
	public static void ProuduceXml(String axmlpath) {

		try {
			Element users = ((org.w3c.dom.Document) doc).createElement("users");// 生产根元素users
			doc.createElement("users");
			((Node) doc).appendChild(users);// 将根元素添加到根节点后面

			for (int i = 0; i < User.list.size(); i++) {
				Element user = ProuduceElement(User.list.get(i).getName(),
						User.list.get(i).getAge(), User.list.get(i).getAddress(),
						User.list.get(i).getPhone());
				users.appendChild(user);

			}
			xmlpath = axmlpath;
			out = new StreamResult(new FileOutputStream(xmlpath));// 生成输出源
			tf.transform(in, out);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public static Element ProuduceElement(String aname, String _age, String _address, String _phone) throws Exception {

		Element user = ((org.w3c.dom.Document) doc).createElement("student");// 生成student元素(students的子元素)
		Element name = ((org.w3c.dom.Document) doc).createElement("name");// 创建name子元素
		name.appendChild(((org.w3c.dom.Document) doc).createTextNode(aname));// 在name元素后添加文本节点
		user.appendChild(name);// 添加student的子元素name

		// 设置student的属性id的值

		Element age = doc.createElement("age");
		age.appendChild(doc.createTextNode(_age));
		user.appendChild(age);

		Element address = doc.createElement("address");
		address.appendChild(doc.createTextNode(_address));
		user.appendChild(address);

		Element phone = doc.createElement("phone");
		phone.appendChild(doc.createTextNode(_phone));
		user.appendChild(phone);
		return user;
	}
	
	public static void createXMLFile(String xmlpath) {
		try {
			CreateXML.init();
			CreateXML.ProuduceXml(xmlpath);
		} catch (Exception e) {
			System.out.println("main:\n" + e.getMessage());
		}
	}
}

 六、测试类

package cn.rebuild;

public class Start {
	public static void main(String[] args) {
		//读excel内容
		ReadFromExcel.readExcelFile("d://temp/user.xls");
		//将excel文件内容写到xml并保存到指定路径
		CreateXML.createXMLFile("d://temp/user.xml");
	}
}

 七、结果

 

posted @ 2017-05-25 09:00  苦海无涯、苦尽甘来  阅读(484)  评论(0编辑  收藏  举报