import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelColumnTraversal {
public static void main(String[] args) {
String filePath = “your_file_path.xlsx”;
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(fis)) {
Sheet sheet = workbook.getSheetAt(0);
Row headerRow = sheet.getRow(0);
// 获取列名
List columnNames = new ArrayList<>();
for (Cell cell : headerRow) {
columnNames.add(cell.getStringCellValue());
}
//遍历数据
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < columnNames.size(); j++) {
Cell cell = row.getCell(j);
String value = cell == null ? “” : getCellValue(cell);
System.out.println(columnNames.get(j) + “: " + value);
}
System.out.println(”—");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getCellValue(Cell cell) {
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue().toString();
} else {
return String.valueOf(cell.getNumericCellValue());
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return "";
}
}
}