과거/Java

엑셀 파일 읽기, 쓰기

청소부 2021. 4. 6. 10:09

1. 개요

 1) 엑셀 파일 읽기

 2) 엑셀 파일 쓰기

 

2. 작업

 1) 라이브러리 추가: apache poi

 

 2) 엑셀 파일 읽기 및 쓰기

public static void main(String[] args) throws Exception{
   List<Employee> empList = new ArrayList<>();
   
   empList = getExcel();  // 1. 엑셀 파일 읽기
   writeExcel(empList);   // 2. 읽은 엑셀 파일 쓰기
  
} // main method end
public static List<Employee> getExcel() throws Exception{
   List<Employee> getEmpList = new ArrayList<>();
   
   String readPath = "읽어들일엑셀파일경로";          // 읽을 파일 경로
   InputStream is = new FileInputStream(readPath);  // inputStream 생성
   
   Workbook workbook = WorkbookFactory.create(is);  // 라이브러리 생성
   
   Sheet sheet = workbook.getSheetAt(0);  // 첫번째 시트 읽기
   Iterator<Row> row = sheet.iterator();
   
   // 행 반복문 돌기
   while(row.hasNext()){
      Employee employee = new Employee();
      Row row = row.next();
      
      if(row.getRowNum() == 0){
         continue;
      }
      
      getEmpList.add(employee);
   }
   
   return getEmpList;
}
public static void writeExcel() throws Exception{
   Stirng path = "파일경로";
   
   FileOutputStream fos = new FileOutputStream(path);
   
   XSSFWorkbook workbook = new XSSFWorkbook();         // 엑셀 라이브러리 생성
   XSSFSheet sheet = workbook.createSheet("직원명단");  // 시트생성
   
   XSSFRow curRow; // 엑셀 row 선언
   
   // 엑셀 row 반복문 돌며 기록
   for(int i = 0; i < list.size(); i++){
      curRow = sheet.createRow(i);
      curRow.createCell(0).setCellValue(list.get(i).getEmpNo());
      curRow.createCell(1).setCellValue(list.get(i).getName());
      curRow.createCell(2).setCellValue(list.get(i).getDepartment());
   }
   
   workbook.write(fos);  // 엑셀내용 쓰기
   fos.close();          // 쓰기 끝났으니 닫기

}