使用SAX解析器解析大型Excel文件的第一列

问题描述

想要仅分析大型excel文件的第一列,并通过连接然后使用逗号(,)将数据存储到字符串中,这里我使用Apache POI库和SAX解析器通过转换为来解析excel文件XML。由于XML文件具有两个相同的元素,即“行”中的“单元”与Excel文件中具有两列的元素相同。 如果有人有想法,请分享

   public void processFirstSheet(String filename) throws Exception{

        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader( pkg );
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);
        InputStream sheet1 = r.getSheet("rId1");
        InputSource sheetSource = new InputSource(sheet1);
        parser.parse(sheetSource);
        sheet1.close();
   }

   public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException,ParserConfigurationException {
    XMLReader parser = SAXHelper.newXMLReader();
    ContentHandler handler = new SheetHandler(sst);
    parser.setContentHandler(handler);
    return parser;
}

private static class SheetHandler extends DefaultHandler{
     private SharedStringsTable sst;
     private String lastContents;
     private boolean nextIsstring;
     private static int count=1;
        
     private SheetHandler(SharedStringsTable sst) {
            
            this.sst = sst;
     }
        
     public void startElement(String uri,String localName,String name,Attributes attributes) throws SAXException {
        
    // c => cell
    if(name.equals("c")) {
     // Print the cell reference
     System.out.print(attributes.getValue("r") + " - ");
     // figure out if the value is an index in the sst
     String cellType = attributes.getValue("t");
     if(cellType != null && cellType.equals("s")) {
        nextIsstring = true;
      } else {
         nextIsstring = false;
      }
     }
        
        // Clear contents cache
        lastContents = "";
            }
        
        public void endElement(String uri,String name)
                throws SAXException {
            
            // Process the last contents as required.
            // Do Now,as characters() may be called more than once
            if(nextIsstring) {
                int idx = Integer.parseInt(lastContents);
                lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                nextIsstring = false;
            }
            // v => contents of a cell
            // Output after we've seen the string contents
            if(name.equals("v")) {
                System.out.println(lastContents);
            }
        }
        public void characters(char[] ch,int start,int length) {
        
            lastContents += new String(ch,start,length);
        }
        
        }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...