【发布时间】:2018-02-28 00:37:06
【问题描述】:
显然,要让 excel 很好地打开 CSV 文件,它的开头应该有字节顺序标记。 CSV 的下载是通过在控制器中写入HttpServletResponse 的输出流来实现的,因为数据是在请求期间生成的。当我尝试写入 BOM 字节时出现异常 - java.io.CharConversionException: Not an ISO 8859-1 character: [](即使我指定的编码是 UTF-8)。
有问题的控制器方法
@RequestMapping("/monthly/list")
public List<MonthlyDetailsItem> queryDetailsItems(
MonthlyDetailsItemQuery query,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "attachment", required = false, defaultValue="false") Boolean attachment,
HttpServletResponse response) throws Exception
{
// load item list
List<MonthlyDetailsItem> list = detailsSvc.queryMonthlyDetailsForList(query);
// adjust format
format = format != null ? format.toLowerCase() : "json";
if (!Arrays.asList("json", "csv").contains(format)) format = "json";
// modify common response headers
response.setCharacterEncoding("UTF-8");
if (attachment)
response.setHeader("Content-Disposition", "attachment;filename=duomenys." + format);
// build csv
if ("csv".equals(format)) {
response.setContentType("text/csv; charset=UTF-8");
response.getOutputStream().print("\ufeff");
response.getOutputStream().write(buildMonthlyDetailsItemCsv(list).getBytes("UTF-8"));
return null;
}
return list;
}
【问题讨论】:
-
您可以试试
response.getOutputStream().write("\ufeff".getBytes("UTF-8"));的 BOM 部分吗?
标签: java spring utf-8 byte-order-mark