angular4 excel导出

##前端HTML页面:

<div class="col-lg-1 mb" style="text-align:center">
  <button class="btn btn-oval btn-danger" type="button" (click)="export()" >导出</button>
</div>

 

## 前端js:

 前端js方法:

public export() {
  const params = {
    appId:this.appId
  };
  this.http.download('/user/app/order/export',params)
    .subscribe(res => {
      const blob = new Blob([res], {type: 'application/vnd.ms-excel'});
      // const fileName = res.headers().filename;
      const fileName = '支付交易记录' + '.xlsx';
      if (window.navigator.msSaveOrOpenBlob) {// For IE浏览器
        navigator.msSaveBlob(blob, fileName);
      } else { // For 其他浏览器
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', fileName);
        a.click();
        URL.revokeObjectURL(objectUrl);
      }
    });
  }
}

 http.download代码封装

 1  public download(url:string, params?: any): Observable<any> {
 2         url = HOST + url;
 3         const headers = new HttpHeaders().set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
 4         const responseType ='blob';
 5         let httpParams: HttpParams = new HttpParams();
 6         if (params) {
 7             for (const p in params) {
 8                 if (params[p]) {
 9                     httpParams = httpParams.set(p, params[p]);
10                 }
11             }
12         }
13         return this.http.get( url,{ 'headers': headers,'responseType': responseType,'params':httpParams })
14         .map(res =>{
15             return res
16         });
17     }

 

## java后台:
 1 /**
 2      * 导出excel
 3      */
 4     public void export(){
 5         //获取查询条件
 6         String appId = getPara("appId");
 7         //判空校验
 8         if(StrKit.isBlank(appId)){
 9             renderJson(RMsg.fail("参数不存在"));
10             return;
11         }
12         //查询数据
13         List<TblTransferRecord> list = TblTransferRecord.me.find(
14                 "SELECT " +
15                 "a.*, b. NAME, " +
16                 "CASE transferState " +
17                 "WHEN 1 THEN " +
18                 "'待转账' " +
19                 "WHEN 2 THEN " +
20                 "'转账处理中' " +
21                 "WHEN 3 THEN " +
22                 "'转账失败' " +
23                 "WHEN 4 THEN " +
24                 "'已退款' " +
25                 "ELSE " +
26                 "'成功' " +
27                 "END AS transferState " +
28                 "FROM " +
29                 "TblTransferRecord a " +
30                 "LEFT JOIN MstTransferMethod b ON a.transferCode = b. CODE " +
31                 "WHERE " +
32                 "appId = ? " +
33                 "ORDER BY " +
34                 " a.updateTime DESC ",appId);
35         //判空
36         if(list == null || list.size() <  0){
37             renderText("暂无记录");
38             return;
39         }
40 
41         //获取上传地址
42         String uploadFolder = PropKit.get(ConstValue.UPLOAD_FILE_PATH).replace('/', File.separatorChar).replace('\\',File.separatorChar);
43         //获取文件路径
44         String filePath = uploadFolder + File.separator + System.currentTimeMillis() + FILE_EXTENSION;
45 
46         //创建目录
47         File dir = new File(filePath);
48 
49         if(!dir.getParentFile().exists()){
50             dir.getParentFile().mkdirs();
51         }
52 
53         createExcel(filePath,list);
54 
55         File file = new File(filePath);
56 
57         if (file == null || !file.exists()) {
58             renderText("对不起,您所要下载的文件不存在!");
59         } else {
60             renderDownloadFile(file, "退款记录.xlsx");
61         }
62     }
##excel样式:

 1 private static CellStyle getCenterCellStyle(Workbook wb) {
 2     CellStyle cellStyle = wb.createCellStyle();
 3     cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
 4     cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
 5 
 6     cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
 7     cellStyle.setBorderTop(CellStyle.BORDER_THIN);
 8     cellStyle.setBorderRight(CellStyle.BORDER_THIN);
 9     cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
10     cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
11     cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
12     cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
13     cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
14 
15     return cellStyle;
16 }
 1 /**
 2  * 设置自定义的颜色
 3  *
 4  * @param cellStyle
 5  */
 6 private static void setCustomColor(XSSFCellStyle cellStyle) {
 7     cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(0xf3, 0xf3, 0xf3)));
 8     cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
 9 }
10 
11 /**
12  * 设置白色
13  *
14  * @param cellStyle
15  */
16 private static void setWhiteColor(XSSFCellStyle cellStyle) {
17     cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
18     cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
19 }

