pawelini1
pawelini1

Reputation: 487

Encoding issue with Apache POI

I'm creating MS Excel file using Apache POI and everything works fine while I'm using it at localhost. But when I deploy project on Google App Engine and then try to open created file in MS Excel I can notice that all my special characters changed into question marks "?". Does anyone of you could tell me why it works on localhost but fail to show special character after deploying.

public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        try {
            OutputStream out = null;
            try
            {
                String dataa = req.getParameter("dataa");
                String json = URLDecoder.decode(dataa, "UTF-8");
                Gson gson = new Gson();
                ExcelData excelData = gson.fromJson(json, ExcelData.class);

                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet1 = (HSSFSheet) workbook.createSheet("myData");

                // workbook creation...

                ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
                workbook.write(outByteStream);
                byte [] outArray = outByteStream.toByteArray();
                res.setContentType("application/ms-excel");
                res.setContentLength(outArray.length);
                res.setHeader("Expires:", "0");
                res.setHeader("Content-Disposition", "attachment; filename=raport.xls");

                out = res.getOutputStream();
                out.write(outArray);
                out.flush();

            } catch (Exception e)
            {
                throw new ServletException("Exception in Excel Sample Servlet", e);
            } finally
            {
                if (out != null)
                    out.close();
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }

Upvotes: 3

Views: 9203

Answers (1)

pawelini1
pawelini1

Reputation: 487

Problem SOLVED

It's quite funny when you try to debug problem for some time and then find the answer just after posting on stackoverflow :) Anyway problem was here:

String data = URLEncoder.encode(someString);
String data2 = URLDecoder.decode(data, "UTF-8");

So while working on localhost with App Engine Local Server data == data2, but on production server data != data2 and the difference are special characters which are encoded as question marks.

// solution
String data = URLEncoder.encode(someString, "UTF-8");
String data2 = URLDecoder.decode(data, "UTF-8");

Upvotes: 1

Related Questions