遇到的问题是:
通过java请求服务器,在文件中心拿到文件EXCEL或者txt,返回到前端直接预览查看内容出现中文乱码
例如:
public void viewFile(){
HttpServletResponse response = ((ServletRequestAttributes)RequestContexHolder.currentRequestAttributes()).getResponse();
byte[] bytes = this.downloadFromFC();
try(InputStream inputStream = new ByteArrayInputStream(bytes)){
ExcelToHtmlParams params = new ExcelToHtmlParams(WorkBookFactory.create(inputStream));
response.getOutputStream().write(ExcelXorHtmlUtil.excelToHtml(params).getBytes());
response.setContentType("text/html");
}catch(Exception e){
}
}
解决的方法:
①更改编码为UTF-8
②注意代码编码顺序(极易忽略的问题,先声明编码,再写流)
public void viewFile(){
HttpServletResponse response = ((ServletRequestAttributes)RequestContexHolder.currentRequestAttributes()).getResponse();
byte[] bytes = this.downloadFromFC();
try(InputStream inputStream = new ByteArrayInputStream(bytes)){
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ExcelToHtmlParams params = new ExcelToHtmlParams(WorkBookFactory.create(inputStream));
response.getOutputStream().write(ExcelXorHtmlUtil.excelToHtml(params).getBytes());
}catch(Exception e){
}
}