-
[java] 엑셀 데이터 추출해오기 - Apache POI (in intellij)java 2023. 6. 19. 00:10
1. 포이 라이브러리 설치하기
https://poi.apache.org/download.htmlApache POI - Download Release Artifacts
<!--+ |breadtrail +--> <!--+ |start Menu, mainarea +--> <!--+ |start Menu +--> <!--+ |end Menu +--> <!--+ |start content +--> Apache POI - Download Release Artifacts Available Downloads This page provides instructions on how to download and verify the Apac
poi.apache.org
Binary Artifacts 클릭 ->poi-bin-5.0.0-20210120.zip 설치
2. 경로 설정해주기
파일 -> 프로젝트 구조총 3가지를 적용
간단한 예제
바탕화면에 있는 a.xlsx 엑셀파일에서 1열 2열에 해당하는 값을 가져와서 총 합을 구하기MAC 맥에서 경로설정 : /Users/사용자이름 으로 시작.
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; public class Macro { public static void main(String[] args) { String filePath = "/Users/___/Desktop/a.xlsx"; // 엑셀 파일 경로 // 1열과 2열의 값을 덧셈 double sum = sumExcelColumns(filePath, 0, 1); System.out.println("Sum of columns 1 and 2: " + sum); } // 엑셀 파일의 두 열(column) 값을 덧셈 private static double sumExcelColumns(String filePath, int column1Index, int column2Index) { try (FileInputStream fileInputStream = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fileInputStream)) { Sheet sheet = workbook.getSheetAt(0); // 첫 번째 시트 선택 int rowCount = sheet.getLastRowNum() + 1; // 행(row) 개수 double sum = 0.0; for (int i = 0; i < rowCount; i++) { Row row = sheet.getRow(i); Cell cell1 = row.getCell(column1Index); Cell cell2 = row.getCell(column2Index); double value1 = cell1.getNumericCellValue(); double value2 = cell2.getNumericCellValue(); sum += value1 + value2; } return sum; } catch (IOException e) { e.printStackTrace(); return 0.0; } } }
출력 Sum of columns 1 and 2: 54.0
'java' 카테고리의 다른 글
[java] 인터페이스 사용법 (0) 2023.07.01 메소드 오버로딩 vs 메소드 오버라이딩 (0) 2023.06.27 7장 연습문제 (0) 2023.01.31 ClassCastException (0) 2023.01.31 String.join (0) 2023.01.27