【问题标题】:Issue with converting XML file into Excel. Can someone help me in this regard?将 XML 文件转换为 Excel 时出现问题。有人可以在这方面帮助我吗?
【发布时间】:2016-06-30 06:19:27
【问题描述】:

我在网上找到了将 XML 文件转换为 Excel 的代码,但是当我打开电子表格时,行的顺序不正确,我的意思是 XML 中的第 3 条记录写在第 1 行,第 2 条写在第 2 行,第 1 条写在第 3 行, 谁能帮我在哪里做错了?

XML:

<book>
<person>
  <first>hi</first>
  <last>hi2</last>
  <age>56</age>
</person>
<person>
  <first>hello</first>
  <last>hello2</last>
  <age>25</age>
</person>
<person>
  <first>madhu</first>
  <last>madhu2</last>
  <age>23</age>
</person>
</book>

JAVA 代码:

package ToSpreadSheet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class Example {
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("C:/Users/emademp/Desktop/persons.xml"));

        // normalize text representation
        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());
            }// end of if clause

        }// end of for loop with s var
        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();
    }


    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("XML 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 {
        FileOutputStream out = new FileOutputStream(new File("C:/Users/emademp/Desktop/book1.xlsx"));
        workbook.write(out);
        out.flush();
        out.close();
        System.out.println("Excel written successfully..");

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

}// end of main

}

电子表格输出:

madhu madhu2 23
hello hello2 25
hi hi2 56

【问题讨论】:

    标签: java excel


    【解决方案1】:

    您的代码包含许多不必要的额外工作。您的问题来自于您将数据放入 HashMap 然后使用键集来迭代项目。 HashMap 的合约声明它不维护顺序,密钥集中的密钥将处于未指定的随机序列中。只是碰巧在您的情况下它们以相反的顺序出现。

    至于解决问题,根本不需要使用HashMap。当您最初从 XML 中提取数据时,将名称和年龄存储在新的自定义类中并创建这些对象的列表,然后遍历该列表以在电子表格中创建行。即,而不是列表 firstNameslastNamesages

    class Person
    {
        private String firstName;
        private String lastName;
        private String age;
        // constructor, getters and setters
    }
    ...
    List<Person> people = new ArrayList<>();
    

    然后为每个输入块创建一个新的Person,存储在people 列表中,然后通过迭代people 写入电子表格。

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 2011-08-09
      • 2019-03-15
      • 2019-04-15
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多