使用java apache poi和react通过api发送xls

niwlg2el  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(283)

我正试图从javaspring服务器向react客户端发送一个xls文件。
使用默认的apachepoi构造函数创建xlsx文件,这是不好的。为了覆盖它,我必须使用fileoutputstream创建文件。

FileOutputStream outputStream = new FileOutputStream("file.xls");

但我不能通过网络发送文件。我试着使用以下答案:https://stackoverflow.com/a/54765335/10319765 我引用:“在下载一个文件时,您的代码需要一块一块地流式处理文件—这就是java流的用途。”

return ResponseEntity.ok().contentLength(inputStreamWrapper.getByteCount())
        .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
        .cacheControl(CacheControl.noCache())
        .header("Content-Disposition", "attachment; filename=" + "file.xls")
        .body(new InputStreamResource(inputStreamWrapper.getByteArrayInputStream()));

所以我的控制器正在发送 InputStreamResource .
我如何构造 InputStreamResource 使用我的 FileOutputStream ?
p、 这是我的客户:

axios.get('/issues/export', { responseType: 'arraybuffer' }).then(response => {
        if (response && !response.error) {
            const blob = new Blob([response.payload.data], {type: 'application/vnd.ms-excel'});
            saveAs(blob);
        }
    });

资料来源:https://stackoverflow.com/a/46331201/10319765

编辑:

我用一个技巧做到了这一点,在我写入fileoutputstream之后,我打开了一个fileinputstream并返回了值。

FileOutputStream outputStream = new FileOutputStream("file.xls");
    workbook.write(outputStream);
    workbook.close();
    final InputStream fileInputStream = new FileInputStream("file.xls");
    return fileInputStream;

但现在,作为对客户端的响应而返回的xls文件已损坏,其中包含奇怪的字符:


excel文件应如下所示(发送后从我的java服务器获取):

rqmkfv5c

rqmkfv5c1#

问题解决了。最终,为了解决损坏的xls文件,我所做的是使用字节数组。控制器看起来完全相同,但现在返回类型是 ResponseEntity<byte[]> . 转换 InputStream 到我用过的字节数组 IOUtils.toByteArray() 方法。
客户端代码也发生了一些变化,因为现在类型不再是 responseType: 'arraybuffer' 但是 'blob' .

axios.get('/issues/export', { responseType: 'blob' }).then(response => {
    if (response && !response.error) {
        const blob = new Blob([response.payload.data]);
        saveAs(blob);
    }
});

这就是全部。

相关问题