반응형

LIB : poi-3.10-FINAL-20140208.jar

ExcelUtils

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package com.exam.common.util;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
 
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
 
import com.exam.domain.user.User;
 
public class ExcelUtils {
    private HSSFWorkbook workBook;
    private String filePath;
    private String excelFileName;
    
    /*
     * 호출 메소드
     * writeData(filePath, fileName, ObjectList);
     */
    public void writeData(String filePath, String fileName, List userList){
        this.filePath = filePath;
        excelFileName = fileName + ".xls";
        try {
            FileOutputStream fout = setFile(filePath, excelFileName);
            HSSFWorkbook workBook = createExcel(userList);
            workBook.write(fout);
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /*
     * 핵심 프로세스
     */
    public HSSFWorkbook createExcel(List userList){
        // Excel Write
        workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet("UserList");
        
        // ## Font Setting
        // @HSSFFont : 폰트 설정
        //  - FONT_ARIAL : 기본
        HSSFFont font = workBook.createFont();
        font.setFontName(HSSFFont.FONT_ARIAL);
        
        // ## Title Style Setting
        // @HSSFColor : 셀 배경색
        //  - GREY_$_PERCENT : 회색 $ 퍼센트
        // @HSSFCellStyle
        //  - ALIGN_$ : $ 쪽 정렬
        HSSFCellStyle titleStyle = workBook.createCellStyle();
        titleStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        titleStyle.setFillPattern(HSSFCellStyle.ALIGN_LEFT);
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setFont(font);
        
        // ## Row Create 
        // ? 가로열 생성
        HSSFRow row = sheet.createRow((short)0);
        
        // ## Title Cell Create
        // @row.createCell((short)n) : n번째 셀 설정
        // @setCellValue(String) : n 번째 셀의 내용 
        // @setCellStyle(style) : n 번째 셀의 스타일
        HSSFCell cell_0 = row.createCell((short)0);
        cell_0.setCellValue("번호");
        cell_0.setCellStyle(titleStyle);
        
        HSSFCell cell_1 = row.createCell((short)1);
        cell_1.setCellValue("E-Mail");
        cell_1.setCellStyle(titleStyle);
        
        HSSFCell cell_2 = row.createCell((short)2);
        cell_2.setCellValue("Password");
        cell_2.setCellStyle(titleStyle);
        
        HSSFCell cell_3 = row.createCell((short)3);
        cell_3.setCellValue("Name");
        cell_3.setCellStyle(titleStyle);
        
        HSSFCell cell_4 = row.createCell((short)4);
        cell_4.setCellValue("Age");
        cell_4.setCellStyle(titleStyle);
        
        HSSFCell cell_5 = row.createCell((short)5);
        cell_5.setCellValue("JoinDate");
        cell_5.setCellStyle(titleStyle);
        
        // ## Content Style Setting
        HSSFCellStyle contentStyle = workBook.createCellStyle();
        contentStyle.setFont(font);
        
        //  Content align : center
        HSSFCellStyle styleCenter = workBook.createCellStyle();
        styleCenter.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        styleCenter.setFont(font);
        
        //  ObjectList 가 비어있으면 제목만 출력 후 종료
        if(userList == nullreturn workBook;
        
        //  ObjectList 엑셀에 출력
        for(int i = 0; i < userList.size(); i++){
            // 1번째 행은 제목이니 건너 뜀
            row = sheet.createRow((short)(i+1));
            User user = userList.get(i);
            
            cell_0 = row.createCell((short)0);
            cell_0.setCellValue(user.getNo());
            cell_0.setCellStyle(styleCenter);
            
            cell_1 = row.createCell((short)1);
            cell_1.setCellValue(user.getEmail());
            cell_1.setCellStyle(styleCenter);
            
            cell_2 = row.createCell((short)2);
            cell_2.setCellValue(user.getPassword());
            cell_2.setCellStyle(styleCenter);
            
            cell_3 = row.createCell((short)3);
            cell_3.setCellValue(user.getName());
            cell_3.setCellStyle(styleCenter);
            
            cell_4 = row.createCell((short)4);
            cell_4.setCellValue(user.getAge());
            cell_4.setCellStyle(styleCenter);
            
            cell_5 = row.createCell((short)5);
            cell_5.setCellValue(user.getDate());
            cell_5.setCellStyle(styleCenter);
        }
        
        return workBook;
    }
    
    private FileOutputStream setFile(String filePath, String excelFileName)throws FileNotFoundException{
        File dir = new File(filePath);
        
        if(!dir.exists()) dir.mkdirs();
        
        FileOutputStream fout = new FileOutputStream(filePath+excelFileName);
        
        return fout;
    }
}
cs


반응형

'IT > 언어' 카테고리의 다른 글

[c#] 파일 출력  (0) 2014.08.19
페이징 처리용 소스(예제?)  (0) 2014.07.08
XStream 사용(_ 중복 출력 해결) & XML to JSON  (0) 2014.06.20
Mybatis + java 연동 기초  (0) 2014.06.19
JDBC 설정  (0) 2014.06.19
반응형

* 필요 jar File

XStreamReq&amp;xml2json.zip


TestMain.java

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
import com.exam.domain.AuthKey;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
 
import com.exam.domain.AuthKey;
import com.exam.util.xstream.Obj2Xml;
 
public class TestMain {
    public static void main(String[] args) throws JSONException{
        AuthKey authKey = new AuthKey();
        
        authKey.setPrimaryKey("key");
        authKey.setId("a001122334455");
        authKey.setProperty_1("pro1");
        authKey.setProperty_2("pro2");
        String xml = new Obj2Xml(authKey).toXml();
        System.out.println("===== XML OUT =====");
        System.out.println(xml);
        
        JSONObject jsonObj = XML.toJSONObject(xml);
        System.out.println("===== JSON OUT =====");
        System.out.println(jsonObj);
    }
}
cs

AuthKey.java

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
package com.exam.domain;
 
public class AuthKey {
    private String primaryKey;
    private String id;
    private String property_1;
    private String property_2;
    public String getPrimaryKey() {
        return primaryKey;
    }
    public void setPrimaryKey(String primaryKey) {
        this.primaryKey = primaryKey;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getProperty_1() {
        return property_1;
    }
    public void setProperty_1(String property_1) {
        this.property_1 = property_1;
    }
    public String getProperty_2() {
        return property_2;
    }
    public void setProperty_2(String property_2) {
        this.property_2 = property_2;
    }
    @Override
    public String toString() {
        return "AuthKey [primaryKey=" + primaryKey + ", id=" + id
                + ", property_1=" + property_1 + ", property_2=" + property_2
                + "]";
    }
        
}
cs

Obj2Xml.java(Obj를 받아서 Xml(String)으로 변환)

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
package com.exam.util.xstream;
 
import com.exam.domain.AuthKey;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
 
public class Obj2Xml {
    private Object obj;
    
    public Obj2Xml(Object obj){
        this.obj = obj;
    }
    
    public String toXml(){
        String toXml;
        
        XmlFriendlyReplacer replacer = new XmlFriendlyReplacer("__","_");
        XStream xStream = new XStream(new DomDriver("UTF-8", replacer)){
            protected boolean useXStreamXmlFriendlyMapper() {
                return true;
            }
        };
        xStream.alias("AuthKey", AuthKey.class);
        toXml = xStream.toXML(obj);
        return toXml;
    }
    
}
cs

Result

1
2
3
4
5
6
7
8
9
===== XML OUT =====
 
  key
  a001122334455
  pro1
  pro2
 
===== JSON OUT =====
{"response":{"id":"a001122334455","property_1":"pro1","primaryKey":"key","property_2":"pro2"}}
cs

*****************************************************

*****************************************************

Xstream 을 사용할때 Obj 속성중 _ 가 있으면 __ 로 변환 되기 때문에 아래처럼 XmlStream을 선언하여 써야 한다.

참고

1
2
3
4
5
6
XmlFriendlyReplacer replacer = new XmlFriendlyReplacer("__","_");
        XStream xStream = new XStream(new DomDriver("UTF-8", replacer)){
            protected boolean useXStreamXmlFriendlyMapper() {
                return true;
            }
        };
cs


반응형

'IT > 언어' 카테고리의 다른 글

페이징 처리용 소스(예제?)  (0) 2014.07.08
POI Excel 파일 쓰기  (0) 2014.06.26
Mybatis + java 연동 기초  (0) 2014.06.19
JDBC 설정  (0) 2014.06.19
[MyBatis] SqlSessionFactory  (0) 2014.06.19
반응형

환경 : Win7, java7, Eclipse Kepler, Mysql 5.6, Mybatis 3.0.6

LIB : MyBatis + MysqlConnector

mybatis mysql.zip

1. 이클립스 Dynamic Web Project 생성

(프레임워크에 따라 다르기 때문에 Console까지만 구현)


2. 각 파일 생성


File Path<그림 1>


MyBatisConnectionFactory.java : SqlSessionFactory 를 생성, SqlMapConfig.xml 과 매핑

UserDAO.java : sqlSessionFactory를 통해 DB와 데이터 교환

User.java : User Bean

UserMapper.java : java 매핑용

UserMapper.xml : xml 매핑용

Test.java : Test용 main메소드(웹환경은 Servlet, Struts, Sping 알아서)

SqlMapConfig.xml : DB 정보, Mapper 정보 등록



3. 소스보기

test/Test.java

import com.exam.dao.UserDAO;
import com.exam.domain.user.User;

public class Test{

	public static void main(String[] args) {
		
			UserDAO dao = new UserDAO();
			User user = new User();
//			
//			user = dao.getUser(new String("kkk@digi.com"));
//			
//			System.out.println(user.toString());
			
			user.setEmail("kj@digi.com");
			user.setPassword("321321");
			user.setName("kj");
			user.setAge(27);
			
			dao.insert(user);
	}

}

com/exam/dao/MyBatisConnectionFactory.java

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.exam.mapper.user.UserMapper;

public class MyBatisConnectionFactory {
	private static SqlSessionFactory sqlSessionFactory;
	
	static{
		try{
			String resource = "SqlMapConfig.xml";
			Reader reader = Resources.getResourceAsReader(resource);
			if(sqlSessionFactory == null){
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, "development");
//				sqlSessionFactory.getConfiguration().addMapper(UserMapper.class);
			}
		}catch(FileNotFoundException e){
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}
	
}


com/exam/dao/UserDAO.java

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.exam.domain.user.User;
import com.exam.mapper.user.UserMapper;

public class UserDAO {
	// UserMapper.xml 의 NameSpace
	private static final String NAMESPACE = "User.";
	
	// UserDAO가 호출될때 생성자를 통해 sqlSessionFactory 생성
	private SqlSessionFactory sqlSessionFactory;
	
	public UserDAO(){
		sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
	}
	
	// xml을 통한 매핑
	public void insert(User user){
		System.out.println("## UserDAO insert() 진입");
		// session Open
		SqlSession session = sqlSessionFactory.openSession();
		try{
			// UserMapper.xml => (NameSpace)User.(id)insert 에 user 객체 매칭 
			session.insert(NAMESPACE+"insert", user);
			// 커밋
			session.commit();
			System.out.println("## insert 성공");
		}catch(Exception e){
			session.rollback();
			e.printStackTrace();
			System.out.println("## insert 실패");
		}finally{
			// 사용후엔 닫아주자
			session.close();
		}
	}
	
	// java를 통한 매핑
	public User getUser(String email){
		SqlSession session = sqlSessionFactory.openSession();
		try{
			// 새로운 mapper를 생성
			UserMapper mapper = session.getMapper(UserMapper.class);
			User user = mapper.getUser(email);
			return user;
		}finally{
			session.close();
		}
	}
}

com/exam/domain/user/User.java

public class User {
	private Integer no;
	private String email;
	private String password;
	private String name;
	private Integer age;
	public Integer getNo() {
		return no;
	}
	public void setNo(Integer no) {
		this.no = no;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [no=" + no + ", email=" + email + ", password=" + password
				+ ", name=" + name + ", age=" + age + "]";
	}
	
	
}

com/exam/mapper/user/UserMapper.java

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.exam.domain.user.User;

public interface UserMapper {
	final String getUser = 
	"SELECT * FROM EXAM.USER " +
	"WHERE email = #{EMAIL}";
	
	// @Select(위의 String getUser 임)
	@Select(getUser)
	// property = User.java 의 속성, column = DB의 컬럼
	@Results(
			value={
					@Result(property="no", column="NO"),
					@Result(property="email", column="Email"),
					@Result(property="password", column="PASSWORD"),
					@Result(property="name", column="NAME"),
					@Result(property="age", column="AGE"),
			}
			)
	User getUser(String email); // email을 이용해 User 객체로 DB 결과값 리턴함
}


com/exam/mapper/user/UserMapper.xml

아래 xml 선언 포함 추가
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


    
    
		INSERT INTO EXAM.USER
		(
			EMAIL
			,PASSWORD
			,NAME
			,AGE
		)values(
			#{email}
			,#{password}
			,#{name}
			,#{age}
		)
    



SqlMapConfig.xml

아래 xml 선언 포함 추가
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">


	
		
	
	
    
		
			
			
				
				
				
				
			
		
				
	
	
		
	




4. 대충의 순서



!!! XML 태그 대소문자 주의!!!(대문자가 소문자로 바뀌어있음...)

반응형

'IT > 언어' 카테고리의 다른 글

POI Excel 파일 쓰기  (0) 2014.06.26
XStream 사용(_ 중복 출력 해결) & XML to JSON  (0) 2014.06.20
JDBC 설정  (0) 2014.06.19
[MyBatis] SqlSessionFactory  (0) 2014.06.19
[LIB] ESAPI 로 XSS 방어  (0) 2014.05.30

+ Recent posts