'spring poi xls xlsx'에 해당되는 글 1건

  1. 2016.03.18 spring boot excel download
카테고리 없음2016. 3. 18. 17:03
반응형

ExcelConstant.java

1
2
3
4
5
6
7
8
public class ExcelConstant {
    public static final String EXCEL_VERSION = "excelVersion";
    public static final String EXCEL_VERSION_2003 = "2003";
    public static final String EXCEL_VERSION_2007 = "2007";
    public static final String EXCEL_FILE_NMAE = "excelFileName";
    public static final String EXCEL_DATA_LIST = "excelDataList";
}
 
cs


.controller.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    @RequestMapping(value="/down", method=RequestMethod.GET)
    public ModelAndView excelDownload(
            @ApiParam(required=false, value="엑셀버전", name="excelversion") @RequestParam(value="excelversion", defaultValue = "2003"String excelversion) {
        DataMap dataMap = new DataMap();
        
        ModelAndView mav = new ModelAndView();
        if("2003".equals(excelversion)){
            mav.addObject(ExcelConstant.EXCEL_VERSION,ExcelConstant.EXCEL_VERSION_2003);
        }else{
            mav.addObject(ExcelConstant.EXCEL_VERSION,ExcelConstant.EXCEL_VERSION_2007);
        }
        mav.addObject(ExcelConstant.EXCEL_FILE_NMAE, "고객사목록");
        mav.addObject(ExcelConstant.EXCEL_DATA_LIST, sampleService.cust2(dataMap));
        mav.setViewName("excelDownloadView");
        return mav;
    }
cs


ExcelDownloadView.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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
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.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.Region;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;
 
import com.kt.aib.ws.config.util.DataMap;
 
@Component("excelDownloadView")
public class ExcelDownloadView extends AbstractView{
    
    public ExcelDownloadView() {
        // TODO Auto-generated constructor stub
        setContentType("application/download; ccharset=utf-8");
    }
 
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        
        String excelVersion = (String)model.get(ExcelConstant.EXCEL_VERSION);
        String excelFileName = (String)model.get(ExcelConstant.EXCEL_FILE_NMAE);
        StringBuffer fileName = new StringBuffer();
        fileName.append(excelFileName+"_"+currentDate("YYYYMMDD_HHMMSS"));
        
        Workbook workbook;
        if("2003".equals(excelVersion)){
            workbook = new HSSFWorkbook();
            buildExcelDocument2003(model, workbook, request, response);
            fileName.append(".xls");
        }else{
            workbook = new XSSFWorkbook();
            buildExcelDocument2007(model, workbook, request, response);
            fileName.append(".xlsx");
        }
        setResponse(request,response,fileName.toString());
 
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        if(out != null){out.close();}
    }
 
    private void setResponse(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException{
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.indexOf("MSIE 5.5"> -1) { // MS IE 5.5 이하
            response.setHeader("Content-Disposition""filename=" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+""\\ "+ ";");
        } else if (userAgent.indexOf("MSIE"> -1) { // MS IE (보통은 6.x 이상 가정)
            response.setHeader("Content-Disposition""attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+""\\ "+ ";");
        } else if (userAgent.indexOf("Trident"> -1) { // MS IE 11
            response.setHeader("Content-Disposition""attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+""\\ "+ ";");
        } else { // 모질라나 오페라
            response.setHeader("Content-Disposition""attachment; filename=" + new String(fileName.getBytes("euc-kr"), "latin1").replaceAll("\\+""\\ "+ ";");
        }
    }
    
    private String currentDate(String format){
        SimpleDateFormat sd = new SimpleDateFormat(format);
        return sd.format(new Date()); 
    }
    
    private void buildExcelDocument2003(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        
        // init
        List<DataMap> excelDataList = (List<DataMap>)model.get(ExcelConstant.EXCEL_DATA_LIST);
        DataMap headerDataMap = excelDataList.get(0);
        
        int rowTitleNum = 0;
        int rowTitleSubNum = 2;
        int rowHeaderNum = 3;
        int rowDataNum = 4;
        
        // create style, font
        HSSFFont titleFont =  (HSSFFont)workbook.createFont();
        titleFont.setFontHeightInPoints((short)16);
//        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        
        HSSFCellStyle  titleCellStyle = (HSSFCellStyle)workbook.createCellStyle();
        titleCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);              
        titleCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);   
        titleCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);   
        titleCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
        titleCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
        titleCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
        titleCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        titleCellStyle.setFont(titleFont);
 
        HSSFCellStyle  titleSubCellStyle = (HSSFCellStyle)workbook.createCellStyle();
        titleSubCellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
        titleSubCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        
        HSSFCellStyle  headerCellStyle = (HSSFCellStyle)workbook.createCellStyle();
        headerCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);              
        headerCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);   
        headerCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);   
        headerCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);   
        headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
        headerCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
 
        HSSFCellStyle  dataCellStyle = (HSSFCellStyle)workbook.createCellStyle();
        dataCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);              
        dataCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);   
        dataCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);   
        dataCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);   
        
        // create sheet
        HSSFSheet sheet = (HSSFSheet)workbook.createSheet("sheet01");
                
        // create title row
        HSSFRow titleRow = sheet.createRow(rowTitleNum);
        titleRow.setHeightInPoints(34);
        HSSFCell titleCell;
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
            titleCell = titleRow.createCell(i);
            if(i == 0){
                titleCell.setCellValue("TITLE");
            }
            titleCell.setCellStyle(titleCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(rowTitleNum,rowTitleNum,0,(headerDataMap.keyList().size()-1)));
        
        // create titleSub row
        HSSFRow titleSubRow = sheet.createRow(rowTitleSubNum);
        HSSFCell titleSubCell;
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
            titleSubCell = titleSubRow.createCell(i);
            if(i == 0){
                titleSubCell.setCellValue("작성일자 :"+currentDate("YYYY년 MM월 DD일 HH:MM:SS"));
            }
            titleSubCell.setCellStyle(titleSubCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(rowTitleSubNum,rowTitleSubNum,0,(headerDataMap.keyList().size()-1)));
        
        // create header row
        HSSFRow headerRow = sheet.createRow(rowHeaderNum);
        HSSFCell hearderCell;
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
            hearderCell = headerRow.createCell(i);
            hearderCell.setCellStyle(headerCellStyle);
            hearderCell.setCellValue((String)headerDataMap.get(i));
        }
        
        // create data row
        HSSFRow row = null;
        HSSFCell cell = null;
        for(int rowIdx = 0 ; rowIdx < excelDataList.size() ; rowIdx++){
            row = sheet.createRow(rowDataNum+rowIdx);
            DataMap rowData = excelDataList.get(rowIdx);
            for(int cellIdx = 0 ; cellIdx < headerDataMap.keyList().size() ; cellIdx++){
                cell = row.createCell(cellIdx);
                String cellKey = (String)headerDataMap.keyList().get(cellIdx);
                Object cellData = rowData.get(cellKey);
                if(cellData instanceof String){
                    cell.setCellValue((String)cellData);
                }else if(cellData instanceof Integer){
                    cell.setCellValue((Integer)cellData);
                }else if(cellData instanceof Long){
                    cell.setCellValue((Long)cellData);
                }else if(cellData instanceof Double){
                    cell.setCellValue((Double)cellData);
                }
                cell.setCellStyle(dataCellStyle);
            }
        }
        // create cell size 
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
//            sheet.autoSizeColumn(i,true);
        }
    }
    
    private void buildExcelDocument2007(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        
        // init
        List<DataMap> excelDataList = (List<DataMap>)model.get(ExcelConstant.EXCEL_DATA_LIST);
        DataMap headerDataMap = excelDataList.get(0);
        
        int rowTitleNum = 0;
        int rowTitleSubNum = 2;
        int rowHeaderNum = 3;
        int rowDataNum = 4;
        
        // create style, font
        XSSFFont titleFont =  (XSSFFont)workbook.createFont();
        titleFont.setFontHeightInPoints((short)16);
//        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        
        XSSFCellStyle  titleCellStyle = (XSSFCellStyle)workbook.createCellStyle();
        titleCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);              
        titleCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);   
        titleCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);   
        titleCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); 
        titleCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
        titleCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        titleCellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION);
        titleCellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        titleCellStyle.setFont(titleFont);
 
        XSSFCellStyle  titleSubCellStyle = (XSSFCellStyle)workbook.createCellStyle();
        titleSubCellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
        titleSubCellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        
        XSSFCellStyle  headerCellStyle = (XSSFCellStyle)workbook.createCellStyle();
        headerCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);              
        headerCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);   
        headerCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);   
        headerCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);   
        headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
        headerCellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
 
        XSSFCellStyle  dataCellStyle = (XSSFCellStyle)workbook.createCellStyle();
        dataCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);              
        dataCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);   
        dataCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);   
        dataCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);   
        
        // create sheet
        XSSFSheet sheet = (XSSFSheet)workbook.createSheet("sheet01");
                
        // create title row
        XSSFRow titleRow = sheet.createRow(rowTitleNum);
        titleRow.setHeightInPoints(34);
        XSSFCell titleCell;
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
            titleCell = titleRow.createCell(i);
            if(i == 0){
                titleCell.setCellValue("TITLE");
            }
            titleCell.setCellStyle(titleCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(rowTitleNum,rowTitleNum,0,(headerDataMap.keyList().size()-1)));
        
        // create titleSub row
        XSSFRow titleSubRow = sheet.createRow(rowTitleSubNum);
        XSSFCell titleSubCell;
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
            titleSubCell = titleSubRow.createCell(i);
            if(i == 0){
                titleSubCell.setCellValue("작성일자 :"+currentDate("YYYY년 MM월 DD일 HH:MM:SS"));
            }
            titleSubCell.setCellStyle(titleSubCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(rowTitleSubNum,rowTitleSubNum,0,(headerDataMap.keyList().size()-1)));
        
        // create header row
        XSSFRow headerRow = sheet.createRow(rowHeaderNum);
        XSSFCell hearderCell;
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
            hearderCell = headerRow.createCell(i);
            hearderCell.setCellStyle(headerCellStyle);
            hearderCell.setCellValue((String)headerDataMap.get(i));
        }
        
        // create data row
        XSSFRow row = null;
        XSSFCell cell = null;
        for(int rowIdx = 0 ; rowIdx < excelDataList.size() ; rowIdx++){
            row = sheet.createRow(rowDataNum+rowIdx);
            DataMap rowData = excelDataList.get(rowIdx);
            for(int cellIdx = 0 ; cellIdx < headerDataMap.keyList().size() ; cellIdx++){
                cell = row.createCell(cellIdx);
                String cellKey = (String)headerDataMap.keyList().get(cellIdx);
                Object cellData = rowData.get(cellKey);
                if(cellData instanceof String){
                    cell.setCellValue((String)cellData);
                }else if(cellData instanceof Integer){
                    cell.setCellValue((Integer)cellData);
                }else if(cellData instanceof Long){
                    cell.setCellValue((Long)cellData);
                }else if(cellData instanceof Double){
                    cell.setCellValue((Double)cellData);
                }
                cell.setCellStyle(dataCellStyle);
            }
        }
        // create cell size 
        for(int i = 0 ; i < headerDataMap.keyList().size() ; i++){
//            sheet.autoSizeColumn(i,true);
        }
    }
}
cs


Posted by 1010