javascript - 使用 java/javascript 和 apache POI 导出 .xls 文件时文件损坏

标签 javascript java excel apache-poi

我正在尝试从 Web 应用程序在浏览器中下载 .xls 文件。下面是相同的代码。

try(FileInputStream inputStream = new FileInputStream("C:\\Users\\Desktop\\Book1.xls")){
            response.setContentType("application/vnd.ms-excel");
            //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=Book1.xls");
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[BUFFERSIZE];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

下面是用于下载文件内容的 JavaScript 代码。

success: function(response, status, xhr) {

                let type = xhr.getResponseHeader('Content-Type');
                let blob = new Blob([response], { type: type });

                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created.
                    //These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    let URL = window.URL || window.webkitURL;
                    let downloadUrl = URL.createObjectURL(blob);
                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        let a = document.createElement("a");
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }
                    setTimeout(function () {
                        URL.revokeObjectURL(downloadUrl);
                    }, 100); // cleanup
                }
            }

我可以下载该文件,但下载的文件内容不是可读格式。如果它是 csv 文件,我可以在我的 javascript 响应对象中看到内容,而 .xls 文件 javascript 响应对象包含不可读的格式化数据。

有人可以帮我吗?

最佳答案

如果其他人遇到同样的问题,请发布此解决方案,我通过将字节数组编码为字符串的 Base64 解决了此问题,如下所示。

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 workbook.write(outputStream);
 String res = Base64.getEncoder().encodeToString(outputStream.toByteArray());

在 javascript 中,我使用下面链接中的 base64ToBlob 方法解码了该字符串

https://stackoverflow.com/a/20151856/2011294

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

关于javascript - 使用 java/javascript 和 apache POI 导出 .xls 文件时文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472768/

相关文章:

java - spring mvc Autowiring sessionFactory 给出 null 对象

Excel VBA 非英文字符支持读取文件

Python - 对试图理解的人的基本解释(CSV,Excel)

excel - VBA - 获取最后添加的工作表的名称

java - 如何将 javascript 对象传递给 GWT 方法并解析结果

javascript - 理解 JavaScript 文档符号

java - 如何使用 ListView 放置复选框(Android)

javascript - NodeJS - response.send() 不是函数

javascript - 如何根据 Javascript 中的属性组合两个不同大小的对象数组?

java - Jvm 会加载一个类文件两次吗?