【问题标题】:Reading Excel, XML MAP element name using Apache POI使用 Apache POI 读取 Excel、XML MAP 元素名称
【发布时间】:2016-11-22 20:05:54
【问题描述】:

我有一个业务需求,其中向我提供了具有 xml 映射的 excel 文档(基本上使用 excel 菜单选项 Developer-> Source,然后选择一个 xml 文件并将 XML 元素映射到 excel 单元格)。例如:单元格 A2 中的值映射到 xml 元素“document_title”,B2 映射到“document_number”。

要求是以编程方式读取 excel 文档并搜索 XML 元素列表并找到映射的单元格和单元格的内容。例如:搜索xml元素“document_title”,找到该元素映射到的单元格(在上面提到的示例中,这是A2)并读取该单元格的内容。

我曾尝试使用 Apache POI 的 OPCP 包和 XSSFReader 类,并尝试使用 DOMParser 对其进行解析,但无法实现。

以下是源代码的精简版,有人可以帮助我正确的方向。

public static void main( String[] args ) throws IOException
{
    System.out.println( "reading excel" );

    try {
        OPCPackage pkg = OPCPackage.open("D:\\test.xlsx");
        XSSFReader r = new XSSFReader( pkg ); 
        SharedStringsTable sst = r.getSharedStringsTable();

        InputStream inp = r.getSheet("rId1"); 

        InputSource inpSource = new InputSource(inp);

        DOMParser parser = new DOMParser(); 
        parser.parse(inpSource); 

        Document doc = parser.getDocument(); 
        inp.close();  // dont know yet, how to read each element, and hence trying to write this to a file

        OutputStream writer = new FileOutputStream("D:\\outtrId11.xml"); 
        TransformerFactory transfac = TransformerFactory.newInstance(); 
        Transformer trans = transfac.newTransformer(); 
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
        trans.setOutputProperty(OutputKeys.INDENT, "yes"); 
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 

        //create string from xml tree 

        StreamResult result = new StreamResult(writer); 
        DOMSource source = new DOMSource(doc); 
        trans.transform(source, result);            

    } catch (InvalidFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (OpenXML4JException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

如有任何疑问/建议,请告诉我。任何帮助将不胜感激

【问题讨论】:

    标签: java xml excel apache-poi


    【解决方案1】:

    在网上搜索了一番后,我发现了一个示例,用于解决其中一个 POI 类中的错误。我已经根据我的需要调整了该示例中的代码,并得到了所需的内容。

    因此,总的来说,以下代码读取 xlsx 文件,检索任何关系(在这种情况下,我感兴趣的关系是 tableSingleCells,因为它包含 xml 地图数据)。然后,该代码会解析该文档以获取所有映射的 XML 元素和关联的单元格引用。

    最后,我显示 XML 元素、xpath 以及与这些 XML 元素关联的单元格的单元格值。

    public static void main(String[] args) throws Exception {
    
         System.out.println( "reading excel" );
    
         File file = new File("D:\\test.xlsx");
         // load an XLSX file with mapping informations
    
         XSSFWorkbook wb;
         wb = new XSSFWorkbook(file.getAbsolutePath());
    
            for( XSSFSheet sheet : wb ) {
    
                for( POIXMLDocumentPart doc : sheet.getRelations() ) {
    
                    final PackagePart part = doc.getPackagePart();
                    assert null!=part;
    
                    if( part==null ) {
                        System.out.println("part of relation is null. Will be ignored!");
                        continue;
                    }
    
                    //System.out.println(String.format("contentType [%s]", part.getContentType()));
    
                    if(part.getContentType().equalsIgnoreCase("application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml"))
                    {
                        System.out.println(String.format("contentType [%s]", part.getContentType()));
    
                        SingleXmlCellsDocument singleCellsXml = SingleXmlCellsDocument.Factory.parse( part.getInputStream() );
                        CTSingleXmlCells scs = singleCellsXml.getSingleXmlCells();
    
                        for( CTSingleXmlCell sc :  scs.getSingleXmlCellArray() ) {
    
                            //get R reference
                            final String ref = sc.getR();
    
                            //get cell reference
                            final CellReference cellRef = new CellReference( ref );
                            final CTXmlCellPr cellPr = sc.getXmlCellPr();
    
                            //get xml element reference
                            final CTXmlPr pr = cellPr.getXmlPr();
    
                            //get xpath reference
                            final String xpath = pr.getXpath();
    
                            //navigate to the cell by setting row and column
                            final int rowNum = cellRef.getRow();
                            XSSFRow row = sheet.getRow(rowNum);
    
                            final int colNum = cellRef.getCol();
                            XSSFCell cell = row.getCell( colNum);
    
    
                            DataFormatter formatter = new DataFormatter();
    
                            String cellStrValue="";
    
                            cellStrValue=formatter.formatCellValue(cell);
    
    
                            //System.out.println(xpathQuery);
                            final String xpathQuery = String.format("[Cell Reference: " + ref +  "] [Element Name: "+ cellPr.getUniqueName()  + "] [Cell Value: " + cellStrValue  + "] [Full xpath: " + xpath + "]" );
                            System.out.println(xpathQuery);
    
    
                        }
    
                    }
    
                }
    
            }
    
            wb.close();
    
    }
    

    希望这对某人有所帮助。如有任何疑问,请随时询问。

    谢谢,

    【讨论】:

    • 请包括导入。我不明白你从哪里得到某些对象!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多