首页 热点资讯 义务教育 高等教育 出国留学 考研考公

如何将excle文件转换成xml文件

发布网友 发布时间:2022-04-23 00:16

我来回答

1个回答

热心网友 时间:2022-04-27 18:05

package test;
import Java.io.*;
import jxl.*;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
/**
* 将excel转换成xml文件
*
* @author ztt
*
*/
public class EtoX {
/**
* 程序入口
*
* @param args
*/
public static void main(String[] args) {
File file = new File("d:/excel");
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
File file1 = new File(files[i]);
String newFile = file1.getName();
String[] names = newFile.split("//.");
String outName = "d:/xml/" + names[0] + ".xml";
String inName = "d:/excel/" + newFile;
excel2Xml(inName, outName);
}
}
/**
* 转换函数
*
* @param filePath
* excel文件
* @param out
* xml文件
*/
public static void excel2Xml(String filePath, String out) {
try {
InputStream in = new FileInputStream(filePath);
Workbook wb = Workbook.getWorkbook(in);
// 工作薄(Workbook)中工作表(Sheet)的个数
System.out.println(wb.getNumberOfSheets());
Sheet sheet = wb.getSheet(0);
int columns = sheet.getColumns(); // 返回表中的总列数
int rows = sheet.getRows(); // 返回表中总行数
System.out.println("文件总共" + rows + "行");
Element root = new Element("allElement");
Document doc = new Document(root);
for (int i = 0; i < rows; i++) {
Cell[] cell = sheet.getRow(i);
// System.out.println(cell.length);
Element instrument = new Element("element");
Element e1 = new Element("name");
e1.setText(cell[0].getContents());
instrument.addContent(e1);
Element e2 = new Element("address");
e2.setText(cell[1].getContents());
instrument.addContent(e2);
Element e3 = new Element("tel");
e3.setText(cell[2].getContents());
instrument.addContent(e3);
Element e4 = new Element("date");
e4.setText(cell[3].getContents());
instrument.addContent(e4);
Element e5 = new Element("map");
e5.setText(cell[4].getContents());
instrument.addContent(e5);
root.addContent(instrument);
}
XMLOutputter outputter = new XMLOutputter();
FileOutputStream output = new FileOutputStream(out);
outputter.output(doc, output);
wb.close();
in.close();
outputter.clone();
} catch (Exception e) {
e.printStackTrace();
}
}
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com