'excel 업로드'에 해당되는 글 1건

Excel Insert, poi

2014. 8. 12. 22:01 Spring/Java

관리자 쪽 서비스를 구현하다 보면, 엑셀에 있는 내용을 일괄적으로 DB에 넣는 작업이 필요할 때가 있다-
Cell에 있는 값의 유효성(null, text, numeric 구분 등)을 하나하나 체크하는 것은 일이 너무 많은 관계로 기본적 내용만을 구현하였다-
나중에 손쉬운 방법을 알아내면 다시 포스팅해야 겠다-

1. pom.xml에 poi를 넣어준다-
1
2
3
4
5
6

<!-- Apache POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.10-FINAL</version> </dependency>


2. Browser에 보여질 내용을 작성한다-
파일 처리, 파일 유효성 체크, Devoops로 진행중인 프로젝트라 페이지 이동보단 ajax submit을 이용한 ajax 처리를 하였다-
<html 부분> 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19

<div class="card"> <h4 class="page-header"><strong>**주의 사항**</strong></h4> <form id="excelUpForm" class="form-horizontal panel-body" role="form" action="" method="post" enctype="multipart/form-data"> <p>* 엑셀 파일만 업로드 가능합니다.</p> <p>* 첫 번째 시트에 데이터가 있어야 합니다. [시트명 : Sheet1]</p> <p>* 엑셀 작성 시, 중간에 빈 줄이 없어야 합니다.</p> <a href="/resources/template/Company_Form.xls" class="btn btn-primary">양식 다운로드</a> <div class="form-group"> <label class="col-sm-2 control-label" style="padding-top : 0px;">엑셀 파일</label> <div class="col-sm-6">

<input id="excel" type="file" class="form-control" name="excel" /> </div> </div> <div class="form-inline"> <button type="button" id="excelUp" onclick="check()" class="btn btn-success pull-right">등록하기</button> </div> </form> </div>

<jquery.form.js 추가>

1
<script src="/resources/js/jquery.form.js"></script>

<javascript 부분>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function checkFileType(filePath){
	var fileFormat = filePath.split(".");
	if(fileFormat.indexOf("xls") > -1){
	    return true;
	}else{
	    return false;
	}
}

function check(){
    var file = $("#excel").val();
    if(file == "" || file == null){
        alert("파일을 선택해주세요.");
        return false;
    }else if(!checkFileType(file)){
        alert("엑셀 파일만 업로드 해주세요.");
        return false;
    }
    
    if(confirm("업로드 하시겠습니까?")){
        $("#excelUpForm").attr("action", "/admin/compExcelUpload");
   		var options = {
   			success : function(data) {
   				alert("모든 데이터가 업로드 되었습니다.");
   				$("#ajax-content").html(data);
   			},
   			type : "POST"
   		};
   		$('form').ajaxSubmit(options);
    }
}


3. Server에서 excel 처리-

파일을 따로 저장할 필요가 없어서, 받은 파일의 input stream으로 workbook을 만들고-

각 Column을 VO객체에 담아서 ArrayList를 만들었다-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@RequestMapping(value = "admin/compExcelUpload")
public ModelAndView excelUpload(MultipartHttpServletRequest req) throws ParseException{
	mav = new ModelAndView("/admin/comp_list");
	
	MultipartFile file = req.getFile("excel");

	ArrayList<CompanyDetailVO> comp_list = new ArrayList<>();
	if (file != null && file.getSize() > 0) {
		try {
			Workbook wb = new HSSFWorkbook(file.getInputStream());
			Sheet sheet = wb.getSheetAt(0);
			
			int last = sheet.getLastRowNum();
			System.out.println("Last : " + last);
			for(int i=1; i<=last; i++){
				Row row = sheet.getRow(i);
				CompanyDetailVO company = new CompanyDetailVO();
				
				String company_name = row.getCell(0, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
				
				if(!company_name.equals("") && company_name != null){
					company.setCompany_name(company_name);
					company.setCompany_ceo(row.getCell(1, Row.CREATE_NULL_AS_BLANK).getStringCellValue());					
					company.setIncorp_date(row.getCell(2, Row.CREATE_NULL_AS_BLANK).getDateCellValue());
					company.setStaff_cnt((int) row.getCell(3, Row.CREATE_NULL_AS_BLANK).getNumericCellValue());
					company.setCompany_url(row.getCell(4, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_sales((int) row.getCell(5, Row.CREATE_NULL_AS_BLANK).getNumericCellValue());
					company.setCompany_type(row.getCell(6, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
						
					String zipcode = row.getCell(7, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
					String[] zipArray = zipcode.split("-");					
					company.setCompany_zipcode1(zipArray[0]);
					company.setCompany_zipcode2(zipArray[1]);
					
					company.setCompany_addr(row.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_detail_addr(row.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_telnumber(row.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_ad_url1(row.getCell(11, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_ad_url2(row.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_ad_url3(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_ad_url4(row.getCell(14, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_ad_url5(row.getCell(15, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
					company.setCompany_ad_url6(row.getCell(16, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
						
					comp_list.add(company);	
				}					
			}				
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
	}
		
	service.insertCompExcel(comp_list);		
	mav.addObject("comp_list", service.getCompanies());
		
	return mav;
}


4. 추가적으로 MyBatis 다중 Insert

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15

<insert id="insertCompExcel" parameterType="HashMap"> INSERT INTO COMPANY_DETAIL( `COMPANY_NAME`, `COMPANY_CEO`, `INCORP_DATE`, `STAFF_CNT`, `COMPANY_URL`, `COMPANY_SALES`, `COMPANY_TYPE`, `COMPANY_ZIPCODE1`, `COMPANY_ZIPCODE2`, `COMPANY_ADDR`, `COMPANY_DETAIL_ADDR`, `COMPANY_TELNUMBER`, `COMPANY_AD_URL1`, `COMPANY_AD_URL2`, `COMPANY_AD_URL3`, `COMPANY_AD_URL4`, `COMPANY_AD_URL5`, `COMPANY_AD_URL6` ) VALUES <foreach collection="comp_list" item="item" separator=" , "> ( #{item.company_name}, #{item.company_ceo}, #{item.incorp_date}, #{item.staff_cnt}, #{item.company_url}, #{item.company_sales}, #{item.company_type}, #{item.company_zipcode1}, #{item.company_zipcode2}, #{item.company_addr}, #{item.company_detail_addr}, #{item.company_telnumber}, #{item.company_ad_url1}, #{item.company_ad_url2}, #{item.company_ad_url3}, #{item.company_ad_url4}, #{item.company_ad_url5}, #{item.company_ad_url6} ) </foreach> </insert>


'Spring/Java' 카테고리의 다른 글

BLOB으로 저장 된 이미지 출력  (0) 2014.08.13
AOP 사용, 어노테이션  (0) 2014.08.10
ppt to image/pdf 변환  (0) 2014.08.10
간단한 암호화, MD5, SHA1  (0) 2014.08.10
MyBatis 연결 설정  (0) 2014.08.09

Recent Posts

Recent Comments

Recent Trackbacks