import java.io.; import java.util.;

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

public class ExcelReaderWriter {

public static void main(String[] args) {
    String inputFilePath = 'input.xlsx';
    String outputFilePath = 'output.xlsx';
    String sheetName = 'Sheet1';

    try {
        // 读取输入Excel文件
        FileInputStream fis = new FileInputStream(inputFilePath);
        Workbook wb = new XSSFWorkbook(fis);
        Sheet sheet = wb.getSheet(sheetName);

        // 读取数据
        Map<Date, Double> dataMap = new TreeMap<>();
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue; // 跳过表头
            }
            Cell dateCell = row.getCell(0);
            Cell dataCell = row.getCell(1);
            Date date = dateCell.getDateCellValue();
            double data = dataCell.getNumericCellValue();
            dataMap.put(date, data);
        }

        // 计算平均值
        double sum = 0.0;
        int count = 0;
        for (Double data : dataMap.values()) {
            sum += data;
            count++;
        }
        double avg = sum / count;

        // 填充缺失数据
        Date startDate = dataMap.keySet().iterator().next();
        Date endDate = new Date(); // 当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (calendar.getTime().before(endDate)) {
            Date date = calendar.getTime();
            if (!dataMap.containsKey(date)) {
                dataMap.put(date, avg);
            }
            calendar.add(Calendar.DATE, 1); // 加一天
        }

        // 写入输出Excel文件
        FileOutputStream fos = new FileOutputStream(outputFilePath);
        XSSFWorkbook wbOut = new XSSFWorkbook();
        Sheet sheetOut = wbOut.createSheet(sheetName);
        int rowNum = 0;
        for (Map.Entry<Date, Double> entry : dataMap.entrySet()) {
            Date date = entry.getKey();
            double data = entry.getValue();
            Row row = sheetOut.createRow(rowNum++);
            Cell dateCell = row.createCell(0);
            Cell dataCell = row.createCell(1);
            dateCell.setCellValue(date);
            dataCell.setCellValue(data);
        }
        wbOut.write(fos);
        fos.close();

        System.out.println('数据已写入输出Excel文件:' + outputFilePath);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

// idea 如何配置只运行它的配置内容:1. 打开 IDEA,找到菜单栏中的 Run,点击 Edit Configurations。 // 2. 在弹出的窗口中,选择需要配置的运行配置。 // 3. 在右侧的配置面板中,找到 Before Launch 标签页,勾选 Skip build and run steps。 // 4. 点击 OK 保存配置。

// 现在,当你运行该配置时,它将只运行已经编译且未运行的代码,而不会重新编译或构建项目。

Java 使用 Apache POI 读取和写入 Excel 文件,并填充缺失数据

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

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