需求:頁面輸入團單號,從數據庫中查詢搬單錯誤的數據,以excel形式導出。
javascript
前端頁面放在ts-settle-tools-web項目中,後端查詢數據庫的部分寫在ts-tg-settle中,以API形式提供給ts-settle-tools使用,實際上是經過webservice調用的。css
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中引入使用。html
在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服務的地址。java
<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前端效果以下
jquery
Controller部分web
@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", "p_w_upload;filename=" + filename); OutputStream ouputStream = response.getOutputStream(); workbook.write(ouputStream); ouputStream.flush(); ouputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
Service部分
spring
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(); } */ } }
附:前端頁面代碼
bootstrap
<%@ 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>