less than 1 minute read

  • 그래들
compile group: 'org.apache.poi', name: 'poi', version: '3.11'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.11'

compile group: 'commons-io', name: 'commons-io', version: '2.4'
  • 코드
@RestController
@RequestMapping("/excel")
public class ExcelController {
	
	@RequestMapping("/read")
	public String readExcel(@RequestParam("file") MultipartFile file)
		      throws IOException { // 2

		    List<String> dataList = new ArrayList<>();

		    String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // 3

		    if (!extension.equals("xlsx") && !extension.equals("xls")) {
		      throw new IOException("엑셀파일만 업로드 해주세요.");
		    }

		    Workbook workbook = null;

		    if (extension.equals("xlsx")) {
		      workbook = new XSSFWorkbook(file.getInputStream());
		    } else if (extension.equals("xls")) {
		      workbook = new HSSFWorkbook(file.getInputStream());
		    }

		    Sheet worksheet = workbook.getSheetAt(0);

		    for (int i = 0; i < worksheet.getPhysicalNumberOfRows(); i++) { // 4

		      Row row = worksheet.getRow(i);

		      String data = "";
		      
		      if (row != null) {
		    	  int cellCount = row.getPhysicalNumberOfCells();
		    	  for (int j=0; j <= cellCount; j++) {
		    		  Cell cell=row.getCell(j);
		    		  String value = "";
		    		  if(cell==null){
		                  continue;
		              }else{
		                  //타입별로 내용 읽기
		                  switch (cell.getCellType()){
		                  case XSSFCell.CELL_TYPE_FORMULA:
		                      value=cell.getCellFormula();
		                      break;
		                  case XSSFCell.CELL_TYPE_NUMERIC:
		                      value=cell.getNumericCellValue()+"";
		                      break;
		                  case XSSFCell.CELL_TYPE_STRING:
		                      value=cell.getStringCellValue()+"";
		                      break;
		                  case XSSFCell.CELL_TYPE_BLANK:
		                      value=cell.getBooleanCellValue()+"";
		                      break;
		                  case XSSFCell.CELL_TYPE_ERROR:
		                      value=cell.getErrorCellValue()+"";
		                      break;
		                  }
		              }
		    		  System.out.println("각 셀의 내용 : "+ value);
		    	  }
		      }
		    }

		    

		    return "excelList";

		  }
}

참고 : https://shinsunyoung.tistory.com/71

Categories:

Updated: