Java下载excel


控制层代码

 1 package com.base.web.controller.common;
 2 
 3 import java.util.HashMap;
 4 import java.util.LinkedHashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import javax.annotation.Resource;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import org.apache.commons.lang3.StringUtils;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15 import org.springframework.stereotype.Controller;
16 import org.springframework.web.bind.annotation.PathVariable;
17 import org.springframework.web.bind.annotation.RequestMapping;
18 import org.springframework.web.bind.annotation.RequestMethod;
19 
20 import com.base.po.business.CustomerPo;
21 import com.base.service.business.BrokerInfoService;
22 import com.base.service.business.CustomerService;
23 import com.base.utils.ExcelExportUtil;
24 import com.base.utils.sysenum.ExcelExportEnum;
25 import com.base.web.controller.BaseController;
26 
27 @Controller
28 @RequestMapping("excel")
29 public class ExcelController extends BaseController{
30 
31     Logger logger = LoggerFactory.getLogger(getClass());
32     
33     @Resource BrokerInfoService brokerInfoService;
34     @Resource CustomerService customerService;
35     
36     @RequestMapping(value = "/download/{name}.do",method = RequestMethod.POST)
37     public void getSystemExcel(HttpServletRequest request, HttpServletResponse response, 
38             @PathVariable("name") String name) {
39         try {
40             if("recommend".equals(name)){//推荐导出
41                 ExcelExportUtil.downloadExcel(request,response,ExcelExportEnum.recommend, getRecommendMap(), getRecommendData(request));
42             }
43         } catch (Exception e) {
44             logger.error(e.getMessage(), e);
45         }
46     }
47     
48     private List<CustomerPo> getRecommendData(HttpServletRequest request) {
49         Map<String, Object> map = new HashMap<String, Object>();
50         String name = request.getParameter("name");
51         String city = request.getParameter("city");
52         String projectName = request.getParameter("projectName");
53         if(StringUtils.isNotBlank(name))
54             map.put("name", name);
55         if(StringUtils.isNotBlank(city))
56             map.put("city", city);
57         if(StringUtils.isNotBlank(projectName))
58             map.put("projectName", projectName);
59         return customerService.findCustomerList(map, 1);
60     }
61 
62     private LinkedHashMap<String, String> getRecommendMap() {
63         LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
64         map.put("客户姓名", "name");
65         map.put("手机号", "tel");
66         map.put("性别", "sex");
67         map.put("预约城市", "city");
68         map.put("预约项目", "projectName");
69         map.put("意向产品类型", "productTypeName");
70         map.put("客户备注信息", "remarks");
71         map.put("跟进状态", "status");
72         map.put("最近跟进时间", "followUp");
73         map.put("经纪人姓名", "brokerName");
74         map.put("经纪人手机号", "brokerTel");
75         map.put("已结佣金", "brokerAmount");
76         return map;
77     }
78 }

 

