使用Java将Excel单元格值附加到XML

时间:2018-07-25 08:28:22

标签: java xml excel

我一直试图通过循环将Excel值附加到某些特定的xml节点中。

我现在正在使用的代码:

 public ExcelReaderAndWriter(String inputFileName,String outputFileName) throws IOException, InvalidFormatException {

    // Creating a Workbook from an Excel file (.xls or .xlsx)


    try (Workbook workbook = WorkbookFactory.create(new File(inputFileName))) {



        // Getting the Sheet at index zero
        Sheet sheet = workbook.getSheet("XSL_RULES");

        // Create a DataFormatter to format and get each cell's value as String
        DataFormatter dataFormatter = new DataFormatter();

        //obtain a rowIterator and columnIterator and iterate over them
        System.out.println("\n\nIterating over Rows and Columns using Iterator\n");

        Iterator <Row> rowIterator = sheet.rowIterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            // Now let's iterate over the columns of the current row
            Iterator <Cell> cellIterator = row.cellIterator();

            if (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                String cellValue = dataFormatter.formatCellValue(cell);

                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = null;
                try {
                    docBuilder = docFactory.newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                }
                Document doc = docBuilder.newDocument();
                Element rootElement = doc.createElement("ROOT");
                doc.appendChild(rootElement);
                // TOMORROW CREATE A LOOP TO GET ALL THE FILES and NODES.

                for (int k = 1; k <= sheet.getLastRowNum(); k++) {
                    Element xslt_rule = doc.createElement("RULES");

                        xslt_rule.setAttribute("ATTR1"sheet.getRow (k).getCell (0).getStringCellValue ());
                        xslt_rule.setAttribute("ATTR2", sheet.getRow (k).getCell (1).getStringCellValue ());
                        xslt_rule.setAttribute("ATTR3", sheet.getRow (k).getCell (2).getStringCellValue ());

                    }

                    xslt_rule.appendChild(doc.createTextNode(sheet.getRow (k).getCell (28).getStringCellValue ());
                    rootElement.appendChild(xslt_rule);


                }
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = null;

                try

                {
                    transformer = transformerFactory.newTransformer();
                } catch (TransformerConfigurationException e)

                {
                    e.printStackTrace();
                }

                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(outputFileName));


                try {
                    transformer.transform(source, result);
                } catch (TransformerException e) {
                    e.printStackTrace();
                }


            }
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}

因此该代码“以某种方式”有效,但是我在递归获取每个元素时遇到了问题。当我执行它时,它将创建文件到某个位置(通常是文件末尾和最后一个单元格值。

想象一下,这是我们简单的excel示例:

 1  Example1  Example5  Example9   Value1
 2  Example2  Example6  Example10  Value2
 3  Example3  Example7  Example11  Value3
 4  Example4  Example8  Example12  Value4

我希望将这些元素映射为XML输出:

<ROOT>
  <RULES ATTR1="Example1" ATTR2="Example5" ATTR3="Example9>Value1</RULES>
  <RULES ATTR1="Example2" ATTR2="Example6" ATTR3="Example10>Value2</RULES>
  <RULES ATTR1="Example3" ATTR2="Example7" ATTR3="Example11>Value3</RULES>
  <RULES ATTR1="Example4" ATTR2="Example8" ATTR3="Example12>Value4</RULES>
</ROOT>

我认为我在While循环中也犯了一个错误,因为它在执行几次后就停止了,因为它永远不会停止执行。

这里的错误在哪里,我如何更好,更干净地改善它?谢谢!

编辑:我找到了解决方案并编辑了代码。它正在工作。

问题是我的for循环,我找不到如何计算行号以及如何基于该循环获取行号。这是关于整个工作表和行号的。毕竟没有那么难。希望对其他人有帮助。

1 个答案:

答案 0 :(得分:0)

有效的解决方案是:

public ExcelReaderAndWriter(String inputFileName,String outputFileName) throws IOException, InvalidFormatException {

// Creating a Workbook from an Excel file (.xls or .xlsx)


try (Workbook workbook = WorkbookFactory.create(new File(inputFileName))) {



    // Getting the Sheet at index zero
    Sheet sheet = workbook.getSheet("XSL_RULES");

    // Create a DataFormatter to format and get each cell's value as String
    DataFormatter dataFormatter = new DataFormatter();

    //obtain a rowIterator and columnIterator and iterate over them
    System.out.println("\n\nIterating over Rows and Columns using Iterator\n");

    Iterator <Row> rowIterator = sheet.rowIterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        // Now let's iterate over the columns of the current row
        Iterator <Cell> cellIterator = row.cellIterator();

        if (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            String cellValue = dataFormatter.formatCellValue(cell);

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = null;
            try {
                docBuilder = docFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ROOT");
            doc.appendChild(rootElement);
            // TOMORROW CREATE A LOOP TO GET ALL THE FILES and NODES.

            for (int k = 1; k <= sheet.getLastRowNum(); k++) {
                Element xslt_rule = doc.createElement("RULES");

                    xslt_rule.setAttribute("ATTR1"sheet.getRow (k).getCell (0).getStringCellValue ());
                    xslt_rule.setAttribute("ATTR2", sheet.getRow (k).getCell (1).getStringCellValue ());
                    xslt_rule.setAttribute("ATTR3", sheet.getRow (k).getCell (2).getStringCellValue ());

                }

                xslt_rule.appendChild(doc.createTextNode(sheet.getRow (k).getCell (28).getStringCellValue ());
                rootElement.appendChild(xslt_rule);


            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = null;

            try

            {
                transformer = transformerFactory.newTransformer();
            } catch (TransformerConfigurationException e)

            {
                e.printStackTrace();
            }

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(outputFileName));


            try {
                transformer.transform(source, result);
            } catch (TransformerException e) {
                e.printStackTrace();
            }


        }
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

}