一、需要读excel文件中的数据写入xml文件中
class="java" name="code">public interface XmlDocument {
/**
* 建立XML文档
* @param fileName 文件全路径名称
*/
public void createXml(String fileName);
/**
* 解析XML文档
* @param fileName 文件全路径名称
*/
public void parserXml(String fileName);
}
二、读excel文件并写入xml文件的test类
@Test
public void createXml() throws IOException {
String fileName = "d://test.xml";
Document document = DocumentHelper.createDocument();
//读取excel
String excelFilename = "d://1.xls";
Element employees = document.addElement("keywords");
Element employee = employees.addElement("fistkeywords");
Element name = employee.addElement("keywords");
name.setText("机械及行业设备");
Element code = employee.addElement("code");
code.setText("113");
Element thisrdkeywords = employee.addElement("thirdkeywords");
InputStream is;
is = new FileInputStream(excelFilename);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null) {
continue;
}
// 循环列Cell
// 0关键词 1code
HSSFCell keycell0 = hssfRow.getCell(0);
keycell0.setCellType(HSSFCell.CELL_TYPE_STRING);
String ssss = keycell0.getStringCellValue();
String keyexcel = getValue(keycell0);
//xml文件中插入值
Element namethird = thisrdkeywords.addElement("keywords");
namethird.setText(keyexcel);
HSSFCell codecell2 = hssfRow.getCell(1);
codecell2.setCellType(HSSFCell.CELL_TYPE_STRING);
String str=hssfRow.getCell(1).toString();
Element codethiird = thisrdkeywords.addElement("code");
codethiird.setText(getValue(codecell2));
}
}
try {
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("utf-8");
format.setNewlines(true);
Writer fileWriter = new FileWriter(fileName);
XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
xmlWriter.write(document);
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
三、读xml文件的类
public void parserXml() {
String fileName = "d://test.xml";
File inputXml = new File(fileName);
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputXml);
Element employees = document.getRootElement();
for (Iterator i = employees.elementIterator(); i.hasNext();) {
Element employee = (Element) i.next();
for (Iterator j = employee.elementIterator(); j.hasNext();) {
Element node = (Element) j.next();
System.out.println(node.getName() + ":" + node.getText());
}
}
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
System.out.println("dom4j parserXml");
}