下载工具类

  1 package com.base.utils;
  2 
  3 import java.io.IOException;
  4 import java.io.OutputStream;
  5 import java.text.DecimalFormat;
  6 import java.text.SimpleDateFormat;
  7 import java.util.Date;
  8 import java.util.LinkedHashMap;
  9 import java.util.List;
 10 
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13 
 14 import org.apache.poi.hssf.usermodel.HSSFCell;
 15 import org.apache.poi.hssf.usermodel.HSSFRow;
 16 import org.apache.poi.hssf.usermodel.HSSFSheet;
 17 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 18 import org.apache.poi.ss.usermodel.BorderStyle;
 19 import org.apache.poi.ss.usermodel.CellStyle;
 20 import org.apache.poi.ss.usermodel.Font;
 21 import org.apache.poi.ss.usermodel.HorizontalAlignment;
 22 import org.apache.poi.ss.usermodel.IndexedColors;
 23 import org.apache.poi.ss.usermodel.VerticalAlignment;
 24 import org.apache.poi.ss.util.CellRangeAddress;
 25 import org.slf4j.Logger;
 26 import org.slf4j.LoggerFactory;
 27 
 28 import com.base.utils.sysenum.ExcelExportEnum;
 29 
 30 public class ExcelExportUtil {
 31 
 32     protected static Logger logger = LoggerFactory.getLogger(ExcelExportUtil.class);
 33     
 34     private static CellStyle titleStyle; // 标题行样式
 35     private static Font titleFont; // 标题行字体
 36     private static CellStyle headStyle; // 表头行样式
 37     private static Font headFont; // 表头行字体
 38     private static CellStyle contentStyle; // 内容行样式
 39     private static Font contentFont; // 内容行字体
 40     
 41     /**
 42      * 初始化HSSFWorkbook
 43      * 
 44      * @Method_Name : init
 45      * @return  HSSFWorkbook
 46      */
 47     private static HSSFWorkbook init() {
 48         HSSFWorkbook wb = new HSSFWorkbook();
 49 
 50         titleFont = wb.createFont();
 51         titleStyle = wb.createCellStyle();
 52         headStyle = wb.createCellStyle();
 53         headFont = wb.createFont();
 54         contentStyle = wb.createCellStyle();
 55         contentFont = wb.createFont();
 56 
 57         initTitleCellStyle();
 58         initTitleFont();
 59         initHeadCellStyle();
 60         initHeadFont();
 61         initContentCellStyle();
 62         initContentFont();
 63         return wb;
 64     }
 65     
 66     /**
 67      * 根据数据集合生成excel文件并下载
 68      * 
 69      * @Method_Name : downloadExcel
 70      * @param excelExportEnum excel文件名称,工作簿和生成的内容标题都用这个名称
 71      * @param map 列名与集合中实体类属性的对应关系
 72      * @param list 需要导出的数据集合
 73      * @return 
 74      * @throws Exception
 75      * @return 
 76      */
 77     public static void downloadExcel(HttpServletRequest request, HttpServletResponse response,ExcelExportEnum excelExportEnum, LinkedHashMap<String, String> map, List<?> list) throws Exception {
 78 
 79         // 第一步,创建一个webbook,对应一个Excel文件  
 80         HSSFWorkbook wb = init();
 81         // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
 82         HSSFSheet sheet = wb.createSheet(excelExportEnum.getTypeName());  
 83         
 84         int columnNum = map.keySet().size();
 85         String[] colNames = (String[]) map.keySet().toArray(new String[columnNum]);
 86         String[] colContents = (String[]) map.values().toArray(new String[columnNum]);
 87         
 88         // 第三步,填充sheet 数据
 89         createTableTitleRow(sheet, excelExportEnum.getTypeName(), columnNum);
 90         creatTableHeadRow(sheet.createRow((int) 1), colNames);
 91         creatTableDataRows(excelExportEnum, sheet, list, colContents);
 92         
 93         // 第四步,自动调整列宽
 94         adjustColumnSize(sheet, columnNum);
 95         
 96         // 第六步,输出Excel文件  
 97         String fileName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "_" + excelExportEnum.getTypeName() +".xls";
 98         outWrite(request, response, wb, fileName);  
 99     }
100 
101     private static void outWrite(HttpServletRequest request, HttpServletResponse response, HSSFWorkbook wb,
102             String fileName) throws IOException {
103         OutputStream output = null;
104         try {
105             String userAgent = request.getHeader("User-Agent");
106             output = response.getOutputStream();
107             response.reset();  
108             response.setHeader("Content-disposition", "attachment; filename="+ StringUtil.encodeFileName(fileName, userAgent));  
109             response.setContentType("application/vnd.ms-excel;charset=utf-8");
110             response.setCharacterEncoding("utf-8");  
111             wb.write(output);  
112             output.flush(); 
113         } catch (IOException e) {
114             e.printStackTrace();
115         }finally {
116             if(output != null){
117                 output.close();  
118             }
119         }
120     }
121     
122     /**
123      * @Description: 创建标题行(需合并单元格)
124      */
125     private static void createTableTitleRow(HSSFSheet sheet, String fileName, int columnNum) {
126         CellRangeAddress titleRange = new CellRangeAddress(0, 0, 1, columnNum);
127         sheet.addMergedRegion(titleRange);
128         HSSFRow row = sheet.createRow(0);
129         row.setHeight((short) 800);
130         HSSFCell cell = row.createCell(1);
131         cell.setCellStyle(titleStyle);
132         cell.setCellValue(fileName);
133     }
134     
135     /**
136      * @Description: 创建表头行(需合并单元格)
137      */
138     private static void creatTableHeadRow(HSSFRow row, String[] colNames) {
139         // 表头
140         row.setHeight((short) 400);
141         // 列头名称
142         HSSFCell cell = null;
143         for (int i = 0; i < colNames.length; i++) {
144             cell = row.createCell(i + 1);
145             cell.setCellStyle(headStyle);
146             cell.setCellValue(colNames[i]);
147         }
148     }
149     
150     /**
151      * @Description: 创建表格数据
152      */
153     private static void creatTableDataRows(ExcelExportEnum excelExportEnum, HSSFSheet sheet, List<?> list, String[] colContents) {
154         HSSFRow row = null;
155         for (int i = 0; i < list.size(); i++) { 
156             row = sheet.createRow((int) i + 2);
157             row.setHeight((short) 350);
158             if(excelExportEnum.equals(ExcelExportEnum.Broker))
159                 createTeableBrokerData(colContents, (Object[])list.get(i), row);
160             else if(excelExportEnum.equals(ExcelExportEnum.appointment))
161                 createTeableAppointmentData(colContents, new Object[]{list.get(i)}, row);
162             else if(excelExportEnum.equals(ExcelExportEnum.recommend))
163                 createTeableRecommendData(colContents, new Object[]{list.get(i)}, row);
164             else
165                 createTeableDefaultDate(colContents, list.get(i), row);
166         }
167     }
168     /**
169      * @Description: 预约客户信息
170      */
171     private static void createTeableRecommendData(String[] colContents, Object[] objects, HSSFRow row) {
172         Object value = null;
173         HSSFCell cell = null;
174         String colContent = "";
175         Object object = objects[0];
176         SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd"); 
177         DecimalFormat df = new DecimalFormat("#.00"); 
178         for (int i = 0; i < colContents.length; i++) {
179             colContent = colContents[i];
180             cell = row.createCell(i + 1);
181             cell.setCellStyle(contentStyle);
182             if (ReflectionUtils.findField(object.getClass(), colContent) == null)
183                 value = null;
184             else
185                 value = ReflectionUtils.invokeGetterMethod(object, colContent);
186             if("sex".equals(colContent)){
187                 cell.setCellValue(value == null ? "--" : ("1".equals(value.toString()) ? "男" : "女"));
188             }else if("status".equals(colContent)){
189                 if(value == null){
190                     cell.setCellValue("--");
191                 }else if("1".equals(value.toString())){
192                     cell.setCellValue("致电");
193                 }else if("2".equals(value.toString())){
194                     cell.setCellValue("到访");
195                 }else if("3".equals(value.toString())){
196                     cell.setCellValue("签约");
197                 }
198             }else if("showRoomTime".equals(colContent) || "followUp".equals(colContent)){
199                 cell.setCellValue(value == null ? "--" : sdf.format(value));
200             }else if("brokerAmount".equals(colContent)){
201                 cell.setCellValue(value == null ? "--" : df.format(value));
202             }else
203                 cell.setCellValue(value == null ? "--" : value.toString());
204         }
205     }
206     /**
207      * @Description: 推荐客户信息
208      */
209     private static void createTeableAppointmentData(String[] colContents, Object[] objects, HSSFRow row) {
210         Object value = null;
211         HSSFCell cell = null;
212         String colContent = "";
213         Object object = objects[0];
214         SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd"); 
215         for (int i = 0; i < colContents.length; i++) {
216             colContent = colContents[i];
217             cell = row.createCell(i + 1);
218             cell.setCellStyle(contentStyle);
219             if (ReflectionUtils.findField(object.getClass(), colContent) == null)
220                 value = null;
221             else
222                 value = ReflectionUtils.invokeGetterMethod(object, colContent);
223             if("status".equals(colContent)){
224                 if(value == null){
225                     cell.setCellValue("--");
226                 }else if("1".equals(value.toString())){
227                     cell.setCellValue("致电");
228                 }else if("2".equals(value.toString())){
229                     cell.setCellValue("到访");
230                 }else if("3".equals(value.toString())){
231                     cell.setCellValue("签约");
232                 }
233             }else if("showRoomTime".equals(colContent) || "followUp".equals(colContent)){
234                 cell.setCellValue(value == null ? "--" : sdf.format(value));
235             }else
236                 cell.setCellValue(value == null ? "--" : value.toString());
237         }
238     }
239 
240     /**
241      * @Description: 经纪人信息
242      */
243     private static void createTeableBrokerData(String[] colContents, Object[] objects, HSSFRow row){
244         Object value = null;
245         HSSFCell cell = null;
246         String colContent = "";
247         Object object = objects[0];
248         for (int i = 0; i < colContents.length; i++) {
249             colContent = colContents[i];
250             cell = row.createCell(i + 1);
251             cell.setCellStyle(contentStyle);
252             
253             if("count".equals(colContent)){//推荐人次
254                 cell.setCellValue(objects[1] == null ? "--" : objects[1].toString());
255                 continue;
256             }
257             if("amount".equals(colContent)){//已结佣总金额(元)
258                 cell.setCellValue(objects[2] == null ? "--" : objects[2].toString());
259                 continue;
260             }
261             
262             if (ReflectionUtils.findField(object.getClass(), colContent) == null)
263                 value = null;
264             else
265                 value = ReflectionUtils.invokeGetterMethod(object, colContent);
266             if("sex".equals(colContent))
267                 cell.setCellValue(value == null ? "--" : ("1".equals(value.toString()) ? "男" : "女"));
268             else if("status".equals(colContent))
269                 cell.setCellValue(value == null ? "--" : ("1".equals(value.toString()) ? "是" : "否"));
270             else
271                 cell.setCellValue(value == null ? "--" : value.toString());
272         }
273     }
274     
275     /**
276      * @Description: 默认信息
277      */
278     private static void createTeableDefaultDate(String[] colContents, Object object, HSSFRow row){
279         Object value = null;
280         HSSFCell cell = null;
281         for (int i = 0; i < colContents.length; i++) {
282             value = ReflectionUtils.invokeGetterMethod(object, colContents[i]);
283             cell = row.createCell(i + 1);
284             cell.setCellStyle(contentStyle);
285             cell.setCellValue(value == null ? "" : value.toString());
286         }
287     }
288     
289     /**
290      * @Description: 自动调整列宽
291      */
292     private static void adjustColumnSize(HSSFSheet sheet, int columnNum) {
293         for (int i = 0; i < columnNum; i++) {
294             sheet.autoSizeColumn(i + 1);
295         }
296     }
297     
298     /**
299      * @Description: 初始化标题行样式
300      */
301     private static void initTitleCellStyle() {
302         titleStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
303         titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
304         titleStyle.setFont(titleFont);
305         titleStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
306     }
307     
308     /**
309      * @Description: 初始化表头行样式
310      */
311     private static void initHeadCellStyle() {
312         headStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
313         headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
314         headStyle.setFont(headFont);
315         headStyle.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
316         headStyle.setBorderTop(BorderStyle.MEDIUM);
317         headStyle.setBorderBottom(BorderStyle.THIN);
318         headStyle.setBorderLeft(BorderStyle.THIN);
319         headStyle.setBorderRight(BorderStyle.THIN);
320         headStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
321         headStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
322         headStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
323         headStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
324     }
325     
326     /**
327      * @Description: 初始化内容行样式
328      */
329     private static void initContentCellStyle() {
330         contentStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
331         contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
332         contentStyle.setFont(contentFont);
333         contentStyle.setBorderTop(BorderStyle.THIN);
334         contentStyle.setBorderBottom(BorderStyle.THIN);
335         contentStyle.setBorderLeft(BorderStyle.THIN);
336         contentStyle.setBorderRight(BorderStyle.THIN);
337         contentStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
338         contentStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
339         contentStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
340         contentStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
341         contentStyle.setWrapText(true); // 字段换行
342     }
343     
344     /**
345      * @Description: 初始化标题行字体
346      */
347     private static void initTitleFont() {
348         titleFont.setFontName("华文楷体");
349         titleFont.setFontHeightInPoints((short) 20);
350         titleFont.setBold(true);
351         titleFont.setCharSet(Font.DEFAULT_CHARSET);
352         titleFont.setColor(IndexedColors.BLACK.getIndex());
353     }
354     
355     /**
356      * @Description: 初始化表头行字体
357      */
358     private static void initHeadFont() {
359         headFont.setFontName("宋体");
360         headFont.setFontHeightInPoints((short) 10);
361         headFont.setBold(true);
362         headFont.setCharSet(Font.DEFAULT_CHARSET);
363         headFont.setColor(IndexedColors.BLACK.getIndex());
364     }
365 
366     /**
367      * @Description: 初始化内容行字体
368      */
369     private static void initContentFont() {
370         contentFont.setFontName("宋体");
371         contentFont.setFontHeightInPoints((short) 10);
372         contentFont.setBold(false);
373         contentFont.setCharSet(Font.DEFAULT_CHARSET);
374         contentFont.setColor(IndexedColors.BLACK.getIndex());
375     }
376 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM