将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文件了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值