学习记录404@react+java+poi导出excel实现

页面

在这里插入图片描述

前端

只记录核心点

  const exportData = () => {
    // Object.keys遍历每个key
    const exportPara = Object.keys(paramsQuery)
      .filter((k) => !!paramsQuery[k])//判断是否为真的,0 和空 null undefined 都为false
      // encodeURIComponent 编码
      // _.isObject 判断是否是对象,如果是对象,返回true
      // _.isArray 判断是否是数组
      // 如果是对象或者数组就转化为json
      .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(_.isObject(paramsQuery[k]) || _.isArray(paramsQuery[k]) ? JSON.stringify(paramsQuery[k]) : paramsQuery[k])}`)
      .join('&')
      // 必须要携带token
    window.open(baseURL + '/third/PingGu/exportPingGuCallDetail?' + exportPara + '&token=' + encodeURIComponent(sessionStorage.getItem('token')))
  }
//虽然引入的图标是AssignmentReturnedSharpIcon,但是要全部小写,且中间部分大写的地方前面要加下划线
              <Button icon="assignment_returned_sharpIcon" variant="contained" color="primary" title="导出" buttonType="button" className="mr-2" onClick={exportData} />}

后端

只记录核心点

//查询结果
        List<Map<String, Object>> list = MysqlDaoImpl.getInstance().queryBySql(sql, null, params, null);

//        导出 xlsx
        Workbook workbook = new XSSFWorkbook();
        //        在工作薄中创建一个工作表
        Sheet sheet = workbook.createSheet();
        //        设置列宽
        sheet.setColumnWidth(0,10*256);
        sheet.setColumnWidth(1,20*256);
        sheet.setColumnWidth(2,40*256);
        sheet.setColumnWidth(3,10*256);
        sheet.setColumnWidth(4,15*256);
        sheet.setColumnWidth(4,10*256);
        sheet.setColumnWidth(4,10*256);
        //            处理标题
        String[] titles = new String[]{"评估方","调用接口","发起人","评估时间","价格","是否成功","是否平台","是否单页面"};

        //        创建标题行
        Row titleRow = sheet.createRow(0);
        Cell cell = null;
        for (int i = 0; i < titles.length; i++) {
            cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        //        处理内容
        int rowIndex = 1;
        Row row = null;

        for (Map map : list) {
            row = sheet.createRow(rowIndex);
            cell = row.createCell(0);
            cell.setCellValue(map.get("type")==null?"":map.get("type").toString());

            cell = row.createCell(1);
            cell.setCellValue(map.get("apiName")==null?"":map.get("apiName").toString());

            cell = row.createCell(2);
            cell.setCellValue(map.get("name")==null?"":map.get("name").toString());

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            cell = row.createCell(3);
            String createTime = map.get("createTime") == null ? "" : map.get("createTime").toString();
            if (createTime==""){
                cell.setCellValue("");
            }else {
                Date date = new Date(Long.parseLong(createTime));//必须转化为long类型
                cell.setCellValue(dateFormat.format(date));
            }

            cell = row.createCell(4);
            cell.setCellValue(map.get("price")==null?"":map.get("price").toString());

            cell = row.createCell(5);
            cell.setCellValue(map.get("msg")==null?"":map.get("msg").toString());


            cell = row.createCell(6);
            cell.setCellValue(isPlatform==null?"全部":isPlatform.equals("ture")?"是":"否");

            cell = row.createCell(7);
            cell.setCellValue(isSinglePage==null?"全部":isSinglePage.equals("ture")?"是":"否");
            rowIndex++;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        //            导出的文件名称
        String filename="评估调用明细"+dateFormat.format(new Date())+".xlsx";
        //            设置文件的打开方式和mime类型
        HttpServletResponse response = ControllerContext.getContext().getResponse();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在前端接收并导出后端导出Excel文件,也可以使用`xlsx`和`file-saver`库来实现。 首先,需要使用`fetch`或`axios`等网络请求库向后端请求Excel文件,并将返回的二进制流进行解析。可以使用`xlsx`库的`read`方法将二进制流转换为JSON格式的数据。示例代码如下: ```javascript import { read } from 'xlsx'; import { saveAs } from 'file-saver'; // ... fetch(url, { responseType: 'blob' }).then(res => { const reader = new FileReader(); reader.onload = () => { const data = new Uint8Array(reader.result); const workbook = read(data, { type: 'array' }); // 处理表格数据 // ... // 导出表格数据 const excelBuffer = write(workbook, { type: 'array', bookType: 'xlsx' }); const excelBlob = new Blob([excelBuffer], { type: 'application/octet-stream' }); saveAs(excelBlob, /* 指定的文件名 */); }; reader.readAsArrayBuffer(res.data); }); ``` 以上代码中,`fetch`请求的响应数据类型设置为`blob`,表示返回的是二进制流。接收到响应数据后,使用`FileReader`将二进制流转换为数组缓冲区,再使用`xlsx`库的`read`方法将数组缓冲区转换为JSON格式的数据。接下来根据具体需求进行表格数据处理,并使用`write`方法将数据转换为Excel文件的二进制流,最后使用`file-saver`库的`saveAs`方法将二进制流导出Excel文件。 需要注意的是,在导出Excel文件时,需要设置正确的文件类型和文件名,否则可能会导致文件无法打开或文件名不符合预期。 以上是一个简单的接收和导出Excel文件的流程,具体实现还需要根据具体情况进行相应的调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值