excel down load 기능을 구현한 api는 많을지 모르지만 검색했을때는 poi를 많이 사용하고 있었고.


현재 내가 다니는 회사도 poi로 구축되어 있는데 하다보니 간단한 부분은 정리해두면 좋을듯 하여 적어본다.





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
  int iRow = 0// 세로출 정의
  int iCol = 0// 가로줄 정의
  Map params = parameters.getMap();
 
 
  Map<StringString> testList =  "DB QUERY LIST";
  
  private String excel_location = PmisConfig.get("excel.template.home");

//WEB-INF 쪽에 EXCEL TEMPLATE경로 지정
  String tmphome = Strings.defaultValue(excel_location, context.getRealPath("excel 양식경로"));  
  String file_name = Strings.defaultValue(params.get("file_nm"), "FILE명"); // 
  FileInputStream fis = new FileInputStream(tmphome + "/" + file_name);
 
  XSSFWorkbook book = new XSSFWorkbook(fis);
  XSSFSheet sheet = book.getSheetAt(0); //EXCEL 시트 지정
 
  Row row = null;
  Cell cell = null
   
/*font style :엑셀 필요 시트에 사용할 STYLE 지정 */
  Font font = book.createFont();
  font.setFontHeightInPoints((short)8);
  font.setFontName("맑은 고딕");
 
 
  XSSFCellStyle cellStyle = book.createCellStyle(); //엑셀에서 사용할 스타일명 지정
  XSSFDataFormat fmt = book.createDataFormat();
 
  /*해당 지정한 스타일에 border 나 배경색 위치정도를 지정해준다.*/
  cellStyle.setFont(font);
  cellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT); //text align 설정
  cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
 
  cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); //border 그려줄 부분 지정
  cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
  cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
  cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
  
 
  cellStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);  
  cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);    //배경색 지정(Back Ground color )
  cellStyle.setWrapText(false);
  
  
  /*data 가져온훈 필요한 부분을 형변한 해준다. data type*/
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //날짜
  SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy.MM");
  DecimalFormat numberFormat = new DecimalFormat("###,###,###.0");// 금액관련 소수점 처리
  DecimalFormat numberFormat2 = new DecimalFormat("###,###");
  Calendar c = Calendar.getInstance();
cs



위의 코드는

excel 구현하기 위한 재료라고 생각하면 될듯하다.

1. sheet 순서

2. excel template 경로

3. excel에서 사용할 font 및 css 정도


이젠 엑셀을 그려보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//그리기 시작할 ROW를 선언 0부터 시작하니 잘 계산해야한다.
  iRow = 2
 //미리 어느정도 그려진 엑셀이라면 GET으로 받아온다. 
  row = sheet.getRow(iRow++);
// 새로운 데이터를 넣어야 한다면 CREATE로 생성
  row = sheet.createRow(iRow++);
  // 해당줄에 시작한 셀의 시작값 0붕터 시작.
  cell = row.getCell(0); 
  // 해당 셀의 스타일 지정
  cell.setCellType(cell.CELL_TYPE_STRING); 
// 필요 VALUE 지정
  cell.setCellValue("넣을값");
//해당셀의 스타일 지정  
  cell.setCellStyle(cellStyle);
  
  //병합(시작 row, 병합 끝 row, 시작col, 끝 col)
  sheet.addMergedRegion(new CellRangeAddress(iRow, iRow+2, iCol, iCol+3 ) );
cs


1. 셀에 data를 넣을 row 지정

2. style 및 css 지정

3. 병합.. 그런데 병합부분은 저렇게 넣으면 css가 안먹히니 미리 병합할 셀들의 css를 주어야한다.

value는 첫번째로 들어옴.


ex)


1
2
3
4
5
6
7
8
9
10
11
12
 
   cell.create(0);
   cell.setCellStyle(cellStyle);
 
   cell.create(1);
   cell.setCellStyle(cellStyle);
 
   cell.create(2);
   cell.setCellStyle(cellStyle);
 
   sheet.addMergedRegion(new CellRangeAddress(iRow, iRow+2, iCol, iCol+3 ) );
 
cs