##创建excel:方法1
  1 /**
  2      * 生成excel表格
  3      * @param filePath
  4      * @param list
  5      * @author tgb
  6      */
  7     private static void createExcel(String filePath, List<TblTransferRecord> list) {
  8 
  9         //创建工作簿
 10         Workbook wb = new XSSFWorkbook();
 11         //创建工作表
 12         Sheet sheet = wb.createSheet("转账记录");
 13         //创建一行
 14         Row row = sheet.createRow(0);
 15         //创建列
 16         for(int i = 0;i < 8; ++i){
 17             row.createCell(i);
 18         }
 19 
 20         //设置单元格的宽高
 21         sheet.setColumnWidth(0, 35 * 200);
 22         sheet.setColumnWidth(1, 35 * 200);
 23         sheet.setColumnWidth(2, 35 * 200);
 24         sheet.setColumnWidth(3, 35 * 200);
 25         sheet.setColumnWidth(4, 35 * 200);
 26         sheet.setColumnWidth(5, 35 * 200);
 27         sheet.setColumnWidth(6, 35 * 200);
 28         sheet.setColumnWidth(7, 35 * 200);
 29         //去掉网格线
 30         sheet.setDisplayGridlines(false);
 31 
 32         //合并标题单元格
 33         sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
 34         //标题
 35         row.getCell(0).setCellValue("转账记录");
 36         //行高
 37         row.setHeightInPoints(30);
 38         //获取工作薄样式
 39         CellStyle cellStyle = getCenterCellStyle(wb);
 40         //设置标题单元格的颜色
 41         cellStyle.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
 42         //设置标题单元格的填充模式
 43         cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
 44         row.getCell(0).setCellStyle(cellStyle);
 45 
 46         //换行
 47         row = sheet.createRow(1);
 48 
 49         cellStyle = getCenterCellStyle(wb);
 50         row.createCell(0).setCellValue("批次号");
 51         row.createCell(1).setCellValue("卡号");
 52         row.createCell(2).setCellValue("银行");
 53         row.createCell(3).setCellValue("收款人");
 54         row.createCell(4).setCellValue("金额");
 55         row.createCell(5).setCellValue("转账方式");
 56         row.createCell(6).setCellValue("状态");
 57         row.createCell(7).setCellValue("创建时间");
 58 
 59         row.getCell(0).setCellStyle(cellStyle);
 60         row.getCell(1).setCellStyle(cellStyle);
 61         row.getCell(2).setCellStyle(cellStyle);
 62         row.getCell(3).setCellStyle(cellStyle);
 63         row.getCell(4).setCellStyle(cellStyle);
 64         row.getCell(5).setCellStyle(cellStyle);
 65         row.getCell(6).setCellStyle(cellStyle);
 66         row.getCell(7).setCellStyle(cellStyle);
 67 
 68         if (list != null && list.size() > 0) {
 69             for (int i = 0; i < list.size(); ++i) {
 70                 row = sheet.createRow(i + 2);
 71                 TblTransferRecord record = list.get(i);
 72 
 73                 row.createCell(0).setCellValue(record.getStr("batchNo")); //批次号
 74                 row.createCell(1).setCellValue(record.getStr("cardNo"));  //卡号
 75                 row.createCell(2).setCellValue(record.getStr("bankName"));//银行
 76                 row.createCell(3).setCellValue(record.getStr("cardHolder"));//收款人
 77                 row.createCell(4).setCellValue(record.getStr("amount"));//金额
 78                 row.createCell(5).setCellValue(record.getStr("transferCode"));//转账方式
 79                 row.createCell(6).setCellValue(record.getStr("transferState"));//状态
 80                 row.createCell(7).setCellValue(record.getStr("createTime")); //创建时间
 81 
 82                 cellStyle = getCenterCellStyle(wb);
 83 
 84                 if (i % 2 == 0) {
 85                     setCustomColor((XSSFCellStyle) cellStyle);
 86                 } else {
 87                     setWhiteColor((XSSFCellStyle) cellStyle);
 88                 }
 89 
 90                 row.getCell(0).setCellStyle(cellStyle);
 91                 row.getCell(1).setCellStyle(cellStyle);
 92                 row.getCell(2).setCellStyle(cellStyle);
 93                 row.getCell(3).setCellStyle(cellStyle);
 94                 row.getCell(4).setCellStyle(cellStyle);
 95                 row.getCell(5).setCellStyle(cellStyle);
 96                 row.getCell(6).setCellStyle(cellStyle);
 97                 row.getCell(7).setCellStyle(cellStyle);
 98             }
 99         }
100 
101         FileOutputStream fileOut = null;
102 
103         try {
104             File file = new File(filePath);
105 
106             if (file.isFile() && !file.exists()) {
107                 file.createNewFile();
108             }
109             fileOut = new FileOutputStream(filePath);
110             wb.write(fileOut);
111         } catch (FileNotFoundException e) {
112             e.printStackTrace();
113         } catch (IOException e) {
114             e.printStackTrace();
115         } finally {
116             try {
117                 if(fileOut != null) {
118                     fileOut.close();
119                 }
120             } catch (IOException e) {
121                 e.printStackTrace();
122             }
123         }
124 
125     }

 ##createExcel 方法2:


 
posted @ 2018-04-17 13:48  downs  阅读(3158)  评论(0编辑  收藏  举报