如何解决使用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 举报,一经查实,本站将立刻删除。