导出excel文件(前后端共同作用)

对于一些需要导出成为Excel的数据,需要通过后端编写处理数据的接口,将要插入的数据写入excel文件中。
后端代码:

public class PoiUtils {
    public static ResponseEntity<byte[]> exportQ2Excel(List<Map<String, String>> list1, List<Map<String, String>> list2, List<Map<String, String>> list3) {
        HttpHeaders headers = null;
        ByteArrayOutputStream baos = null;
        try {
            //创建第一个Excel文档
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建Excel表单,设置sheet名称
            HSSFSheet sheet1 = workbook.createSheet("a");
            //设置表头
            HSSFRow headerRow1 = sheet1.createRow(0);
			//插入表头数据,可以多行插入,现只插入一行
            headerRow1.createCell(0).setCellValue("ID");
            //装数据,可以多行插入,现只插入一行
            for (int i = 0; i < list1.size(); i++) {
                HSSFRow row = sheet1.createRow(i + 1);
                row.createCell(0).setCellValue(list1.get(i).get("ID"));
            }

            //创建第二个Excel表单
            HSSFSheet sheet2 = workbook.createSheet("b");
            //设置表头
            HSSFRow headerRow2 = sheet2.createRow(0);
			//插入表头数据,可以多行插入,现只插入一行
            headerRow2.createCell(0).setCellValue("ID");
            //装数据,可以多行插入,现只插入一行
            for (int i = 0; i < list2.size(); i++) {
                HSSFRow row = sheet2.createRow(i + 1);
                row.createCell(0).setCellValue(list2.get(i).get("ID"));
            }

            //创建第三个Excel表单
            HSSFSheet sheet3 = workbook.createSheet("c");
			//设置表头,可以多行插入,现只插入一行
            HSSFRow headerRow3 = sheet3.createRow(0);
            headerRow3.createCell(0).setCellValue("ID");
			//装数据,可以多行插入,现只插入一行
            for (int i = 0; i < list3.size(); i++) {
                HSSFRow row = sheet3.createRow(i + 1);
                row.createCell(0).setCellValue(list3.get(i).get("ID"));
            }
            headers = new HttpHeaders();
			//经过试验,此处的命名无法起作用。真正起作用的是前端的文件定义
            headers.setContentDispositionFormData("attachment",
                    new String("aaaaa.xls".getBytes("UTF-8"), "iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            baos = new ByteArrayOutputStream();
            workbook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
    }
}

以上可以生成三个sheet表的excel文件,对于不需要生成多sheet的程序来说,只需要添加一个sheet即可, 切 记 , 传 参 的 时 候 记 得 修 改 传 参 个 数 \color{red}{切记,传参的时候记得修改传参个数}

下面是前端(Angular)代码:

export() {
	// 此处写后端接口的地址
    const url;
    return this.http.get(url,
      {headers: this.header, observe: 'response', responseType: 'blob'}).subscribe(response => {
      // 规范下载格式,对不同的浏览器进行不同的处理,主要针对IE浏览器
      this.downloadFile(response);
      this.nzMessageService.success('导出成功!');
    }, error => {
      this.nzMessageService.error('导出失败!');
    });
  }

  downloadFile(data: HttpResponse<Blob>) {
    // 为了兼容IE
    const uA = window.navigator.userAgent;
    const isIE = /msie\s|trident\/|edge\//i.test(uA) && !!('uniqueID' in document || 'documentMode' in document || ('ActiveXObject' in window) || 'MSInputMethodContext' in window);

    const file = new Blob([data.body], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    // const fileName = decodeURIComponent(data.headers.get('content-disposition').split('filename=')[1]);
    const currentDate = new Date();
    // 此处是真正的对excel表的名字进行命名的地方
    const fileName = 'a-' + currentDate.getFullYear() + (currentDate.getMonth() + 1)
      + currentDate.getDate() + currentDate.getHours() + currentDate.getMinutes() + currentDate.getSeconds() + '.xls'; // 名称
    if (isIE) {  // 如果是IE
      navigator.msSaveBlob(file, fileName);
    } else {
      const a = document.createElement('a');
      a.id = 'tempId';
      document.body.appendChild(a);
      a.download = fileName;
      a.href = URL.createObjectURL(file);
      a.click();
      // 删除<a>标签
      const tempA = document.getElementById('tempId');
      if (tempA) {
        tempA.parentNode.removeChild(tempA);
      }
    }
  }

以上Angular代码存在于service中,可以直接通过ts文件里进行调用,记得在html文件里面写(click)="exportTable()"哦!这样可以实现点击执行exportTable函数中的操作,将export函数加进去,大功告成!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值