package com.siwei.rsmonitoring.service.impl;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class ReadMultiSheetXLSXToMap {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream(new File("D:\\02DATA\\图斑\\业务研判示例\\wuchuan0705.xlsx"));
             Workbook workbook = new XSSFWorkbook(fis)) {

            // 获取工作簿中 sheet 的数量
            int numberOfSheets = workbook.getNumberOfSheets();

            // 遍历每个 sheet
            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                System.out.println("Sheet 名称: " + sheet.getSheetName());

                // 获取第一行作为列名
                Row headerRow = sheet.getRow(0);
                List<String> headers = new ArrayList<>();
                for (Cell cell : headerRow) {
                    headers.add(cell.getStringCellValue());
                }

                // 从第二行开始遍历数据行
                for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                    Row row = sheet.getRow(j);
                    Map<String, Object> rowData = new HashMap<>();

                    // 遍历每个单元格
                    for (int k = 0; k < headers.size(); k++) {
                        Cell cell = row.getCell(k);
                        Object cellValue = null;
                        if (cell != null) {
                            switch (cell.getCellType()) {
                                case STRING:
                                    cellValue = cell.getStringCellValue();
                                    break;
                                case NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        cellValue = cell.getDateCellValue();
                                    } else {
                                        cellValue = cell.getNumericCellValue();
                                    }
                                    break;
                                case BOOLEAN:
                                    cellValue = cell.getBooleanCellValue();
                                    break;
                                case FORMULA:
                                    cellValue = cell.getCellFormula();
                                    break;
                                default:
                                    cellValue = null;
                            }
                        }
                        // 将单元格值存入 Map，键为列名
                        rowData.put(headers.get(k), cellValue);
                    }
                    // 打印每行数据的 Map
                    System.out.println(rowData);
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
