// 导入必要的库 package org.example;

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.Comparator; // 用于排序 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 工作簿工厂 import org.apache.poi.xssf.usermodel.XSSFChart; // Excel 折线图 import org.apache.poi.xssf.usermodel.XSSFChartAxis; // Excel 折线图坐标轴 import org.apache.poi.xssf.usermodel.XSSFChartLegend; // Excel 折线图图例 import org.apache.poi.xssf.usermodel.XSSFClientAnchor; // Excel 折线图锚点 import org.apache.poi.xssf.usermodel.XSSFColor; // Excel 颜色 import org.apache.poi.xssf.usermodel.XSSFLineChartData; // Excel 折线图数据 import org.apache.poi.xssf.usermodel.XSSFLineChartData.Series; // Excel 折线图系列 import org.apache.poi.xssf.usermodel.XSSFLineChartSeries; // Excel 折线图系列 import org.apache.poi.xssf.usermodel.XSSFValueAxis; // Excel 折线图数值轴

public class knn {

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 格式化器,用于保留两位小数
        // 对每个月的数据进行处理
        Map<String, List<Double>> monthData = new HashMap<String, List<Double>>(); // 存储每个月的数据
        SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy/MM'); // 创建日期格式化器,用于解析日期
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i); // 获取行对象
            if (row != null) {
                Cell cell = row.getCell(0); // 获取第一列单元格
                if (cell != null && cell.getCellType() == CellType.STRING) {
                    String dateString = cell.getStringCellValue(); // 获取日期字符串
                    Date date = parseDate(dateString); // 解析日期
                    if (date != null) {
                        String monthString = dateFormat.format(date); // 获取月份字符串
                        if (!monthData.containsKey(monthString)) {
                            monthData.put(monthString, new ArrayList<Double>()); // 如果不存在该月份的数据,则创建新的列表
                        }
                        Cell valueCell = row.getCell(1); // 获取第二列单元格
                        if (valueCell != null && valueCell.getCellType() == CellType.NUMERIC) {
                            double value = valueCell.getNumericCellValue(); // 获取值
                            monthData.get(monthString).add(value); // 将值添加到对应的列表中
                        }
                    }
                }
            }
        }
        // 对每个月的数据进行补充
        for (String monthString : monthData.keySet()) {
            List<Double> data = monthData.get(monthString); // 获取该月份的数据列表
            if (data.size() < 5) { // 如果数据少于五个
                int year = Integer.parseInt(monthString.substring(0, 4)); // 获取年份
                int month = Integer.parseInt(monthString.substring(5)); // 获取月份
                for (int i = data.size() + 1; i <= 5; i++) { // 对缺失的数据进行补充
                    int day = i * 5; // 计算日期
                    Date date = new Date(year - 1900, month - 1, day); // 创建日期对象
                    String dateString = dateFormat.format(date); // 格式化日期字符串
                    sheet.createRow(sheet.getLastRowNum() + 1).createCell(0).setCellValue(dateString); // 创建新的行,并填入日期
                    double avg = calculateKNN(sheet, sheet.getLastRowNum(), 1); // 计算KNN邻近算法填充的值
                    if (avg > 0) { // 如果填充的值大于 0
                        sheet.getRow(sheet.getLastRowNum()).createCell(1).setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格
                        data.add(avg); // 将填充的值添加到列表中
                    }
                }
            }
        }
        // 将新旧数据在新建的execl里用折线图展示出来
        Sheet chartSheet = workbook.createSheet('Chart'); // 创建新的工作表
        int chartRowNum = 0; // 折线图所在行号
        for (String monthString : monthData.keySet()) {
            List<Double> data = monthData.get(monthString); // 获取该月份的数据列表
            if (data.size() > 0) { // 如果存在数据
                // 创建折线图
                XSSFChart chart = (XSSFChart) chartSheet.createDrawingPatriarch().createChart(new XSSFClientAnchor(0, 0, 0, 0, 0, chartRowNum, 10, chartRowNum + 15)); // 创建锚点并创建折线图
                chart.setTitleText(monthString); // 设置标题
                chart.setTitleOverlay(false); // 不显示标题覆盖
                XSSFChartLegend legend = chart.getOrCreateLegend(); // 获取图例
                legend.setPosition(org.apache.poi.xssf.usermodel.XSSFChartLegend.LegendPosition.BOTTOM); // 设置图例位置
                XSSFValueAxis valueAxis = chart.getChartAxisFactory().createValueAxis(org.apache.poi.ss.usermodel.charts.AxisPosition.LEFT); // 创建数值轴
                valueAxis.setCrosses(org.apache.poi.ss.usermodel.charts.AxisCrosses.AUTO_ZERO); // 设置交叉轴
                XSSFChartAxis categoryAxis = chart.getChartAxisFactory().createCategoryAxis(org.apache.poi.ss.usermodel.charts.AxisPosition.BOTTOM); // 创建分类轴
                categoryAxis.setCrosses(org.apache.poi.ss.usermodel.charts.AxisCrosses.AUTO_ZERO); // 设置交叉轴
                // 创建折线图数据
                XSSFLineChartData chartData = chart.getChartDataFactory().createLineChartData();
                // 创建折线图系列
                XSSFLineChartSeries series = (XSSFLineChartSeries) chartData.addSeries(categoryAxis, valueAxis);
                // 设置系列名称
                series.setTitle('Data');
                // 创建系列数据
                List<Double> values = new ArrayList<Double>();
                for (double value : data) {
                    values.add(Double.parseDouble(df.format(value))); // 将数据保留两位小数并添加到列表中
                }
                // 设置系列数据
                series.setValues(values);
                // 设置系列颜色
                XSSFColor color = new XSSFColor(new java.awt.Color(255, 0, 0)); // 红色
                series.setLineColor(color);
                // 添加折线图系列到折线图数据中
                chartData.addSeries(series);
                // 将折线图数据添加到折线图中
                chart.plot(chartData);
                chartRowNum += 20; // 更新折线图所在行号
            }
        }
        workbook.write(outputStream); // 将工作簿写入输出文件
        System.out.println('Data filling and chart generation completed.'); // 输出信息
    } catch (Exception e) { // 捕获异常
        e.printStackTrace();
    }
}

// 计算KNN邻近算法填充的值
private static double calculateKNN(Sheet sheet, int rowIndex, int columnIndex) {
    List<Double> data = new ArrayList<Double>(); // 存储数据
    for (int i = 0; i <= sheet.getLastRowNum(); i++) { // 对每一行进行处理
        Row row = sheet.getRow(i); // 获取行对象
        if (row != null) {
            Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
            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(columnIndex); // 获取指定列的单元格
            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<Double>(); // 存储距离
            for (double value : data) { // 遍历数据
                double distance = Math.abs(value - missingValue); // 计算距离
                distances.add(distance); // 将距离添加到列表中
            }
            Collections.sort(distances, new Comparator<Double>() { // 对距离进行排序
                @Override
                public int compare(Double o1, Double o2) {
                    return Double.compare(o1, o2);
                }
            });
            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
    }
}
Excel 数据填充及折线图生成 - 基于 KNN 算法

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

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