0

Why does the file name appear garbled when using easyExcel to export the excel file? The browser used is chrome.
The output file name is %3F%3F%3F%3F%3F%3F%3F%3F2020-08-28 11_11_28.xlsx

public String encodeFileName(String userAgent, String fileName){
    try{
        fileName = StringUtils.contains(userAgent, "Mozilla") ? URLEncoder.encode(fileName, "ISO8859-1") : URLEncoder.encode(fileName, "UTF-8");
        return fileName;
    } catch (UnsupportedEncodingException e){
        e.printStackTrace();
        return fileName;
    }
}

final String userAgent = request.getHeader("USER-AGENT");
        String encodeFileName = encodeFileName(userAgent,"流程管理名单")+ DateUtil.getyyyyMMddHHmmss(new Date())+".xlsx";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition",
                "attachment;filename=" + encodeFileName);
        out = response.getOutputStream();
zbin z
  • 1
  • 1
  • Consider using Spring's [`ContentDisposition`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ContentDisposition.html). For sample code see [this answer](https://stackoverflow.com/a/53961688/6486622) – Denis Zavedeev Aug 28 '20 at 03:25
  • The `encodeFileName` seems to have selected `ISO8859-1` as the character set. That is, the user agent includes `Mozilla`. Why is there 8 `%3F`, even though `"流程管理名单"` has 6 characters? –  Aug 28 '20 at 05:17

1 Answers1

0

Why does the file name appear garbled when using easyExcel to export the excel file?

ISO8859-1 does not support characters you're trying to encode.

You can simply encode the filename using UTF-8:

public String encodeFileName(String userAgent, String fileName) {
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
    return fileName;
}

Or, if you're using Spring 5+ use ContentDisposition:

String contentDisposition = ContentDisposition.builder("attachment")
        .filename("流程管理名单.xlsx")
        .build()
        .toString();
response.setHeader("Content-Disposition", contentDisposition);

See also

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53