2016년 12월 13일 화요일

### JAVA Excel POI, Cell Style 배경색 채우기

### JAVA Excel POI, Cell Style 배경색 채우기

Excel Form 만들때, 아래 처럼 Cell에 Style을 넣을 수 있다.

아래 예제는 Cell에 배경색을 넣는 예제이다.






String color = "#FF0F0F";

//16진수값을 R,G,B값으로 변환
int colorR = Integer.parseInt( color.substring(1, 3), 16);
int colorG = Integer.parseInt( color.substring(3, 5), 16);

int colorB = Integer.parseInt( color.substring(5, 7), 16);

//직접 RGB 컬러값을 사용하는 경우 아래와 같이 getCustomPalette()를 사용해야 컬러값이 적용된다.
palette = workbook.getCustomPalette();
HSSFColor myColor = palette.findSimilarColor(colorR, colorG, colorB);

//cell에 style 만들기
style = workbook.createCellStyle();
style.setFillForegroundColor(myColor.getIndex()); //위에 컬러값의 index값으로 칼라값을 지정해주게된다.
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //컬러가 cell에 적용되는 style 정의
cell.setCellStyle(style); //style을 cell에 적용

//cell에 표시할 value 값을 적용
HSSFRichTextString text = new HSSFRichTextString(value);                

cell.setCellValue(text);





* 참고 )

256 색상값만 사용가능하다. myColor.getIndex()에서 흐릿한 색상은 256 칼라 중 유사한 칼라 값을 불러오지만, 대부분 흰색 값(9) 로 처리한다.













2016년 12월 9일 금요일

[Spring Boot] JAVA에서 Excel 폼 작성 후, 다운로드 하기


### JAVA에서 Excel 폼 작성 후, 다운로드 하기



# 개발환경 : SPRING BOOT + JPA + MySQL



1. html파일에서 엑셀다운로드 실행위해 엑셀다운로드 버튼 클릭



<button id="xls_btn" type="button" onClick="javascript:goXls()">엑셀다운로드</button>
<script>
    function goXls() {
           location.href="/xls";
      }
</script>


2. Controller 클래스에서 Excel폼을 작성을 위한 데이타를 Map 에 담아서 엑셀폼만드는 Class로 보내기


@Controller

public class XlsController {

    @RequestMapping(value="/xls", method=RequestMethod.GET)  
    public ModelAndView viewExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> model = new HashMap<String, Object>();
model.put("sheetname", date); //Sheet Name
    
List<String> titles = new ArrayList<String>();
titles.add("예제");
titles.add("");
titles.add("");
model.put("titles", titles); //titles List
    
List<String> headers = new ArrayList<String>(); 
headers.add("목록1");
headers.add("목록2");
headers.add("목록3");
model.put("headers", headers); //headers List
        List<List<String>> bodyList = new ArrayList<List<String>>(); 

List<String> body = new ArrayList<String>(); 
body.add("DATA1");
body.add("DATA2");
body.add("DATA3");
        bodyList.add(body);

        List<String> body = new ArrayList<String>(); 
body.add("DATA1");
body.add("DATA2");
body.add("DATA3");
        bodyList.add(body);

model.put("body", bodyList); //body List
      
      response.setContentType( "application/ms-excel" );
        response.setHeader( "Content-disposition", "attachment; filename=data.xls" );
               
    return new ModelAndView(new MakingExcelForm(), model);
    }
}


3. MakingExcelForm Class에서 엑셀폼 만들기


public class MakingExcelForm extends AbstractExcelView {
  
    @SuppressWarnings("unchecked")
    protected void buildExcelDocument(Map<String, Object> model,
        HSSFWorkbook workbook,
        HttpServletRequest request,
        HttpServletResponse response) {
    
        String sheetName = (String)model.get("sheetname");

        List<String> titles = (List<String>)model.get("titles");
        List<String> headers = (List<String>)model.get("headers");
        List<List<String>> bodyList = (List<List<String>>)model.get("body");
        
        HSSFSheet sheet = workbook.createSheet(sheetName); // create sheet
        sheet.setDefaultColumnWidth((short) 12);
        
        int currentRow = 0;
        int currentColumn = 0;
        
        HSSFCellStyle titleStyle = workbook.createCellStyle(); //title style
        HSSFFont titleFont = workbook.createFont();
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        titleStyle.setFont(titleFont); 
        
        HSSFCellStyle headerStyle = workbook.createCellStyle(); //header style
        HSSFFont headerFont = workbook.createFont();
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(headerFont); 
        
        HSSFRow titleRow = sheet.createRow(currentRow); // create title row
        for(String titletitles){
            HSSFRichTextString text = new HSSFRichTextString(title);
            HSSFCell cell = titleRow.createCell(currentColumn)
            cell.setCellStyle(titleStyle);
            cell.setCellValue(text);            
            currentColumn++;
        }
        
        currentRow++;
        HSSFRow headerRow = sheet.createRow(currentRow); // create header row
        currentColumn = 0;
        for(String headerheaders){
            HSSFRichTextString text = new HSSFRichTextString(header);
            HSSFCell cell = headerRow.createCell(currentColumn)
            cell.setCellStyle(headerStyle);
            cell.setCellValue(text);            
            currentColumn++;
        }
       
        currentRow++;
        for(List<String> body: bodyList){
            currentColumn = 0;
            HSSFRow row = sheet.createRow(currentRow); // create body row
            for(String value : body){
                HSSFCell cell = row.createCell(currentColumn);
        HSSFRichTextString text = new HSSFRichTextString(value);                
        cell.setCellValue(text);
                currentColumn++;
            }
            currentRow++;
        }
    }
}

