package org.simantics.excel.poi.parser.streaming; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XSSSheetHandler extends DefaultHandler { private SharedStringsTable sst; private String lastContents; private boolean nextIsString; int rowIndex = 0; List row = new ArrayList(); List rowTypes = new ArrayList(); String cellType; String cellId; SheetImpl sheet; public XSSSheetHandler(SharedStringsTable sst) { this.sst = sst; } public void setSheet(SheetImpl sheet) { this.sheet = sheet; } public void writeRow(Row row) { System.out.println(row); } public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { // c => cell // System.out.println(name); // for (int i = 0; i < attributes.getLength(); i++) { // System.out.println(" " + attributes.getLocalName(i) + "; "+attributes.getValue(i) + "; " + attributes.getType(i) ); // // } if(name.equals("c")) { // Figure out if the value is an index in the SST cellType = attributes.getValue("t"); cellId = attributes.getValue("r"); if(cellType != null) { if (cellType.equals("s")) nextIsString = true; else nextIsString = false; } else { nextIsString = false; cellType = "v"; } } // Clear contents cache lastContents = ""; } public void endElement(String uri, String localName, 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("c")) { int colIndex = getColIndex(cellId); for (int i = row.size(); i< colIndex; i++) { row.add(null); rowTypes.add("s"); } row.add(lastContents); rowTypes.add(cellType); //System.out.println(lastContents); lastContents = ""; } else if (name.equals("row")) { writeRow( new RowImpl(sheet, row, rowTypes,rowIndex)); rowIndex++; row.clear(); rowTypes.clear(); } } public void characters(char[] ch, int start, int length) throws SAXException { lastContents += new String(ch, start, length); // System.out.println("char : " + lastContents); } private int getColIndex(String id) { int len = 0; int range = 'Z'-'A'+1; for (int i = 0; i < id.length(); i++) { char c = id.charAt(i) ; if ('A' <= c && c <= 'Z') { len = i+1; } else { break; } } int index = 0; for (int i = 0; i < len; i++) { char c = id.charAt(len-i-1); index += (c-'A') + i * range; } return index; } }