Java Excel 数据填充:使用 Apache POI 计算平均值并写入 Excel 文件
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.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 test09 {
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('#.##');
if(cell == null){
cell = row.createCell(1);
}
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;
}
}
}
原文地址: https://www.cveoy.top/t/topic/oNl2 著作权归作者所有。请勿转载和采集!