4. 참고)
- html에서 jquery ajax 또는 form submit으로 다운로드 버튼 실행하면, 엑셀 파일이 다운로드 되지 않는다. 이유는 잘 모르겠지만, href호출로써만 가능했다.

- html에서 생성된 table dom을 자바스크립트를 사용하여 엑셀로 전환시켜 파일을 다운로드하면, html태그가 엑셀에 모두 표시되면, 그러므로 엑셀에서 셀하나에 모든 문자가 들어가 있는 채로 다운로드되어 제대로 만들어지지 않았다. 결국 자바에서 직접 엑셀 폼을 만들어 다운로드 하는 방법만 되더라.










2016년 3월 24일 목요일

php 이미지 크기 조절, html 목록 채우기, 시간체크해서 남은시간 감소시키기(javascript포함)


##### php 이미지 크기
http://blog.iramine.com/entry/PHP-%EC%9D%B4%EB%AF%B8%EC%A7%80-%ED%81%AC%EA%B8%B0-%EB%B3%80%ED%99%98

##### db에서 가져온 값으로 목록 표시 / db시간 에서 현재시간 간격체크해서 남은시간 감소해주는 코드
<?
if($results != null) {
?>
<table class="my_list">
<colgroup>
<col style="width:110px ;" />
<col style="width:420px;" />
<col style="width:60px;" />
<col style="width:340px;" />
<col style="width:270px ;" />
</colgroup>
<tbody>
<?
$item = 0;
foreach($results as $row) {
$item ++;
$publish=$row['PUBLISH'];
$cnt=$row['CNT'];
$id=$row['ID'];
$rating1=$row['RATING'];
$createdat1=$row['CREATEDAT'];
$title=$row['TITLE'];
$image=$row['IMAGE'];
$competi_title=$row['COMPETITION_TITLE'];
$competi_id=$row['COMPETITION_ID'];
?>
<tr>
<td><div class="thp_img"><span><img src="<?=$row['IMAGE']?>" width="80" alt=""/></span></div></td>
<td class="tal"><div class="thp_tit">
<span class="stxt"><?=$row['COMPETITION_TITLE']?></span>
<a href="#" class="ttt"><?=$row['TITLE']?></a>
</div>
</td>
<?
if($publish==0) {//게시자 수정가능
?>
<td><span class="t2">심사중</span></td>
<?
} else if($publish==1){//반려
?>
<td><span class="t3">반려</span></td>
<?
} else {//2 : 게시
?>
<td><span class="t1">게시중</span></td>
<?
}
?>
<td>View <strong><?=number_format((Int)$row['CNT'])?></strong>  /  득표수 <strong><?=number_format((Int)$row['RATING'])?></strong> </td>
<?
if($publish==1){//반려
?>
<td><a href="#" class="btn_type5">재신청하기</a><span class="btnt"></span></td>
<?
} else if($publish==0 || $publish==2){//0 : 심사중 2 : 게시
$createdat = strtotime(date($row['CREATEDAT']));
$finish_time = $createdat + (24*60*60);
$now_time = strtotime(date("Y-m-d H:i:s"));
$remaining_time = $finish_time - $now_time;

if($remaining_time > 0) { //수정시간 지났는지..
?>
<td><a href="#" class="btn_type2">수정신청하기</a><span id='timmer<?=$item?>' class="btnt"></span></td>
 <script>
 timmer<?=$item?>(<?=floor($remaining_time)?>, $("#timmer<?=$item?>"));
 </script>
<?
} else {
?>
<td><a href="#" class="btn_type6">수정신청하기</a><span class="btnt"></span></td>
<?
}
}
?>
</tr>
<?

}
?>










function timmer5(remain_time, view_id) {
remain_time5 = remain_time;
view_id5 = view_id;
timer_id5 = setInterval("decreTime5()", 1000);
}

function decreTime5() {
view_id5.html('수정 가능시간 '+ time_format(remain_time5));
if(remain_time5 > 0) remain_time5--;
else {
// 시간이 0이 되었으므로 타이머를 중지함
clearInterval(timer_id5);
// 시간이 만료되고 나서 할 작업을 여기에 작성
// document.form.submit(); // 예: 강제로 form 실행
}
}

function time_format(v) {
                var value;
var h;
var m;
var i;
h = Math.floor(v / (3600));
m = Math.floor( (v-(h*3600)) / 60 );
i = Math.floor(v - (h*3600) - (m*60));
if(h < 10) h = "0" + h;
if(m < 10) m = "0" + m;
if(i < 10) i = "0" + i;
                value = h + ":" + m + ":" + i;
return value;
}



javascript tip

#### a tag에 onclick 붙이기

<a href="#" class="btn_url" onclick="return form_video();">url등록하기</a>

#### 글자수제한
input :
maxlength="20"

textarea :
//글자수 제한 체크
        function len_chk(){
            var frm = document.insertFrm.test;
            if(frm.value.length > 4000){
                alert("글자수는 영문4000, 한글2000자로 제한됩니다.!");
                frm.value = frm.value.substring(0,4000);
                frm.focus();
            }
        }

#### trim() 대체함수

data = data.replace(/(^\s*)|(\s*$)/gi, "");
            if(data=='') {
            alert('글자없음');

            }


#####jquery checkbox 상태 참고
http://hobbiez.tistory.com/321


###### jQuery 로 ajax 처리시 data 형식 중 배열(array)값을 넘기려면 다음과 같이 ajax 처리 전 세팅값을 바꿔 주어야 한다.
jQuery.ajaxSettings.traditional = true;