美文网首页
百万Excel读取

百万Excel读取

作者: Omgxixi | 来源:发表于2020-09-14 09:54 被阅读0次

    导入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) {

    }

    }

    }

    ```

    相关文章

      网友评论

          本文标题:百万Excel读取

          本文链接:https://www.haomeiwen.com/subject/fbbaektx.html