Java 从输入Excel文件中读取数据每个日期对应一个数据按日期对数据排序计算数据的平均值填充到缺失数据的日期并将数据写入输出Excel文件
以下是Java代码示例:
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/hh9J 著作权归作者所有。请勿转载和采集!