웹 개발

[spring] file upload ( excel )

노루아부지 2019. 8. 23. 22:09

1. HTML

<form id="multiForm" name="multiForm" method="post" 
		action="/target/multiInsertAction.do" enctype="multipart/form-data">
	
    <input type="file" id="file" name="file"/>
	<button type="submit" class="cm_btn_01"><span>등록</span></button>
</form>

 

2. FileUploadBean

public class FileUploadBean {
	private MultipartFile file;
	
    public MultipartFile getFile() {
		return file;
	}

	public void setFile(MultipartFile file) {
		this.file = file;
	}
}

 

3. Controller

public ModelAndView multiInsertAction(HttpServletRequest request, HttpServletResponse response, FileUploadBean file) throws Exception {
	setReqMap(request, response);
	
	POIFSFileSystem fileSystem = null;
	
    try {
		fileSystem = new POIFSFileSystem(new ByteArrayInputStream(file.getFile().getBytes()));
	}
	catch(Exception e) {
		logger.error("The file uploaded is not an excel file");
		return movePage(listPage);
	}
  
	try {
		HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
		HSSFSheet sheet = workBook.getSheetAt (0);
		Iterator<Row> rows = sheet.rowIterator();
	
		while (rows.hasNext()){
			Row row = (Row)rows.next();
          
			Iterator<Cell> cells = row.cellIterator();
 
			while (cells.hasNext()) {
				Cell cell = (Cell)cells.next();
           
				switch (cell.getCellType ()){
					case HSSFCell.CELL_TYPE_NUMERIC :
						System.out.println ("Numeric value: " + cell.getStringCellValue());                     
						break;
					case HSSFCell.CELL_TYPE_STRING :
						RichTextString richTextString = cell.getRichStringCellValue ();
						System.out.println ("String value: " + richTextString.getString ());
            	        break;
					default :
						System.out.println ("Type not supported.");
				}
			}
		}
	}
	catch(Exception e) {
		logger.error("error reading excel file",e);
		return movePage(listPage);
	}

	return movePage(listPage);
}
728x90
loading