Encoding issue with Apache POI

旧城冷巷雨未停 提交于 2019-12-22 12:30:58

问题


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);
        }
    }

回答1:


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");


来源:https://stackoverflow.com/questions/24564028/encoding-issue-with-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!