Excel 数据自动补全 - KNN 算法与时间规律填充
// 导入必要的库 package org1;
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.Collections; // 用于排序 import java.util.Date; // 用于处理日期 import java.util.HashMap; // 用于存储月份数据 import java.util.List; // 用于存储数据 import java.util.Map; // 用于存储键值对
import org.apache.poi.ss.usermodel.Cell; // Excel 单元格 import org.apache.poi.ss.usermodel.CellType; // Excel 单元格类型 import org.apache.poi.ss.usermodel.Row; // Excel 行 import org.apache.poi.ss.usermodel.Sheet; // Excel 工作表 import org.apache.poi.ss.usermodel.Workbook; // Excel 工作簿 import org.apache.poi.ss.usermodel.WorkbookFactory; // Excel 工作簿工厂
public class Data_Recovery { private static final DecimalFormat df = new DecimalFormat("#.##"); public static void main(String[] args) { // 定义输入文件和输出文件的路径 String inputFile = "input.xlsx"; String outputFile = "output1.xlsx"; try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile)); // 使用工作簿工厂创建 Excel 工作簿 FileOutputStream outputStream = new FileOutputStream(outputFile)) { // 创建输出文件 Sheet sheet = workbook.getSheetAt(0); // 获取 Excel 工作表 DecimalFormat df = new DecimalFormat("#.##"); // 创建 Decimal 格式化器,用于保留两位小数 // 对每一行进行处理 for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); // 获取行对象 if (row != null) { Cell cell = row.getCell(1); // 获取第二列单元格 if (cell != null && cell.getCellType() != CellType.BLANK) { // 如果单元格不为空,则跳过 } else { double avg = calculateKNN(sheet, i); // 计算KNN邻近算法填充的值 if (avg > 0) { // 如果填充的值大于 0 if(cell == null){ // 如果单元格为空,则创建新的单元格 cell = row.createCell(1); } cell.setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格 } } } } // 根据时间规律补全数据 fillMissingData(sheet); workbook.write(outputStream); // 将工作簿写入输出文件 System.out.println("Data filling completed."); // 输出信息 } catch (Exception e) { // 捕获异常 e.printStackTrace(); } }
// 计算KNN邻近算法填充的值
private static double calculateKNN(Sheet sheet, int rowIndex) {
List<Double> data = new ArrayList<>(); // 存储数据
for (int i = 0; i <= sheet.getLastRowNum(); i++) { // 对每一行进行处理
Row row = sheet.getRow(i); // 获取行对象
if (row != null) {
Cell cell = row.getCell(1); // 获取指定列的单元格
if (cell != null && cell.getCellType() == CellType.NUMERIC) {
data.add(cell.getNumericCellValue()); // 将数据添加到列表中
}
}
}
if (data.size() > 0) { // 如果存在数据
double missingValue = 0; // 缺失值
Row row = sheet.getRow(rowIndex); // 获取当前行对象
if (row != null) {
Cell cell = row.getCell(1); // 获取指定列的单元格
if (cell == null || cell.getCellType() == CellType.BLANK) { // 如果单元格为空
missingValue = 0; // 缺失值为 0
} else if (cell.getCellType() == CellType.NUMERIC) {
missingValue = cell.getNumericCellValue(); // 缺失值为单元格中的值
} else if (cell.getCellType() == CellType.STRING) {
try {
missingValue = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
} catch (NumberFormatException e) {
missingValue = 0; // 转换失败则缺失值为 0
}
}
}
if (missingValue > 0) { // 如果缺失值大于 0
return missingValue; // 直接返回缺失值
} else {
List<Double> distances = new ArrayList<>(); // 存储距离
for (double value : data) { // 遍历数据
double distance = Math.abs(value - missingValue); // 计算距离
distances.add(distance); // 将距离添加到列表中
}
// 对距离进行排序
distances.sort(Double::compare);
int k = 3; // 取前三个最近的邻居
double sum = 0; // 总和
int count = 0; // 计数器
for (int i = 0; i < k && i < distances.size(); i++) { // 对前 k 个最近的邻居进行处理
double value = data.get(distances.indexOf(distances.get(i))); // 获取对应的值
sum += value; // 累加值
count++; // 计数器加 1
}
if (count > 0) { // 如果计数器大于 0
return sum / count; // 返回平均值
} else {
return 0; // 否则返回 0
}
}
} else {
return 0; // 如果不存在数据,则返回 0
}
}
// 解析日期
private static Date parseDate(String dateString) {
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 fillMissingData(Sheet sheet) {
int rowIndex = 1; // 行索引
int columnIndex = 0; // 列索引
List<Date> dates = new ArrayList<>(); // 存储日期
Map<String, List<Date>> monthData = new HashMap<>(); // 存储每个月份的数据
while (rowIndex <= sheet.getLastRowNum()) { // 对每一行进行处理
Row row = sheet.getRow(rowIndex); // 获取行对象
if (row != null) {
Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
if (cell != null && cell.getCellType() == CellType.STRING) {
Date date = parseDate(cell.getStringCellValue()); // 解析日期
if (date != null) {
dates.add(date); // 将日期添加到列表中
String month = new SimpleDateFormat("yyyy/MM").format(date); // 获取月份
if (monthData.containsKey(month)) {
monthData.get(month).add(date);
} else {
List<Date> monthDates = new ArrayList<>();
monthDates.add(date);
monthData.put(month, monthDates);
}
}
}
}
rowIndex++; // 行索引加 1
}
if (dates.size() > 0) { // 如果存在日期
Collections.sort(dates); // 对日期进行排序
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // 创建日期格式化器
Date startDate = dates.get(0); // 获取起始日期
Date endDate = dates.get(dates.size() - 1); // 获取结束日期
int monthCount = getMonthCount(startDate, endDate); // 获取月份差
if (monthCount > 0) { // 如果月份差大于 0
rowIndex = 1; // 行索引重置为 1
for (Map.Entry<String, List<Date>> entry : monthData.entrySet()) {
String month = entry.getKey();
List<Date> monthDates = entry.getValue();
Collections.sort(monthDates); // 对每个月的日期进行排序
if (monthDates.size() < 5) { // 如果数据组数不足五组
int missingCount = 5 - monthDates.size(); // 计算缺失的月份数
for (int i = 0; i < missingCount; i++) { // 对每个缺失的月份进行处理
Row newRow = sheet.createRow(rowIndex + i); // 创建新的行
Cell newCell = newRow.createCell(columnIndex); // 创建新的单元格
Date newDate = getNextMonth(monthDates.get(monthDates.size() - 1), i + 1); // 获取下一个月的日期
newCell.setCellValue(dateFormat.format(newDate)); // 将日期填入单元格
double avg = calculateKNN(sheet, rowIndex - 1); // 计算KNN邻近算法填充的值
if (avg > 0) { // 如果填充的值大于 0
Cell valueCell = newRow.createCell(1); // 创建新的单元格
valueCell.setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格
}
}
rowIndex += missingCount; // 行索引加上缺失的月份数
}
rowIndex += monthDates.size(); // 行索引加上当前月的组数
}
}
}
}
// 获取月份差
private static int getMonthCount(Date startDate, Date endDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM"); // 创建日期格式化器
String startMonth = dateFormat.format(startDate); // 获取起始月份
String endMonth = dateFormat.format(endDate); // 获取结束月份
String[] startMonthArray = startMonth.split("/"); // 分割起始月份
String[] endMonthArray = endMonth.split("/"); // 分割结束月份
int startYear = Integer.parseInt(startMonthArray[0]); // 获取起始年份
int endYear = Integer.parseInt(endMonthArray[0]); // 获取结束年份
int startMonthNumber = Integer.parseInt(startMonthArray[1]); // 获取起始月份
int endMonthNumber = Integer.parseInt(endMonthArray[1]); // 获取结束月份
return (endYear - startYear) * 12 + (endMonthNumber - startMonthNumber) + 1; // 计算月份差
}
// 获取下一个月的日期
private static Date getNextMonth(Date date, int count) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // 创建日期格式化器
String dateString = dateFormat.format(date); // 格式化日期
String[] dateArray = dateString.split("/"); // 分割日期
int year = Integer.parseInt(dateArray[0]); // 获取年份
int month = Integer.parseInt(dateArray[1]); // 获取月份
int day = Integer.parseInt(dateArray[2].substring(0, 2)); // 获取日份
int hour = Integer.parseInt(dateArray[2].substring(3)); // 获取小时数
int daysInMonth = getDaysInMonth(year, month); // 获取该月份的天数
if (day > daysInMonth) { // 如果日份大于该月份的天数
day = daysInMonth; // 日份为该月份的天数
}
if (hour >= 24) { // 如果小时数大于等于 24
hour = 0; // 小时数为 0
day++; // 日份加 1
if (day > daysInMonth) { // 如果日份大于该月份的天数
day = 1; // 日份为 1
month++; // 月份加 1
if (month > 12) { // 如果月份大于 12
month = 1; // 月份为 1
year++; // 年份加 1
}
}
}
month += count; // 月份加上指定的月份数
if (month > 12) { // 如果月份大于 12
month = 1; // 月份为 1
year++; // 年份加 1
}
daysInMonth = getDaysInMonth(year, month); // 获取该月份的天数
if (day > daysInMonth) { // 如果日份大于该月份的天数
day = daysInMonth; // 日份为该月份的天数
}
String newDateString = String.format("%04d/%02d/%02d %02d:00", year, month, day, hour); // 格式化新的日期
return parseDate(newDateString); // 解析新的日期
}
// 获取指定年份和月份的天数
private static int getDaysInMonth(int year, int month) {
switch (month) {
case 2 -> {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return 29; // 闰年二月份有 29 天
} else {
return 28; // 平年二月份有 28 天
}
}
case 4, 6, 9, 11 -> {
return 30; // 四月、六月、九月、十一月份有 30 天
}
default -> {
return 31; // 其他月份有 31 天
}
}
}
}
原文地址: https://www.cveoy.top/t/topic/oXpl 著作权归作者所有。请勿转载和采集!