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태그가 엑셀에 모두 표시되면, 그러므로 엑셀에서 셀하나에 모든 문자가 들어가 있는 채로 다운로드되어 제대로 만들어지지 않았다. 결국 자바에서 직접 엑셀 폼을 만들어 다운로드 하는 방법만 되더라.