Search in sources :

Example 1 with AnalysisEventListener

use of com.alibaba.excel.event.AnalysisEventListener in project rebuild by getrebuild.

the class ExcelUtils method readExcel.

/**
 * @param excel
 * @param maxRows
 * @param hasHead
 * @return
 */
public static List<Cell[]> readExcel(File excel, int maxRows, boolean hasHead) {
    final List<Cell[]> rows = new ArrayList<>();
    final AtomicInteger rowNo = new AtomicInteger(0);
    try (InputStream is = new FileInputStream(excel)) {
        try (BufferedInputStream bis = new BufferedInputStream(is)) {
            // noinspection rawtypes
            EasyExcel.read(bis, null, new AnalysisEventListener() {

                @Override
                public void invokeHeadMap(Map headMap, AnalysisContext context) {
                    if (hasHead) {
                        this.invoke(headMap, context);
                    } else {
                        rowNo.incrementAndGet();
                    }
                }

                @Override
                public void invoke(Object data, AnalysisContext analysisContext) {
                    if (maxRows > 0 && rows.size() >= maxRows) {
                        return;
                    }
                    @SuppressWarnings("unchecked") Map<Integer, String> dataMap = (Map<Integer, String>) data;
                    List<Cell> row = new ArrayList<>();
                    for (int i = 0; i < dataMap.size(); i++) {
                        row.add(new Cell(dataMap.get(i), rowNo.get(), i));
                    }
                    rows.add(row.toArray(new Cell[0]));
                    rowNo.incrementAndGet();
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            }).sheet().doRead();
        }
    } catch (IOException e) {
        throw new RebuildException(e);
    }
    return rows;
}
Also used : ArrayList(java.util.ArrayList) RebuildException(com.rebuild.core.RebuildException) AnalysisContext(com.alibaba.excel.context.AnalysisContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AnalysisEventListener(com.alibaba.excel.event.AnalysisEventListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) Cell(cn.devezhao.commons.excel.Cell)

Aggregations

Cell (cn.devezhao.commons.excel.Cell)1 AnalysisContext (com.alibaba.excel.context.AnalysisContext)1 AnalysisEventListener (com.alibaba.excel.event.AnalysisEventListener)1 RebuildException (com.rebuild.core.RebuildException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1