XML到XLS的转换

时间:2016-12-21 13:47:32

标签: java xml-parsing apache-poi

public static void main(String argv[]) {

    ArrayList<String> firstNames = new ArrayList<String>();
    ArrayList<String> lastNames = new ArrayList<String>();
    ArrayList<String> ages = new ArrayList<String>();

    try {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        Document doc = docBuilder.parse(new File("D:/XML/Books.xml"));
        doc.getDocumentElement().normalize();
        System.out.println("Root element of the doc is :\" " + doc.getDocumentElement().getNodeName() + "\"");
        NodeList listOfPersons = doc.getElementsByTagName("person");
        int totalPersons = listOfPersons.getLength();
        System.out.println("Total no of people : " + totalPersons);
        for (int s = 0; s < listOfPersons.getLength(); s++) {
            Node firstPersonNode = listOfPersons.item(s);
            if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
                Element firstPersonElement = (Element) firstPersonNode;
                NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                Element firstNameElement = (Element) firstNameList.item(0);
                NodeList textFNList = firstNameElement.getChildNodes();
                System.out.println("First Name : " + ((Node) textFNList.item(0)).getNodeValue().trim());
                firstNames.add(((Node) textFNList.item(0)).getNodeValue().trim());
                NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                Element lastNameElement = (Element) lastNameList.item(0);
                NodeList textLNList = lastNameElement.getChildNodes();
                System.out.println("Last Name : " + ((Node) textLNList.item(0)).getNodeValue().trim());
                lastNames.add(((Node) textLNList.item(0)).getNodeValue().trim());
                NodeList ageList = firstPersonElement.getElementsByTagName("age");
                Element ageElement = (Element) ageList.item(0);
                NodeList textAgeList = ageElement.getChildNodes();
                System.out.println("Age : " + ((Node) textAgeList.item(0)).getNodeValue().trim());
                ages.add(((Node) textAgeList.item(0)).getNodeValue().trim());
            }

        }
        for (String firstName : firstNames) {
            System.out.println("firstName : " + firstName);
        }
        for (String lastName : lastNames) {
            System.out.println("lastName : " + lastName);
        }
        for (String age : ages) {
            System.out.println("age : " + age);
        }

    } catch (SAXParseException err) {
        System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
        System.out.println(" " + err.getMessage());
    } catch (SAXException e) {
        Exception x = e.getException();
        ((x == null) ? e : x).printStackTrace();
    } catch (Throwable t) {
        t.printStackTrace();
    }

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("Sample sheet");

    Map<String, Object[]> data = new HashMap<String, Object[]>();
    for (int i = 0; i < firstNames.size(); i++) {
        data.put(i + "", new Object[] { firstNames.get(i), lastNames.get(i), ages.get(i) });
    }
    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object[] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof Date)
                cell.setCellValue((Date) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }
    }

    try {

        String excelFileName = "MY_EXCEL1.xls";
        if (wb instanceof XSSFWorkbook)
            excelFileName += "x";
        FileOutputStream out = new FileOutputStream(excelFileName);
        wb.write(out);
        out.close();
        System.out.println("Excel written successfully..");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}// end of main

}

堆栈跟踪: java.io.FileNotFoundException:D:\ Informatica_Code_Review \ XMLParser \ trial.xml(系统找不到指定的文件)     at java.io.FileInputStream.open0(Native Method)     在java.io.FileInputStream.open(未知来源)     在java.io.FileInputStream。(未知来源)     在java.io.FileInputStream。(未知来源)     在sun.net.www.protocol.file.FileURLConnection.connect(未知来源)     at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)     at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)     at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)     在com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(未知来源)     at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)     at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)     在javax.xml.parsers.DocumentBuilder.parse(未知来源)     在XMLParser.main(XMLParser.java:25)

当我在其他位置寻找Books.xml时,为什么要查找文件名trial.xml。

0 个答案:

没有答案