Getting corrupted file while exporting .xls file using java/javascript and apache POI

前端 未结 1 1536
失恋的感觉
失恋的感觉 2021-01-23 10:21

I am trying to downlaod a .xls file in browser from a web application. Below is the code for the same.

try(FileInputStream inputStream = new FileInputStream(\"C:         


        
相关标签:
1条回答
  • 2021-01-23 10:58

    Posting this solution if anyone else faces the same issue, I resolved this issue via base64 encoding the byte array to a string as below.

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

    In javascript I decoded that string using base64ToBlob method from below link

    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 });
    }
    
    0 讨论(0)
提交回复
热议问题