Convert byteArray to XSSFWorkbook using Apache POI

2019-05-29 02:24发布

问题:

I am using Apache POI and I am trying to send a xlsx file as HTTP request and get it back as response. I am using jayway restassured for making HTTP requests.

Here is the part of the code where I send the request

 File file = new File("path");
String response = given().multipart(file).when().post("URL").getBody().asString();

byte[] bytes = response.getBytes("ISO-8859-1");
InputStream stream = new ByteArrayOutputStream(bytes);

try
{
    XSSFWorkbook workbook = new XSSFWorkbook(stream);
}
catch(Exception e){
    e.printStackTrace();
}

Here is the code where the response is generated for the request

XSSFWorkbook workBook;  //this workBook has the workbook sent as HTTP request
//code to make changes in workBook

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

workBook.write(outStream);
byte[] byteArray = outStream.toByteArray();
String responseBody = new String(byteArray, "ISO-8859-1");

context.response().putHeader("Content-Type", "multipart/form-data").setStatusCode(200).end(responseBody);

So, what I am trying to do is send a xlsx file as request make some changes and get it back as a string response, convert it back to xssfworkbook. When converting back I get error in the following line-

XSSFWorkbook workbook = new XSSFWorkbook(stream);

The error I get is

java.util.zip.ZipException: invalid code lengths set

回答1:

You cannot simply send the byte-array as ISO-8859-1 encoded text the way you attempt.

There will be special characters that might get replaced/truncated/modified.

Currently you mix binary data and a text-only channel (HTTP). You will need to do it differently, either use a binary data transfer and not convert it to String or use some binary-to-text representation, see e.g. https://en.wikipedia.org/wiki/Binary-to-text_encoding, the most common one being Base64