Excel 自动填充数据:根据相邻单元格计算平均值
Excel 自动填充数据:根据相邻单元格计算平均值
使用 Java 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('#.##');
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;
}
}
}
### 问题解决:
- **NullPointerException:** 原代码在填充空单元格时,没有创建新单元格,导致 `cell` 为空,引发 `NullPointerException`。
- **解决方案:** 在代码的 `if` 语句中添加一行代码 `cell = row.createCell(1);`,用于创建新的单元格。
### 代码说明:
1. **`inputFile` 和 `outputFile`:** 分别用于指定输入和输出 Excel 文件的路径。
2. **`WorkbookFactory.create(new FileInputStream(inputFile))`:** 创建 Workbook 对象,用于读取 Excel 文件。
3. **`sheet = workbook.getSheetAt(0)`:** 获取第一个工作表。
4. **`for` 循环:** 循环遍历所有行,检查第 2 列(索引为 1)的单元格是否为空。
5. **`calculateAverage(sheet, i, 1)`:** 计算第 `i` 行第 2 列单元格的相邻两个单元格的平均值。
6. **`cell.setCellValue(Double.parseDouble(df.format(avg)))`:** 将计算得到的平均值填充到空单元格。
7. **`workbook.write(outputStream)`:** 将修改后的 Excel 文件写入到 `outputFile` 指定的路径。
### 总结:
这段代码通过循环遍历 Excel 文件,根据相邻单元格计算平均值,并填入空单元格,自动完成数据填充工作。这个方法能够有效提升工作效率,并避免手动操作可能出现的错误。
**注意:** 本代码仅供参考,请根据实际需求修改代码参数和逻辑。
java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Cell.setCellValue(double)" because "cell" is null at org.example.test09.main(test09.java:35)
**解决方案:**
在第35行之前,添加一行代码,用于创建新的单元格:
`cell = row.createCell(1);`
完整代码如下:
```java
if (cell != null && cell.getCellType() != CellType.BLANK) {
// do nothing
} else {
double avg = calculateAverage(sheet, i, 1);
if (avg > 0) {
DecimalFormat df = new DecimalFormat('#.##');
cell = row.createCell(1); // 添加这行代码
cell.setCellValue(Double.parseDouble(df.format(avg)));
}
}
原文地址: https://www.cveoy.top/t/topic/oNlP 著作权归作者所有。请勿转载和采集!