필요 데이터를 다 생성하였다면 excel download 파일을 만들어야한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  fis.close(); 
 file_nm = "템플릿 파일명.xlsx";
        File outputFile = temporaryFileService.getNewFile(".xlsx");
        OutputStream output = new FileOutputStream(outputFile);
        
        book.write(output);
        
        contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if (outputFile.exists()) {
            exportStream = temporaryFileService.getFileAsStream(outputFile.getName());
            file_nm = URLEncoder.encode(file_nm, "UTF-8").replace("+""%20").replace("%28","(").replace("%29",")");
            file_size = outputFile.length();
        }
        
    Cookie cook = new Cookie(name, URLEncoder.encode(value, "utf-8"));
 
 
        cook.setPath("/");
        response.addCookie(cook);
cs

fis.close: input data를 닫아줌??


1. 템플릿 파일명 지정

2. 템플릿 파일 확장자 지정

3. content Type = Excel 파일로 type 변환

if 문 : 파일명이 공란이면 + 글자가 나오고 "()" 괄호관련 특수문자가 들어가면 %28, %29로 나와서 repalce 처리.

4. cooke 생성


*기존에 구현된 excel을 수정해서 한거라 문법및 여러부분이 틀릴수도있으니.. 틀린부분은 댓글로 알려주세요.!*

1
2
3
4
// 소수 한자리까지만 표시 자동으로 소수둘째 자리에서 반올림
        DecimalFormat numberFormat = new DecimalFormat("###,###.0"); //형변환 Decimal
        numberFormat.format(Double.parseDouble('파라미터로 넘어온 String 값'))
 
cs



무언가에 값을 넣을때 저렇게 형변환하여 처리


ex) 파라미터: 1234.344444 =>쿼리에서 넘어온값.

String test1 = 1234.34444;

String test2 = query.get("test");

numberFormat.format(Double.parseDouble(test));

numberFormat.format(Double.parseDouble(test2));


결과 : 1234.4 로 나온다.


DecimalFormat 에서 소수점 자리를 처리 ###,###.0000 : 

*###뒤에 부분이 소수점 자리수.

calender - roll(int field, int amount) // 일자 정도 구할때만 사용 상위값은 변환 x  //p.249


=====================================================


쓰레드에 안전하게 후견하기 위해선 synchronizedList 생성


ex) List list = Collections.synchronizedList(new ArrayList());


Araay 에서 fill = 특정문자로 채워주는것


ex )

 int[] emptyArray = new int[10];

 Array.fill(emptyArray,0,5,9);


첫번째 는 채울 객체, 두번째 배열의 시작위치, 세번째 배열의 끝위치, 바꿀숫자 p.254



=====================================================


문자열 구분자 분리 StringTokenizer 


ex)

String data = "this is a book";

//StringTokenizer st = new STringTokenizer(data); //결과1

StringTokenizer st = new STringTokenizer(data,"a"); //결과2

1.결과: this, is, a , book

2.결과 : this is, book //a는 결과에 없음 p.259

 

 ** 보통 split으로 자르고 아주큰 메모리 낭비가 심할경우만 StringTokenizer


=====================================================

돈계산관련 중요 math 메소드

BigDecimal// 아직은 돈관련 프로그램을 만들어보지 않았으므로 pass

=====================================================


쓰래드 //p.275

 - 쓰레드의 사전적 의미는 실타래를 의미, 프로세스를 생성하기위해서는 많은 실타래의 쓰래드가 생성되어짐

 - 쓰레드가 시작하면 수행되는 메소드는 run()

 - 쓰레드를 시작하는 메소드는 start();


=====================================================









1.구글에서 java를 검색해여 해당 운영체제 맞는 버전 설치 

java 다운로드 << 클릭


또는 

접속





2. 내컴퓨터> 속성> 고급 시스템 설정> 환경변수 클릭

3. 환경변수 내에서 새로만들기 클릭하여 'JAVA_HOME' 및 JDK 경로 설정

  * JDK 경로 설정시 \bin;을 붙여야만 cmd 창에서 javac 명령어 입력시 적용이 됨


