Java Excel 数据处理:填充缺失日期并计算平均值
以下是 Java 代码示例,演示如何从输入 Excel 文件中读取数据,每个日期对应一个数据,按日期对数据排序,计算数据的平均值,填充到缺失数据的日期,并将数据写入输出 Excel 文件。
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();
}
}
}
注意事项:
- 代码依赖 Apache POI 库,需先下载并添加到项目依赖中。
- 输入 Excel 文件需符合以下要求:
- 第一列为日期(日期格式为 Excel 默认格式),第二列为数字。
- 第一行为表头,不包含数据。
- 输出 Excel 文件将覆盖同名文件,如需保留原文件,需先备份或更改输出文件名。
- 代码中使用了 Java 8 新特性,如需在较旧的 Java 版本中运行,需做相应修改。
原文地址: https://www.cveoy.top/t/topic/oK0a 著作权归作者所有。请勿转载和采集!