package com.pms.common.utils; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.pms.service.CommonService; import com.pms.common.utils.CommonUtils; import com.pms.common.utils.Constants; @Component public class WBSParsingUtil { @Autowired CommonService commonService; public static void main(String[] args) { // TODO Auto-generated method stub Map fileMap = new HashMap<>(); fileMap.put("FILE_PATH", Constants.FILE_STORAGE); fileMap.put("SAVED_FILE_NAME", "20180525-WBS.xlsx"); try{ parsingExcelFile(null, null, fileMap); }catch(Exception e){ e.printStackTrace(); } //rows의 경우 버그로 인해 파싱 시 row를 실제 값을 상수로 지정해 주어야함 //버그로 인해 마지막 row를 가져오지 못하고 있음 } /** * 업로드된 Excel File을 통해 데이터를 Parsing 한다. * @param request * @param response * @param fileMap * @return * @throws Exception */ @SuppressWarnings("unchecked") public static Map parsingExcelFile(HttpServletRequest request, Object response, Map fileMap) throws Exception { Map resultMap = new HashMap<>(); String filePath = CommonUtils.checkNull(fileMap.get("FILE_PATH")); String savedFileName = CommonUtils.checkNull(fileMap.get("SAVED_FILE_NAME")); String fullPath = filePath + savedFileName; System.out.println("WBS 파싱 시작 - 파일 경로: " + fullPath); try (FileInputStream fis = new FileInputStream(fullPath); XSSFWorkbook workbook = new XSSFWorkbook(fis)) { XSSFSheet sheet = workbook.getSheetAt(0); List> dataList = new ArrayList<>(); // 헤더 row 처리 (첫 번째 행) XSSFRow headerRow = sheet.getRow(0); List headers = new ArrayList<>(); if (headerRow != null) { int cellCount = headerRow.getPhysicalNumberOfCells(); for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) { XSSFCell cell = headerRow.getCell(cellIndex); String cellValue = getCellValue(cell); headers.add(cellValue); } } // 데이터 row 처리 (두 번째 행부터) int rowCount = sheet.getPhysicalNumberOfRows(); for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) { XSSFRow row = sheet.getRow(rowIndex); if (row == null) continue; Map rowData = new HashMap<>(); int cellCount = Math.max(row.getPhysicalNumberOfCells(), headers.size()); for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) { XSSFCell cell = row.getCell(cellIndex); String cellValue = getCellValue(cell); String columnName = cellIndex < headers.size() ? headers.get(cellIndex) : "COL_" + cellIndex; rowData.put(columnName, cellValue); } dataList.add(rowData); } resultMap.put("success", true); resultMap.put("dataList", dataList); resultMap.put("headers", headers); resultMap.put("totalCount", dataList.size()); System.out.println("WBS 파싱 완료 - 총 " + dataList.size() + "개 행 처리"); } catch (Exception e) { System.err.println("WBS 파싱 중 오류 발생: " + e.getMessage()); e.printStackTrace(); resultMap.put("success", false); resultMap.put("error", e.getMessage()); resultMap.put("dataList", new ArrayList<>()); } return resultMap; } /** * Excel 셀 값을 문자열로 변환 */ private static String getCellValue(XSSFCell cell) { if (cell == null) { return ""; } switch (cell.getCellType()) { case STRING: return cell.getStringCellValue().trim(); case NUMERIC: // 날짜인지 확인 if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { return cell.getDateCellValue().toString(); } else { // 정수인지 실수인지 확인 double numericValue = cell.getNumericCellValue(); if (numericValue == (long) numericValue) { return String.valueOf((long) numericValue); } else { return String.valueOf(numericValue); } } case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case FORMULA: try { return cell.getStringCellValue().trim(); } catch (Exception e) { return String.valueOf(cell.getNumericCellValue()); } case BLANK: default: return ""; } } /** * 데이터베이스 연결 테스트 (개발용) */ public static void testDatabaseConnection() { String url = "jdbc:postgresql://localhost:5432/ilshin"; String username = "postgres"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1")) { if (rs.next()) { System.out.println("데이터베이스 연결 성공"); } } catch (Exception e) { System.err.println("데이터베이스 연결 실패: " + e.getMessage()); e.printStackTrace(); } } }