package Data_Recovery;

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EM03 {

    public static void main(String[] args) {
        // 定义输入文件和输出文件的路径
        String inputFile = 'input-2.xlsx';
        try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile))) { // 使用工作簿工厂创建 Excel 工作簿
            Sheet sheet = workbook.getSheet('P1'); // 获取 P1 工作表
            DecimalFormat df = new DecimalFormat('#.##'); // 创建 Decimal 格式化器,用于保留两位小数
            // 创建新的工作表
            String newSheetName = 'P1-1';
            int sheetIndex = workbook.getSheetIndex(newSheetName);
            Sheet newDataSheet;
            if (sheetIndex >= 0) {
                workbook.removeSheetAt(sheetIndex);
            }
            newDataSheet = workbook.createSheet(newSheetName);
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Row oldRow = sheet.getRow(i);
                Row newRow = newDataSheet.createRow(i);
                if (oldRow != null) {
                    for (int j = 0; j < oldRow.getLastCellNum(); j++) {
                        Cell oldCell = oldRow.getCell(j);
                        Cell newCell = newRow.createCell(j);
                        if (oldCell != null) {
                            if (oldCell.getCellType() == CellType.STRING) {
                                newCell.setCellValue(oldCell.getStringCellValue());
                            } else if (oldCell.getCellType() == CellType.NUMERIC) {
                                if (DateUtil.isCellDateFormatted(oldCell)) {
                                    newCell.setCellValue(oldCell.getDateCellValue());
                                } else {
                                    newCell.setCellValue(oldCell.getNumericCellValue());
                                }
                            } else if (oldCell.getCellType() == CellType.BOOLEAN) {
                                newCell.setCellValue(oldCell.getBooleanCellValue());
                            } else if (oldCell.getCellType() == CellType.FORMULA) {
                                newCell.setCellValue(oldCell.getCellFormula());
                            } else if (oldCell.getCellType() == CellType.ERROR) {
                                newCell.setCellValue(oldCell.getErrorCellValue());
                            }
                            // 复制原单元格的样式到新单元格
                            CellStyle oldCellStyle = oldCell.getCellStyle();
                            CellStyle newCellStyle = workbook.createCellStyle();
                            newCellStyle.cloneStyleFrom(oldCellStyle);
                            newCell.setCellStyle(newCellStyle);
                            // 复制原单元格的时间日期内容到新单元格
                            if (oldCell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(oldCell)) {
                                newCell.setCellValue(oldCell.getDateCellValue());
                            }
                        }
                    }
                }
            }
            // 插入缺失的时间
            insertMissingDates(workbook, newDataSheet);
            // 对每一行进行处理
            for (int i = 1; i <= newDataSheet.getLastRowNum(); i++) {
                Row row = newDataSheet.getRow(i); // 获取行对象
                if (row != null) {
                    Cell cell = row.getCell(1); // 获取第二列单元格
                    if (cell == null || cell.getCellType() == CellType.BLANK) { // 判断单元格是否为空或者空白
                        double avg = calculateEM(newDataSheet, i); // 计算EM算法填充的值
                        if (avg > 0) { // 如果填充的值大于 0
                            cell = row.createCell(1); // 创建新的单元格
                            cell.setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格
                            // 设置单元格的数据类型为数值类型
                            CellStyle cellStyle = workbook.createCellStyle();
                            DataFormat dataFormat = workbook.createDataFormat();
                            cellStyle.setDataFormat(dataFormat.getFormat('0.00'));
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }
            }
            // 将工作簿写入输入文件
            FileOutputStream outputStream = new FileOutputStream(inputFile);
            workbook.write(outputStream);
            outputStream.close();
            System.out.println('Data filling completed.'); // 输出信息
        } catch (Exception e) { // 捕获异常
            e.printStackTrace();
        }
    }

    // 计算EM算法填充的值
    private static double calculateEM(Sheet sheet, int rowIndex) {
        Row row;
        double missingValue = 0; // 缺失值
        row = sheet.getRow(rowIndex); // 获取当前行对象
        if (row != null) {
            Cell cell = row.getCell(1); // 获取指定列的单元格
            if (cell != null && cell.getCellType() == CellType.NUMERIC) {
                missingValue = cell.getNumericCellValue(); // 缺失值为单元格中的值
            } else if (cell != null && cell.getCellType() == CellType.STRING) {
                try {
                    missingValue = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
                } catch (NumberFormatException e) {
                    missingValue = 0; // 转换失败则缺失值为 0
                }
            }
        }

        List<Double> data = new ArrayList<>(); // 存储数据
        for (int i = 0; i <= sheet.getLastRowNum(); i++) { // 对每一行进行处理
            row = sheet.getRow(i); // 获取行对象
            if (row != null) {
                Cell cell = row.getCell(1); // 获取指定列的单元格
                if (cell != null && cell.getCellType() == CellType.NUMERIC) {
                    data.add(cell.getNumericCellValue()); // 将数据添加到列表中
                } else if (cell != null && cell.getCellType() == CellType.STRING) {
                    try {
                        double value = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
                        data.add(value); // 将数据添加到列表中
                    } catch (NumberFormatException e) {
                        // 转换失败,忽略该值
                    }
                }
            }
        }

        if (data.size() > 0 && missingValue > 0) { // 如果存在数据且缺失值大于 0
            double sum = 0; // 总和
            int count = 0; // 非缺失值个数
            for (double value : data) { // 遍历数据
                if (value >= 0) { // 非缺失值
                    sum += value; // 累加非缺失值
                    count++; // 非缺失值个数加一
                }
            }
            if (count > 0) { // 如果存在非缺失值
                double average = sum / count; // 计算平均值
                double variance = 0; // 方差
                for (double value : data) { // 遍历数据
                    if (value >= 0) { // 非缺失值
                        variance += Math.pow(value - average, 2); // 累加方差
                    }
                }
                variance /= count; // 计算方差
                double stdDeviation = Math.sqrt(variance); // 标准差
                return generateRandomValue(average, stdDeviation); // 返回填充的值
            }
        }
        return 0; // 如果不存在数据或缺失值小于等于0,返回 0
    }

    // 生成符合正态分布的随机值
    private static double generateRandomValue(double average, double stdDeviation) {
        double value;
        do {
            value = average + stdDeviation * Math.random(); // 生成随机值
        } while (value < 0); // 保证生成的值大于等于 0
        return value;
    }

    // 解析日期
    private static Date parseDate(String dateString) {
        if (dateString.isEmpty()) {
            return null;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy/MM/dd HH:mm'); // 创建日期格式化器
        try {
            return dateFormat.parse(dateString); // 解析日期
        } catch (ParseException e) { // 捕获异常
            e.printStackTrace();
            return null; // 返回 null
        }
    }
    // 插入缺失的时间
    private static void insertMissingDates(Workbook workbook, Sheet sheet) {
        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 currentCell = currentRow.getCell(0);
                Cell nextCell = nextRow.getCell(0);
                if (currentCell != null && nextCell != null) {
                    String currentDateValue = '';
                    String nextDateValue = '';
                    if (currentCell.getCellType() == CellType.NUMERIC) {
                        Date currentDate = currentCell.getDateCellValue();
                        currentDateValue = formatDate(currentDate);
                    } else if (currentCell.getCellType() == CellType.STRING) {
                        currentDateValue = currentCell.getStringCellValue();
                    }
                    if (nextCell.getCellType() == CellType.NUMERIC) {
                        Date nextDate = nextCell.getDateCellValue();
                        nextDateValue = formatDate(nextDate);
                    } else if (nextCell.getCellType() == CellType.STRING) {
                        nextDateValue = nextCell.getStringCellValue();
                    }
                    Date currentDate = parseDate(currentDateValue);
                    Date nextDate = parseDate(nextDateValue);
                    long diff = 0;
                    if (nextDate != null) {
                        if (currentDate != null) {
                            diff = nextDate.getTime() - currentDate.getTime();
                        }
                    }
                    if (diff > 10 * 24 * 60 * 60 * 1000) {
                        int insertCount = (int) (diff / (10 * 24 * 60 * 60 * 1000));
                        for (int j = 1; j <= insertCount; j++) {
                            Row newRow = sheet.createRow(i + j);
                            Cell newCell = newRow.createCell(0);
                            newCell.setCellValue(formatDate(new Date(currentDate.getTime() + (long) j * 10 * 24 * 60 * 60 * 1000)));

                            // 复制原单元格的样式到新单元格
                            CellStyle currentCellStyle = currentCell.getCellStyle();
                            CellStyle newCellStyle = workbook.createCellStyle();
                            newCellStyle.cloneStyleFrom(currentCellStyle);
                            newCell.setCellStyle(newCellStyle);
                        }
                    }
                }
            }
        }
    }

    // 格式化日期
    private static String formatDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy/MM/dd HH:mm');
        return dateFormat.format(date);
    }
}
Excel 数据填充:使用 EM 算法自动补全缺失数据并插入缺失日期

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

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