0

I want to splicing the data in the list with StringBuilder and return the csv file to the front end, but the data contains Chinese characters. When I open it with Microsoft Notepad, there will be no garbled characters, but when I open it with Excel, garbled characters will appear.

public void generateCSV(List<A> data, HttpServletResponse response){
    StringBulider sb = new StringBuilder();
    // append BOM
    sb.append('\uFEFF');
    // append title
    sb.append(String.join(",", CSV_HEADERS));
    // TODO append list data
    response.setContentType("text/csv");
    String encodedName = URLEncoder.encode("data.csv", StandardCharsets.UTF_8);
    response.setHeader("Content-Disposition", "attachment; filename=" + encodedName);
    OutputStream outputStream = response.getOutputStream();
    outputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
}

It seems that adding the BOM header has no effect. The post I found on Google is to return to the front-end csv file through the file stream, but I want to try my approach. Can't I do it this way? Or something missing in my code?

I'd appreciate any advice.

HuaJFrame
  • 72
  • 7

0 Answers0