将Excel文件生成xml文件
一.下载jxl.jar(用来读取excel文件)和jdom(用来生成xml文件)
二.准备需要转换的数据,如图
三.代码部分
1.先写个类来处理如何生成xml
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
public class GenEduXml {
Document myDoc;
Element myRoot;
Element subRoot;
public void init() throws IOException, JDOMException{
myDoc = new Document(); //创建document
Attribute att1 = new Attribute("grade","3");
Attribute att2 = new Attribute("version","高级");
ArrayList<Attribute> list = new ArrayList<Attribute>();
list.add(att1);
list.add(att2);
myRoot = new Element("subChannel").setAttribute("id","英语").
addContent(new Element("questions").setAttributes(list));
//此处注意用setAttribute设置属性时,属性个数大于1时参数为Collection类
myDoc.setRootElement(myRoot); //设置根节点
subRoot = myRoot.getChild("questions"); //移动到需要插入数据的节点
}
//写一个用来插入excel中一行数据的函数,注意如何形成所需结构
public void addOneItem(String question,String anwser,String option1,String option2,String option3){
subRoot.addContent(new Element("questionItem").setAttribute("answerid",anwser).
addContent(new Element("text").setText(question)).
addContent(new Element("answer").setAttribute("id","1").setText(option1)).
addContent(new Element("answer").setAttribute("id","2").setText(option2)).
addContent(new Element("answer").setAttribute("id","3").setText(option3)));
}
//将数据导出为xml文件的函数
public void toXml()throws IOException, JDOMException{
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.output(myDoc, new FileOutputStream("test1.xml"));
}
}
2.写主函数类ExcelToXml,主函数中需要读取excel并调用GenEduXml
import java.io.File;
import jxl.*;
public class ExcelToXml {
public static void main(String args[]){
try{
Workbook workbook = Workbook.getWorkbook(new File("D:\\myfile.xls"));
Sheet sheet = workbook.getSheet(0); //获得第一个sheet
GenEduXml gen = new GenEduXml(); //创建生成xml文件的实例
gen.init();
Cell[] a = sheet.getColumn(0); //获得第一列
Cell[] b = sheet.getColumn(1);
Cell[] c = sheet.getColumn(2);
Cell[] d = sheet.getColumn(3);
Cell[] e = sheet.getColumn(4);
for(int i=0;i<a.length;i++){
gen.addOneItem(a[i].getContents(), b[i].getContents(), c[i].getContents(), d[i].getContents(), e[i].getContents());
}
workbook.close();
gen.toXml();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Xml has been biult!");
}
}
这样就可以形成所需的xml文件了