在代码中,可以添加一个新的方法insertMissingData来实现这个功能。该方法接收一个Sheet对象作为参数,然后遍历每一行数据,判断相邻两行的时间间隔是否超过10天,如果超过则插入新的行并填充时间和数据。

具体实现如下:

private static void insertMissingData(Sheet sheet) {
    Workbook workbook = sheet.getWorkbook(); // 获取工作簿对象
    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
        Row currentRow = sheet.getRow(i);
        Row nextRow = sheet.getRow(i + 1);
        if (currentRow != null && nextRow != null) {
            Cell currentDateCell = currentRow.getCell(0);
            Cell nextDateCell = nextRow.getCell(0);
            if (currentDateCell != null && nextDateCell != null && currentDateCell.getCellType() == CellType.NUMERIC && nextDateCell.getCellType() == CellType.NUMERIC) {
                Date currentDate = currentDateCell.getDateCellValue();
                Date nextDate = nextDateCell.getDateCellValue();
                long diff = nextDate.getTime() - currentDate.getTime();
                long diffDays = diff / (24 * 60 * 60 * 1000);
                if (diffDays > 10) {
                    int insertCount = (int) (diffDays / 10);
                    for (int j = 1; j <= insertCount; j++) {
                        // 移动原有数据
                        sheet.shiftRows(i + 1, sheet.getLastRowNum(), 1, true, true);

                        // 插入新行
                        Row newRow = sheet.createRow(i + 1);
                        Cell newDateCell = newRow.createCell(0);
                        Cell newDataCell = newRow.createCell(1);
                        Date insertDate = new Date(currentDate.getTime() + (long) j * 10 * 24 * 60 * 60 * 1000);
                        newDateCell.setCellValue(insertDate);

                        // 设置新单元格的格式与原单元格一致
                        CellStyle oldDateCellStyle = currentDateCell.getCellStyle();
                        CellStyle newDateCellStyle = workbook.createCellStyle();
                        newDateCellStyle.cloneStyleFrom(oldDateCellStyle);
                        newDateCell.setCellStyle(newDateCellStyle);

                        // 设置新数据单元格的格式与原单
                        CellStyle oldDataCellStyle = currentRow.getCell(1).getCellStyle();
                        CellStyle newDataCellStyle = workbook.createCellStyle();
                        newDataCellStyle.cloneStyleFrom(oldDataCellStyle);
                        newDataCell.setCellStyle(newDataCellStyle);

                        newDataCell.setCellValue(calculateEM(sheet, i + j));
                    }
                    i += insertCount;
                }
            }
        }
    }
}

然后在main方法中调用这个方法即可:

// 插入缺失的时间和数据
insertMissingData(newDataSheet);

这样就可以在数据中插入缺失的时间和对应的数据了。

package Data_Recovery;import orgapachepoissusermodel;import javaioFileInputStream;import javaioFileOutputStream;import javatextDecimalFormat;import javautilArrayList;import javautilDate;import javauti

原文地址: https://www.cveoy.top/t/topic/ijxr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录