解析XML 然后将内容写入EXCEL

解析XML类:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ParseXMLUtil {

 static final String TARGET_OBJECT_PATH = "item";
 static final String TARGET_OBJECT_NAME = "name";
 static final String TARGET_SCREEN_NAME = "name";

 static final String PARAM_SCREEN_NAME = "screenname";
 static final String PARAM_OBJECT_NAME = "objectname";
 static final String PARAM_OBJECT_PATH = "objectpath";

 public String targetNodeName = TARGET_OBJECT_PATH;
 public List<Map<String, String>> parseResult = null;

 public String outputPath = "output.xls";

 public List<Map<String, String>> parseXML(String path) {
  parseResult = new ArrayList<Map<String, String>>();
  try {
   InputStream in = ParseXMLUtil.class.getResourceAsStream(path);//get the stream for relative path file
   SAXReader reader = new SAXReader();
   Document doc = reader.read(in); // get document object
   Element rootElement = doc.getRootElement(); // "repository"
   if (rootElement == null) {
    throw new Exception("Root node is blank");
   }
   List<Element> targetElements = new ArrayList<Element>();
   targetElements.add(rootElement);
   while (!targetElements.isEmpty() && targetElements.size() > 0) {
    targetElements = getChildNodes(targetElements);

    for (Element itemNode : targetElements) {
     if (itemNode.getName().equals(TARGET_OBJECT_PATH)) {
      String screenName = itemNode.getParent()
        .attributeValue(TARGET_SCREEN_NAME);
      String objectName = itemNode
        .attributeValue(TARGET_OBJECT_NAME);
      String objectPath = itemNode.getTextTrim();
      if (objectPath != null && objectPath.length() >= 0) {
       Map<String, String> dataMap = new HashMap<String, String>();
       dataMap.put(PARAM_SCREEN_NAME, screenName);
       dataMap.put(PARAM_OBJECT_NAME, objectName);
       dataMap.put(PARAM_OBJECT_PATH, objectPath);
       parseResult.add(dataMap);
      }
     }
    }
   }

  } catch (Exception e) {
   System.err.println("Error:" + e);
   e.printStackTrace();
  }

  return parseResult;
 }

 @SuppressWarnings("unchecked")
 private List<Element> getChildNodes(List<Element> eList) throws Exception {
  List<Element> results = new ArrayList<Element>();
  try {
   if (eList != null && eList.size() > 0) {
    for (Element e : eList) {
     results.addAll(e.elements());
    }
   }
  } catch (Exception ex) {
   throw new Exception("Error in getChildNodes:" + ex);
  }
  return results;
 }

 public static void main(String[] args) throws Exception {
  String xmlName = "target.xml";
  String outputPath = "result.xls";
  String targetNodeName = "item";
  if (args != null && args.length > 0) {
   xmlName = args[0];
  }
  if (args != null && args.length > 1) {
   outputPath = args[1];
  }
  if (args != null && args.length > 2) {
   targetNodeName = args[2];
  }

  ParseXMLUtil util = new ParseXMLUtil();
  util.targetNodeName = targetNodeName;
  List<Map<String, String>> list = util.parseXML("/xml/" + xmlName);

  if (!list.isEmpty()) {
   System.out.println("XML " + xmlName + " " + list.size()
     + " Elements");
   ExcelWriter wrt = new ExcelWriter();
   wrt.buildXSLXExcel(list, "./output/" + outputPath);
   System.out.println("Excel paresed success and outputpath is "
     + outputPath);
  }
 }
}

写入EXCEL类:

package com.pengtao.www;


import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 


public class ExcelWriter {

 /**
  * Write Excel 2003
  */
 public void buildXSLXExcel(List<Map<String, String>> list, String filePath) {
  HSSFWorkbook workBook = null;
  String[] cellTitle = { "Screen Name", "Object Name", "XPath" };
  try {
   workBook = new HSSFWorkbook();// Create workbook
   HSSFSheet sheet = workBook.createSheet();// create work sheet
   workBook.setSheetName(0, "Repository");// set sheet name
   HSSFRow titleRow = sheet.createRow(0);// Create first row

   HSSFCell ScreenNameCell = titleRow.createCell(0, 0);
   HSSFCell ObjectCell = titleRow.createCell(2, 0);
   HSSFCell XpathCell = titleRow.createCell(4, 0);

   // Create background color style
   HSSFCellStyle cellStyle = workBook.createCellStyle();
   cellStyle.setFillForegroundColor((short)13);
   cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

   // Create font style
   Font titleFont = workBook.createFont();
   titleFont.setFontHeightInPoints((short) 12);
   titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

   cellStyle.setFont(titleFont);

   // Add color style
   ScreenNameCell.setCellStyle(cellStyle);
   ObjectCell.setCellStyle(cellStyle);
   XpathCell.setCellStyle(cellStyle);


   // Set value
   ScreenNameCell.setCellValue(cellTitle[0]);
   ObjectCell.setCellValue(cellTitle[1]);
   XpathCell.setCellValue(cellTitle[2]);

   if (list != null && !list.isEmpty()) {
    for (int i = 0; i < list.size(); i++) {
     Map<String, String> dataMap = list.get(i);
     HSSFRow row = sheet.createRow(i + 1);
     HSSFCell ScreenNamecell = row.createCell(0);
     HSSFCell Objectcell = row.createCell(2);
     HSSFCell XPathcell = row.createCell(4);
     ScreenNamecell.setCellValue(dataMap
       .get(ParseXMLUtil.PARAM_SCREEN_NAME));
     Objectcell.setCellValue(dataMap
       .get(ParseXMLUtil.PARAM_OBJECT_NAME));
     XPathcell.setCellValue(dataMap
       .get(ParseXMLUtil.PARAM_OBJECT_PATH));
    }

   }

   File file = new File(filePath);
   File parent = file.getParentFile();
   if (!parent.exists()) {
    parent.mkdir();
   }
   if (!file.exists()) {
    file.createNewFile();
   }
   FileOutputStream outStream = new FileOutputStream(file);
   workBook.write(outStream);
   outStream.flush();
   outStream.close();

  } catch (Exception e) {
   System.err.println(e);
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  // TODO Auto-generated method stub
 }

}

猜你喜欢

转载自201505240204.iteye.com/blog/2265461