java - 使用 SAX 解析器解析大型 Excel 文件的第一列
问题描述
只想解析大型 excel 文件的第一列并通过连接然后使用逗号 (,) 将数据存储到字符串中,这里我使用 Apache POI 库和 SAX 解析器通过转换为 XML 来解析 excel 文件。由于 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 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("v")) {
System.out.println(lastContents);
}
}
public void characters(char[] ch, int start, int length) {
lastContents += new String(ch, start, length);
}
}
解决方案
推荐阅读
- javascript - 如何在不需要的情况下删除网页上的滚动条?
- python-3.x - 根据行搜索子字符串值创建熊猫数据框
- unit-testing - 使用 Visual Studio 2019 对 BizTalk 架构和地图进行单元测试
- azure-cli - 有没有办法获得 AKS 命名空间?
- sql - 使用别名查询作为表
- python - AttributeError:“WebsocketServerWorker”对象没有属性“add_dataset”
- image - 图像未出现在 Safari 上
- excel - Excel Vba,如何用另一个单元格更改单元格值?
- acumatica - 将供应商导入 Acumatica
- mongodb - 使用 PyMongo 使用 update_one() 执行 UPSERT,同时为每个文档添加/设置一个新字段