Java 使用 Apache POI 填充 Excel 缺失数据
该程序的功能是读取输入 Excel 文件中的数据,计算出数据的平均值,并填充缺失数据,最后将处理后的数据写入输出 Excel 文件中。
具体实现过程如下:
-
定义输入 Excel 文件路径、输出 Excel 文件路径和工作表名称。
-
读取输入 Excel 文件,获取指定工作表。
-
遍历工作表的每一行,将日期和数据存储到一个 TreeMap 中,其中日期作为键,数据作为值。
-
计算数据的平均值,遍历 TreeMap 中的所有数据,累加数据的值并统计数据的个数,最后计算平均值。
-
填充缺失数据,首先获取 TreeMap 中的第一个日期作为起始日期,然后获取当前日期作为结束日期,使用 Calendar 类逐一遍历起始日期到结束日期之间的所有日期,如果在 TreeMap 中找不到某个日期对应的数据,则将其填充为平均值。
-
写入输出 Excel 文件,创建一个新的 XSSFWorkbook 对象,创建一个与输入 Excel 文件工作表名称相同的工作表,遍历 TreeMap 中的所有数据,将日期和数据写入到新工作表的单元格中,最后将新 Excel 文件写入到输出 Excel 文件路径中。
-
异常处理,如果出现 IO 异常,则打印异常信息。
该程序的主要技术点涉及 Apache POI 库的使用,包括 Workbook、Sheet、Row、Cell 等对象的创建和操作,以及日期的处理和 Calendar 类的使用。同时,该程序还利用了 TreeMap 的自动排序功能,方便对日期进行遍历和处理。
package org.example;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
public class test05 {
public static void main(String[] args) {
String inputFilePath = 'C:\Users\Administrator\Desktop\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);
if (dataCell == null) {
continue;
}
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();
}
}
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/oMVi 著作权归作者所有。请勿转载和采集!