导入maven依赖
```<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>```
代码类
```
public class ExcelParser {
private static Loggerlogger = LoggerFactory.getLogger(ExcelParser.class);
private StringfilePath;
private SheetContentsHandlerhandler;
public ExcelParser(String filePath) {
this.filePath = filePath;
}
public ExcelParsersetHandler(SheetContentsHandler handler) {
this.handler = handler;
return this;
}
public void parse() {
OPCPackage pkg =null;
InputStream inputStream =null;
try {
pkg = OPCPackage.open(filePath, PackageAccess.READ);
XSSFReader xssfReader =new XSSFReader(pkg);
StylesTable styles = xssfReader.getStylesTable();
ReadOnlySharedStringsTable strings =new ReadOnlySharedStringsTable(pkg);
inputStream = xssfReader.getSheetsData().next();
processSheet(styles, strings, inputStream);
}catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}finally {
if (inputStream !=null) {
try {
inputStream.close();
}catch (IOException e) {
logger.error("ExcelParser", e);
}
}
if (pkg !=null) {
try {
pkg.close();
}catch (IOException e) {
logger.error("ExcelParser", e);
}
}
}
}
private void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream)throws SAXException, IOException {
XMLReader sheetParser = XMLReaderFactory.createXMLReader();
if (handler !=null) {
sheetParser.setContentHandler(new XSSFSheetXMLHandler(styles, strings, handler, false));
}else {
sheetParser.setContentHandler(new XSSFSheetXMLHandler(styles, strings, new SimpleSheetContentsHandler(), false));
}
sheetParser.parse(new InputSource(sheetInputStream));
}
public static class SimpleSheetContentsHandlerimplements SheetContentsHandler {
@Override
public void startRow(int rowNum) {
}
@Override
public void endRow() {
}
@Override
public void cell(String cellReference, String formattedValue) {
}
@Override
public void headerFooter(String text, boolean isHeader, String tagName) {
}
}
}
```
网友评论