4. Path에 JAVA_HOME 추가

 EX ) %JAVA_HOME%;


5. 윈도우키+R 눌러서 cmd 접속

   javac , java -version 입력하여 확인



1
2
3
4
5
6
7
public void currentTime(){
        //1970년1월1일부터 현재까지의 시간을 밀리초 Nano초로 계산
        long startTime = System.currentTimeMillis();
        long startNanoTime = System.nanoTime();
        System.out.println(startTime);    // 결과: 1495725443222
        System.out.println(startNanoTime);//결과:269033075717973
    }
cs


흠 언제쓸지는 모르겠는데 밀리초와 나노초는..?


올림관련

round(): 반올림, ruturn type : int(float)

rint(): 반올림, return type : double(long) //거의 안쓸듯?


ceil(): 올림,double

floor(): 버림,double


제곱과 제곱근

Math.sqrt():제곱근

Math.cbrt():세제곱근

Math.pow(): 첫번째 매개변수와 두번째 매개변수만큼의 제곱값 구현 

1
2
3
        Integer a = (int) Math.pow(34);
        System.out.println(a);//81
 
cs

Math.scalb(): 첫번째 매개변수 *2^(매개변수) 


1
2
Integer b = (int) Math.scalb(52);
        System.out.println(b);    //20 (5*2^2)

cs






Math.hypot() : 첫번재 매개변수 제곱+ 두번째 매개변수 제곱


1
2
Integer c = (int) Math.hypot(34);
        System.out.println(c);    //√25 = 5

cs




삼각함수(Double)

​Math.toRadians : 각도를 라디안으로 변경

Math.toDegress : 라디안 각도로

Math.sin()

Math.cos()

Math.tan()


 

toLowerCase() : 모든 문자열의 내용을 소문자로 바굼

toUpperCase(): 모든 문자열의 내용을 대문자로 바꿈

append : 문자 더하는 method


StringBuffer가 String Bulider보다 더 안전

속도는 bulider가 더 빠름


즉 여러가지 쓰레드 사용시는 StringBuffer 사용..~//~p.93

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package Test1;
 
public class p70 {
 
    public static void main(String[] args) {
        //subString
        String a = "Java technology is both a programming laguage and a platform.";
//공백 들어간 것만 잘라내는거구나 for문 이용해서 
        String[] splitArray = a.split(" ");
        System.out.println(splitArray);
        for(String temp:splitArray){
            System.out.println(temp);
        }
    }
    
 
}
 
cs


공백 들어간 문자 자르기 split


결과

Java

technology

is

both

a

programming

laguage

and

a

platform.


""가 빠진 값들만 표현되어나옴.

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
package Test1;
 
public class StringTest {
    
//p.66
    public static void main(String[] args) {
        String addresses[] = new String[]{
 
                "경기도 서울시",
                "구로구에서 태어난 나는 서울시에서 지냈지만 정말 는 정말 구로구고 동동동",
//                "남양주시 구로구 구로구 구로동"
        };
        
        
        int startCount = 0, endCount = 0, containCount = 0//글의 시작수 
        String startText ="서울시";
        String containText ="구로구";
        String endText ="동";
        
        for (String address : addresses) {
            
        //startWith : 매개변수로 넘겨준값이 시작하는지 확인
            if(address.startsWith(startText)) {
                startCount++;
            }
        //containText : 배개변수로 넘어온 값이 문자열에 존재하는지  Check
            if(address.contains(containText)){
                containCount++;
            }
 
        //endsWith : 매개변수로 넘어온 값이 끝나는지  check
            if(address.endsWith(endText)) {
                endCount++;
            }
 
        }
        
        System.out.println("시작글    " + startText+ "갯수  :  " + startCount);
        System.out.println("중간글    " + containText + "의갯수  :  " + containCount);
        System.out.println("끝나는글    " + endText + "의갯수  :  " + endCount);
    }
}
 
cs



결과:


시작글 서울시갯수  :  0

중간글 구로구의갯수  :  1

끝나는글 동의갯수  :  1




이건쉬운듯..해당 문구를 for문을 돌려서 확인하는 예제 정도? 


+ Recent posts