日期 数据202159 1000 2614202292 1000 2411202293 1000 2662202293 1000 2556202294 800 2556202295 800 2537202296 800 202298 800 29012022915 800 29042022922 800 29032022102 800 289620
以下是可能的Java代码实现:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelDataFiller {
public static void main(String[] args) {
String inputFile = "input.xlsx";
String outputFile = "output.xlsx";
try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile));
FileOutputStream outputStream = new FileOutputStream(outputFile)) {
Sheet sheet = workbook.getSheetAt(0);
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) {
// do nothing
} else {
double avg = calculateAverage(sheet, i, 1);
if (avg > 0) {
DecimalFormat df = new DecimalFormat("#.##");
cell.setCellValue(Double.parseDouble(df.format(avg)));
}
}
}
}
workbook.write(outputStream);
System.out.println("Data filling completed.");
} catch (Exception e) {
e.printStackTrace();
}
}
private static double calculateAverage(Sheet sheet, int rowIndex, int columnIndex) {
double sum = 0;
int count = 0;
for (int i = rowIndex - 1; i >= 0; i--) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(columnIndex);
if (cell != null && cell.getCellType() != CellType.BLANK) {
sum += cell.getNumericCellValue();
count++;
break;
}
}
}
for (int i = rowIndex + 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(columnIndex);
if (cell != null && cell.getCellType() != CellType.BLANK) {
sum += cell.getNumericCellValue();
count++;
break;
}
}
}
if (count > 0) {
return sum / count;
} else {
return 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;
}
}
}
在此示例中,我们使用了Apache POI库来处理Excel文件。我们首先打开输入文件并获取第一张工作表。然后,我们遍历每一行,如果第二列为空白单元格,则计算它上下相邻的数据的平均值,并将结果填充到该单元格中。
计算平均值时,我们遍历该单元格上下的行,找到第一个非空白单元格,并将其作为起点或终点计算平均值。我们忽略空白单元格。
最后,我们将填充后的数据写入输出文件中。
请注意,此代码假定日期格式为“yyyy/MM/dd HH:mm”,并且数据列为第二列(B列)。如果您的实际情况不同,请相应地更改代码
原文地址: https://www.cveoy.top/t/topic/hkzz 著作权归作者所有。请勿转载和采集!