使用apache poi xssf退出读取文件

时间:2016-01-13 09:24:24

标签: java excel apache apache-poi xssf

我正在使用apache poi xssf来读取excel文件,当我找到没有字段“date”的行时,我需要停止读取(从第三行开始,每行有一个字段日期,如果它是空的我必须停止文件阅读)。 所以我有这个实现SheetContentsHandler的类:

public class SheetToCSV implements SheetContentsHandler {

    //Custom comparator used to store key in map with the same order of excel cells
    private Comparator<String> excelOrder = comparingInt(String::length).thenComparing(String::compareTo);
    //data structure used to store cell coordinates and value where cell coordinates are the keys
    private TreeMap<String,String> rowValues=new TreeMap<String, String>(excelOrder);
    private int currentRow = -1;
    private AcquisitionForm acquisitionForm;
    private int sheetIndex;
    private DatabaseAcquisitionServices databaseAcquisitionServices;
    private int startRow;

    /**
     * @param acquisitionForm
     * @param sheetIndex
     * @param databaseAcquisitionServices
     */
    public SheetToCSV(AcquisitionForm acquisitionForm, int sheetIndex,
            DatabaseAcquisitionServices databaseAcquisitionServices, int startRow) {
        super();
        this.acquisitionForm = acquisitionForm;
        this.sheetIndex = sheetIndex;
        this.databaseAcquisitionServices = databaseAcquisitionServices;
        this.startRow=startRow;
    }

    public void startRow(int rowNum) {
        //add +1 to keep the same numeration of excel file, so start from 1 and not 0
        currentRow = rowNum + 1;
    }

    public void cell(String cellReference, String formattedValue,
            XSSFComment comment) {
        if (currentRow <= startRow) { 
            return; 
        }
        rowValues.put(cellReference, formattedValue);
    }

    @Override
    public void endRow(int rowNum) {
        if (!rowValues.isEmpty()){
            try {
                databaseAcquisitionServices.archiveAcquisition(new TreeMap<>(rowValues), currentRow, acquisitionForm, sheetIndex);
            } catch (ExcelReadException e) {
                return;
            }
            rowValues.clear();
        }
    }

    @Override
    public void headerFooter(String text, boolean isHeader, String tagName) {
    }
}

我的方法databaseAcquisitionServices.archiveAcquisition()在找到没有日期的第一行时抛出异常,但我只捕获此异常,因为endRow方法不能抛出任何异常。 archiveAcquisiont的一部分,代码启动异常(整个代码太长):

if (actualRowValues.get(ExcelMappingCoordinate.date.getCoordinate()+index)==null){
    String message = "Threw exception in DatabaseServicesImpl::archiveAcquisition : the excel file contain no longer usuful row";
    LOG.error(message);
    throw new ExcelReadException(message);
}
try {
    date = format.parse(actualRowValues.get(ExcelMappingCoordinate.date.getCoordinate()+index));
    } catch (ParseException e) {
        LOG.error("Threw exception in DatabaseServicesImpl::archiveAcquisition : " + ErrorExceptionBuilder.buildErrorResponse(e));
}

使用实际代码我只进入下一行,但在第一个空日期行之后,所有后续行都相等。 我该如何退出阅读? 非常感谢

0 个答案:

没有答案