以下是一个示例代码,演示了如何使用Apache POI根据其他列的操作更新列:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
public class UpdateColumnBasedOnOtherColumns {
public static void main(String[] args) {
try {
// 读取Excel文件
FileInputStream fis = new FileInputStream("input.xlsx");
Workbook workbook = WorkbookFactory.create(fis);
fis.close();
// 获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
// 遍历每一行
for (Row row : sheet) {
// 获取第一列的值
Cell cell1 = row.getCell(0);
String value1 = cell1.getStringCellValue();
// 获取第二列的值
Cell cell2 = row.getCell(1);
double value2 = cell2.getNumericCellValue();
// 根据第二列的值更新第三列
Cell cell3 = row.createCell(2);
if (value2 > 10) {
cell3.setCellValue(value1 + " - High");
} else {
cell3.setCellValue(value1 + " - Low");
}
}
// 将更新后的Excel保存到文件
FileOutputStream fos = new FileOutputStream("output.xlsx");
workbook.write(fos);
fos.close();
System.out.println("Excel文件更新成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码假设你有一个名为input.xlsx
的Excel文件,其中包含三列数据。第一列为字符串类型,第二列为数字类型。代码通过遍历每一行,根据第二列的值更新第三列。如果第二列的值大于10,第三列将被更新为“原始字符串 - High”,否则将被更新为“原始字符串 - Low”。
最后,代码将更新后的Excel保存到名为output.xlsx
的文件中。