---从数据库去取需要导出数据的java类
/** * com.test.bcp.report.view.EveryDayRankAction * */ package com.test.bcp.report.view; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.kms.framework.core.dao.support.ModelSetup; import com.kms.framework.core.dao.support.ORMType; import com.kms.framework.core.dao.support.ibatis.IBatisModelSetup; import com.kms.framework.core.logger.LoggerFactory; import com.kms.framework.core.logger.type.DebugLogger; import com.kms.framework.core.view.support.entity.BaseEntityAction; import com.test.bcp.report.domain.ProTopReport; import com.test.bcp.report.service.IProTopReportService; import com.test.bcp.report.utils.ExportExcelPdf; import com.test.bcp.report.utils.ReportConfig; import com.test.bcp.user.vo.Loginer; /** * @date: 2012-4-17 * @time: 16:38:06 * @desc: 每日排行榜 查询Action */ public class ProTopReportAction extends BaseEntityAction<ProTopReport, IProTopReportService>{ private static final long serialVersionUID = -2520269272172780318L; private DebugLogger debugLogger = LoggerFactory.getDebugLogger(ProTopReportAction.class); private String beNum; private String enNum; private IProTopReportService proTopReportService; protected ModelSetup setupModel() { IBatisModelSetup modelSetup = (IBatisModelSetup) getModelSetupFromRequest(ORMType.IBATIS); modelSetup.addParameter("code", getLoginer().getOrganise() .getOrganiseCode()); modelSetup.addParameter("beginTime", getEntity().getBeginTime()); modelSetup.addParameter("endTime", getEntity().getEndTime()); return modelSetup; } public String list() { setupModel(); HashMap acceptParam = new HashMap(); acceptParam.put("beginTime", entity.getBeginTime()); acceptParam.put("endTime", entity.getEndTime()); acceptParam.put("code", getLoginer().getOrganise() .getOrganiseCode()); System.out.println(getLoginer().getOrganise() .getOrganiseCode()); setEntitys(proTopReportService.getProTopReportList(acceptParam)); return SUCCESS; } private Loginer getLoginer() { HttpSession session = ServletActionContext.getRequest().getSession(); return (Loginer) session.getAttribute(Loginer.USER_IN_SESSION); } /** * 导出Excel * @return Excel */ public String exportProTopReport() { HashMap acceptParam = new HashMap(); acceptParam.put("beginTime", entity.getBeginTime()); acceptParam.put("endTime", entity.getEndTime()); acceptParam.put("beNum", this.getBeNum()); acceptParam.put("enNum", this.getEnNum()); acceptParam.put("organiseCode", getLoginer().getOrganise() .getOrganiseCode()); //1.获取数据源 List dataList = proTopReportService.getProTopReportList(acceptParam); //2.把TmcIntspAcceptInfo对象专为HashMap对象 List savedata=new ArrayList(); for(int i=0;i<dataList.size();i++){ ProTopReport proTopReport=(ProTopReport) dataList.get(i); HashMap map=new LinkedHashMap(); map.put("organiseName",proTopReport.getOrganiseName()); map.put("top1_pro",proTopReport.getTop1_pro()); map.put("top1_c",proTopReport.getTop1_c()); map.put("top2_pro",proTopReport.getTop2_pro()); map.put("top2_c",proTopReport.getTop2_c()); map.put("top3_pro",proTopReport.getTop3_pro()); map.put("top3_c",proTopReport.getTop3_c()); map.put("top4_pro",proTopReport.getTop4_pro()); map.put("top4_c",proTopReport.getTop4_c()); map.put("top5_pro",proTopReport.getTop5_pro()); map.put("top5_c",proTopReport.getTop5_c()); savedata.add(map); } //3.传递参数导出报表 return new ExportExcelPdf().exportExcelReport( ReportConfig.proTopReport, ReportConfig.proTopHead, ReportConfig.proTopTail, savedata,ReportConfig.getRecordName().get("top")); } public void setProTopReportService(IProTopReportService proTopReportService) { this.proTopReportService = proTopReportService; } protected IProTopReportService getEntityManager() { return proTopReportService; } public IProTopReportService getProTopReportService() { return proTopReportService; } public String getEnNum() { return enNum; } public void setEnNum(String enNum) { this.enNum = enNum; } public String getBeNum() { return beNum; } public void setBeNum(String beNum) { this.beNum = beNum; } }
------导出excel的常用变量定义类(表名,表头,等等常用变量)-----
1 /** 2 * com.newyulong.bcp.report.utils.ReportConfig 3 6 */ 7 package com.newyulong.bcp.report.utils; 8 9 import java.util.ArrayList; 10 import java.util.HashMap; 11 12 /** 13 * @author: lifeng@foxmail.com 14 * @date: 2012-4-28 15 * @time: 16:38:06 16 * @desc:导出报表数据参数配置类 17 */ 18 19 public class ReportConfig { 20 21 /*产品TOP查询参数配置 */ 22 public static final String proTopReport = "产品TOP统计";// 报表名称 23 public static final String proTopHead = null;// 报表头 24 public static final String proTopTail = null;// 报表尾 25 26 // 设置报表字段名称 27 public static HashMap<String,ArrayList<String>> getRecordName() { 28 ArrayList<String> top=new ArrayList<String>(); 29 top.add("组织机构名称"); 30 top.add("TOP1"); 31 top.add("成功量"); 32 top.add("TOP2"); 33 top.add("成功量"); 34 top.add("TOP3"); 35 top.add("成功量"); 36 top.add("TOP4"); 37 top.add("成功量"); 38 top.add("TOP5"); 39 top.add("成功量"); 40 allRecordName.put("top",top); 41 return allRecordName; 42 } 43 44 }
-----导出excel的工具类
1 /** 2 * com.test.bcp.report.utils.ExportExcelPdf 5 * @licences: 6 */ 7 package com.test.bcp.report.utils; 8 9 import java.io.IOException; 10 import java.io.OutputStream; 11 import java.text.SimpleDateFormat; 12 import java.util.ArrayList; 13 import java.util.Date; 14 import java.util.HashMap; 15 import java.util.Iterator; 16 import java.util.List; 17 import java.util.Map; 18 19 import javax.servlet.http.HttpServletResponse; 20 21 import org.apache.poi.hssf.usermodel.HSSFCell; 22 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 23 import org.apache.poi.hssf.usermodel.HSSFDataFormat; 24 import org.apache.poi.hssf.usermodel.HSSFFont; 25 import org.apache.poi.hssf.usermodel.HSSFFooter; 26 import org.apache.poi.hssf.usermodel.HSSFHeader; 27 import org.apache.poi.hssf.usermodel.HSSFRow; 28 import org.apache.poi.hssf.usermodel.HSSFSheet; 29 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 30 import org.apache.poi.hssf.util.CellRangeAddress; 31 import org.apache.struts2.ServletActionContext; 32 33 /** 34 * @author: lifeng 35 * @date: 2012-4-27 36 * @time: 16:38:06 37 * @desc: 导出excel pdf 功能实现 38 */ 39 public class ExportExcelPdf { 40 41 /** 42 * 导出报表到excel方法 43 * @param reportName 报表名称 44 * @param reportHead 报表头 45 * @param reportTail 报表尾 46 * @param dataList 需要的数据集 47 * @param columnName 表头显示字段名称 48 * @return 49 */ 50 51 public String exportExcelReport(String reportName,String reportHead,String reportTail,List dataList,ArrayList columnName) { 52 //增加表头显示字段名称 53 dataList.add(0, columnName); 54 55 if (dataList.size() > 0 && !dataList.isEmpty()) { 56 if (!dataList.isEmpty() && dataList.size() > 0) { 57 List<List> excelData = this.getExportData(dataList); 58 List displayNames = excelData.get(0); 59 List filldataList = null; 60 if (excelData.remove(displayNames)) { 61 filldataList = excelData; 62 } 63 64 // filldataList:为要填充的数据 displayNames要显示的title 65 HSSFWorkbook workbook = null; 66 try { 67 workbook = exportExcel(reportHead, reportTail, reportName, 68 filldataList, displayNames); 69 } catch (Exception e) { 70 e.printStackTrace(); 71 }// 绑定excel与数据 72 HttpServletResponse response = ServletActionContext 73 .getResponse(); 74 if (workbook != null) { 75 // 打印导出excel 76 this.printExcel(workbook, response, 77 getExportFileName(".xls")); 78 } 79 80 } 81 } 82 return null; 83 } 84 85 /** 86 * 87 * 获取导出的数据 88 */ 89 private List<List> getExportData(List dataList) { 90 List<List> result = new ArrayList(); 91 92 if (!dataList.isEmpty() && dataList.size() > 0) { 93 ArrayList<String> displayNames=(ArrayList)dataList.get(0); 94 result.add(displayNames); 95 96 for (int i = 1; i < dataList.size(); i++) { 97 Map data =(Map) dataList.get(i); 98 List<String> filldataList = new ArrayList(); 99 for (Iterator iter = data.entrySet().iterator(); iter.hasNext();) { 100 Map.Entry entry = (Map.Entry) iter.next(); 101 Object value = entry.getValue(); 102 if (value == null) { 103 value = ""; 104 } 105 filldataList.add(value.toString()); 106 } 107 result.add(filldataList); 108 } 109 } 110 return result; 111 } 112 113 /** 114 * 打印导出的Excel 115 */ 116 private void printExcel(HSSFWorkbook workbook, 117 HttpServletResponse response, String excelFileName) { 118 try { 119 OutputStream out = response.getOutputStream(); 120 response.reset(); 121 response.setHeader("Content-disposition", "attachment;filename=" 122 + excelFileName); 123 // 设置响应文档类型为excel 124 response.setContentType("application/msexcel"); 125 response.setCharacterEncoding("UTF-8"); 126 workbook.write(out); 127 out.flush(); 128 out.close(); 129 } catch (IOException e) { 130 e.printStackTrace(); 131 } 132 } 133 134 /** 135 * 写入输入流中 136 */ 137 public HSSFWorkbook exportExcel(String reportHead, String reportTail, 138 String reprotName, List<List> filldataList, List displayNames) 139 throws Exception { 140 HSSFWorkbook workbook = null; 141 142 // 这里的数据即时你要从后台取得的数据 143 144 // 创建工作簿实例 145 workbook = new HSSFWorkbook(); 146 // 创建工作表实例 147 HSSFSheet sheet = workbook.createSheet("TscExcel"); 148 // 设置列宽 149 this.setSheetColumnWidth(displayNames.size(), sheet); 150 // 获取样式 151 HSSFCellStyle style = this.createTitleStyle(workbook); 152 HSSFDataFormat format = workbook.createDataFormat(); 153 style.setDataFormat(format.getFormat("@")); 154 // 设置页眉 155 HSSFHeader header = sheet.getHeader(); 156 HSSFHeader.fontSize((short) 16); 157 header.setCenter(reportHead); 158 159 // 设置报表名称 160 HSSFRow rowReportName = sheet.createRow((short) 0);// 建立新行 161 HSSFFont boldFont = workbook.createFont(); 162 boldFont.setFontHeight((short) 400); 163 HSSFCellStyle styleT = workbook.createCellStyle(); 164 styleT.setAlignment(HSSFCellStyle.ALIGN_CENTER); 165 styleT.setFont(boldFont); 166 this.createCell(rowReportName, 0, styleT, HSSFCell.CELL_TYPE_STRING, 167 reprotName); 168 // 合并单元格 169 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, displayNames.size())); 170 171 // 1. 创建第一行:标题, 172 HSSFRow row = sheet.createRow((short) 1);// 建立新行 173 for (int i = 0; i < displayNames.size(); i++) { 174 this.createCell(row, i, style, HSSFCell.CELL_TYPE_STRING, 175 displayNames.get(i)); 176 } 177 178 // 2. 给excel填充数据 179 int i = 0; 180 for (List<List> tableBody : filldataList) { 181 HSSFRow rowBody = sheet.createRow((short) (i + 2));// 建立新行 182 for (int j = 0; j < tableBody.size(); j++) { 183 this.createCell(rowBody, j, style,tableBody.get(j)); 184 } 185 i++; 186 } 187 // 设置页脚 188 HSSFFooter footer = sheet.getFooter(); 189 HSSFFooter.fontSize((short) 16); 190 footer.setCenter(reportTail); 191 192 return workbook; 193 } 194 195 /** 196 * 生成导出文件的名称 :按导出时间生成文件名称 197 */ 198 private String getExportFileName(String fix) { 199 Date date = new Date(); 200 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 201 return dateFormat.format(date) + fix; 202 } 203 204 /** 205 * 创建Excel单元格 206 */ 207 private void createCell(HSSFRow row, int column, HSSFCellStyle style, 208 int cellType, Object value) { 209 HSSFCell cell = row.createCell((short) column); 210 if (style != null) { 211 cell.setCellStyle(style); 212 } 213 switch (cellType) { 214 case HSSFCell.CELL_TYPE_BLANK: { 215 } 216 break; 217 case HSSFCell.CELL_TYPE_STRING: { 218 if(value==null){ 219 value = ""; 220 } 221 cell.setCellValue(value.toString() + ""); 222 223 } 224 break; 225 case HSSFCell.CELL_TYPE_NUMERIC: { 226 cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); 227 cell.setCellValue(Double.parseDouble(value.toString())); 228 } 229 break; 230 default: 231 break; 232 } 233 } 234 235 /** 236 * 创建Excel单元格及默认格式 237 */ 238 private void createCell(HSSFRow row, int column, HSSFCellStyle style, Object value) { 239 HSSFCell cell = row.createCell((short) column); 240 String data =""; 241 if(value!=null) data += value; 242 if(!"".equals(data)&&isNumeric(data) && data.indexOf("0")!=0){ 243 if (data.indexOf("86")==0 && data.length() == 13){ 244 cell.setCellValue(data); 245 }else{ 246 cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); 247 cell.setCellValue(Double.parseDouble(data.trim())); 248 } 249 }else{ 250 cell.setCellValue(data); 251 } 252 253 } 254 255 /** 256 * 判断是否为数字 257 * @param str 258 * @return 259 */ 260 public static boolean isNumeric(String str){ 261 for (int i = str.length();--i>=0;){ 262 if (!Character.isDigit(str.charAt(i))){ 263 return false; 264 } 265 } 266 return true; 267 } 268 269 /** 270 * 设置列宽 271 */ 272 private void setSheetColumnWidth(int titles_CN, HSSFSheet sheet) { 273 // 根据你数据里面的记录有多少列,就设置多少列 274 for (int i = 0; i < titles_CN; i++) { 275 sheet.setColumnWidth((short) i, (short) 3000); 276 } 277 278 } 279 280 /** 281 * 设置excel的title样式 282 */ 283 private HSSFCellStyle createTitleStyle(HSSFWorkbook wb) { 284 HSSFFont boldFont = wb.createFont(); 285 boldFont.setFontHeight((short) 200); 286 HSSFCellStyle style = wb.createCellStyle(); 287 style.setFont(boldFont); 288 style.setDataFormat(HSSFDataFormat.getBuiltinFormat("###,##0.00")); 289 return style; 290 } 291 }