需求:页面输入团单号,从数据库中查询搬单错误的数据,以excel形式导出。
前端页面放在ts-settle-tools-web项目中,后端查询数据库的部分写在ts-tg-settle中,以API形式提供给ts-settle-tools使用,其实是通过webservice调用的。
public interface TSSettleService { /** * 查询搬单错误数据 * @param dealGroupIds * @return */ public List<TSTGSettleDetailDTO> getWrongData(List<Integer> dealGroupIds); }
public class TSSettleServiceObject implements TSSettleService { @Override public List<TSTGSettleDetailDTO> getWrongData(List<Integer> dealGroupIds){ if(dealGroupIds == null || dealGroupIds.size() == 0){ return null; } List<TSTGSettleDetailDTO> result =tsSettleDetailDao.getWrongData(dealGroupIds); return result; } }
public interface TSSettleDetailDao extends GenericDao { @DAOAction(action = DAOActionType.QUERY) public List<TSTGSettleDetailDTO> getWrongData(@DAOParam("dealGroupIds") List<Integer> dealGroupIds); }
<resultMap id="tstgSettleDetailDTO" class="com.dianping.ts.tg.settle.api.dtos.TSTGSettleDetailDTO"> <result property="dealGroupId" column="DealGroupID"/> <result property="dealId" column="DealID"/> <result property="shopId" column="ShopID"/> <result property="dealCost" column="DealCost"/> <result property="dealPrice" column="DealPrice"/> <result property="settleTime" column="SettleTime"/> <result property="detailId" column="DetailID"/> <result property="status" column="Status"/> </resultMap> <select id="getWrongData" parameterClass="map" resultMap="tstgSettleDetailDTO"> select t.id ID, t.DealGroupID DealGroupID, t.DealID DealID, t.ShopID ShopID, t.DealCost DealCost, t.DealPrice DealPrice, t.SettleTime SettleTime, t.DetailID DetailID, (CASE WHEN p.status=5 THEN 1 ELSE 0 END) as Status from TS_TGSettleDetail t left join TS_DistributionDetail d on d.AccountID=t.AccountID left join TS_PayPlan p on d.PayPlanID=p.id where d.outbizid=t.GroupID and t.DealGroupID in <iterate property="dealGroupIds" open="(" close=")" conjunction=","> #dealGroupIds[]# </iterate> <![CDATA[ and t.UpdateTime>‘2015-12-01‘ and d.UpdateTime>‘2015-12-01‘ and t.SettleType in (1,3) order by t.id ; ]]> </select>
以上即为API部分的关键代码,打包成jar之后就可以在ts-settle-tools中引入使用。
在ts-tg-settle-service中需要配置pigeon服务的地址,其实就是在配置中心注册服务
<bean id="tsSettleSystemService" class="com.dianping.dpsf.spring.ServiceRegistry" init-method="init" lazy-init="false"> <property name="port" value="${ts-tg-settle-service.tsSettleService.port}"/> <property name="services"> <map> <entry key="http://service.dianping.com/ts/tg/tsSettleService/TSSettleService_1.0.0" value-ref="tsTGSettleService"/> </map> </property> </bean>
ts-settle-tools的pom中需要添加对ts-tg-settle-api的依赖。并且需要配置pigeon服务的地址。
<bean id="tsSettleService" class="com.dianping.dpsf.spring.ProxyBeanFactory" init-method="init"> <property name="serviceName" value="http://service.dianping.com/ts/tg/tsSettleService/TSSettleService_1.0.0"/> <property name="iface" value="com.dianping.ts.tg.settle.api.TSSettleService"/> <property name="serialize" value="hessian"/> <property name="callMethod" value="sync"/> <property name="timeout" value="5000"/> </bean>
ts-settle-tools前端效果如下
Controller部分
@RequestMapping("/settle") @Controller public class SettleController { @Autowired private SettleService settleService; @RequestMapping("/downloadResult") public String downloadResult(){ return "downloadResult"; } @RequestMapping("/downloadResultAction") public void downloadResultAction(@RequestParam String dealGroupIds, HttpServletRequest request, HttpServletResponse response){ // System.out.println(groupNo); List<TSTGSettleDetailDTO> list = settleService.getWrongData(dealGroupIds); //List<TSTGSettleDetailDTO> list1 = settleService.getRightData(dealGroupIds); //list.addAll(list1); System.out.println(list); ExportExcel<TSTGSettleDetailDTO> ex = new ExportExcel<TSTGSettleDetailDTO>(); String[] headers = { "团单号", "套餐号", "验券门店", "结算价", "售价", "验券时间", "券号", "打款状态"}; try { HSSFWorkbook workbook = ex.exportExcel(headers, list); String filename = "result.xls"; response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + filename); OutputStream ouputStream = response.getOutputStream(); workbook.write(ouputStream); ouputStream.flush(); ouputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
Service部分
public class SettleServiceImpl implements SettleService { @Autowired private TSSettleService tsSettleService; public List<TSTGSettleDetailDTO> getRightData(String dealGroupIds){ String[] strs=dealGroupIds.split(","); List<Integer> dealGroupIdList = new ArrayList<Integer>(); for(int i = 0; i < strs.length; i++){ dealGroupIdList.add(Integer.valueOf(strs[i])); } List<TSTGSettleDetailDTO> result = tsSettleService.getRightData(dealGroupIdList); return result; } }
处理excel部分
public class ExportExcel<T> { public HSSFWorkbook exportExcel(Collection<T> dataset) { return exportExcel("导出结果", null, dataset); } public HSSFWorkbook exportExcel(String[] headers, Collection<T> dataset) { return exportExcel("导出结果", headers, dataset); } @SuppressWarnings("unchecked") public HSSFWorkbook exportExcel(String title, String[] headers, Collection<T> dataset) { // 声明一个工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一个表格 HSSFSheet sheet = workbook.createSheet(title); // 设置表格默认列宽度为18个字节 sheet.setDefaultColumnWidth((short) 18); // 生成一个样式 HSSFCellStyle style = workbook.createCellStyle(); // 设置这些样式 style.setFillForegroundColor(HSSFColor.WHITE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一个字体 HSSFFont font = workbook.createFont(); // font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前的样式 style.setFont(font); // 生成并设置另一个样式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.WHITE.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成另一个字体 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字体应用到当前的样式 style2.setFont(font2); // 产生表格标题行 HSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } // 遍历集合数据,产生数据行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值 Field[] fields = t.getClass().getDeclaredFields(); for (short i = 0; i < fields.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style2); Field field = fields[i]; String fieldName = field.getName(); String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Class tCls = t.getClass(); Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); // 判断值的类型后进行强制类型转换 if(fieldName.equals("dealCost") || fieldName.equals("dealPrice")){ cell.setCellValue(Double.parseDouble(value.toString())); }else if(fieldName.equals("status")){ cell.setCellValue(TSTGSettleStatusEnum.getByCode(Integer.valueOf(value.toString())).getMessage()); }else if(value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cell.setCellValue(sdf.format(date)); }else { cell.setCellValue(value.toString()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 清理资源 } } } return workbook; } public static void main(String[] args) { /* ExportExcel<SettleGroup> ex = new ExportExcel<SettleGroup>(); String[] headers = { "团单号", "套餐号", "验券门店", "结算价", "售价", "验券时间", "券号", "打款状态"}; List<SettleGroup> dataset = new ArrayList<SettleGroup>(); SettleGroup settleGroup = new SettleGroup(); settleGroup.setStatus("已打款"); settleGroup.setConsumeTime(new Date()); settleGroup.setSellPrice(new BigDecimal("188")); settleGroup.setSettleGroupNo("15034827"); settleGroup.setSettlePackageNo("15142878"); settleGroup.setSettlePrice(new BigDecimal("174.84")); settleGroup.setShopId("11313206"); settleGroup.setVoucherNo("7893006716"); for(int i = 0; i < 10; i++){ dataset.add(settleGroup); } try { HSSFWorkbook workbook = ex.exportExcel(headers, dataset); OutputStream out = new FileOutputStream("E://a.xls"); workbook.write(out); out.close(); System.out.println("excel导出成功!"); } catch (Exception e) { e.printStackTrace(); } */ } }
附:前端页面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="/css/bootstrap.min.css" rel="stylesheet"> <title></title> </head> <body> <div class="panel panel-primary"> <div class="panel-heading"> <div class="panel-title">搬单错误数据查询</div> </div> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <form class="form-horizontal" action="/settle/downloadResultAction" onsubmit="return check()" method="post"> <div class="form-group"> <label class="col-md-2 control-label">团单号</label> <div class="col-md-10"> <textarea rows="3" class="form-control" id="dealGroupIds" name="dealGroupIds" placeholder="使用英文逗号分隔"></textarea> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button class="btn btn-primary" type="submit">查询</button> </div> </div> </form> </div> </div> </div> </div> <script type="text/javascript" src="/js/jquery.min.js"></script> <script type="text/javascript"> function check(){ if($("#dealGroupIds").val() == "" || $("#dealGroupIds").val() == ","){ alert("请输入团单号"); return false; } } </script> </body> </html>
本文出自 “优赛工作室” 博客,谢绝转载!
原文:http://shamrock.blog.51cto.com/2079212/1772124