当我从包含 java 的文件夹下载 Excel 时,出现此错误“.xls 文件的格式和扩展名不匹配。文件可能已损坏”
When I download Excel from a folder with java I get this error " the format and extension of the .xls file do not match. The file may be damaged"
正如标题所说,当我从文件夹下载 excel sheet 时,我收到此消息
这是我的代码
RequestMapping(value = "/descargar-datos-entrada/{idSimulacion}", method = RequestMethod.GET)
public void descargarDatosEntrada(@PathVariable("idSimulacion") String idSimulacion, HttpServletResponse response)
throws IOException {
Properties properties = new Properties();
properties = Util.getProperties("mongo");
FileInputStream inputStream = null;
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=Hoja-Resultados-Descarga.xls");
try {
Simulacion simulacion = simulacionService.finById(idSimulacion);
inputStream = new FileInputStream(
properties.getProperty("ruta.copia.resultados.excel") + idSimulacion + ".xls");
int c;
while ((c = inputStream.read()) != -1) {
response.getWriter().write(c);
}
} catch (SimulacionException | IOException e) {
Util.autoLogError(e);
} finally {
if (inputStream != null)
inputStream.close();
response.getWriter().close();
}
}
结果 .xls 文件如下:
我将不胜感激一些帮助或建议,在此先感谢,这是我的第一个问题,如果我问得不正确,请原谅。
使用 getOutputStream
进行二进制输出,而不是文本输出 getWriter
:
Path path = Paths.get(properties.getProperty("ruta.copia.resultados.excel")
+ idSimulacion + ".xls");
Files.copy(path, response.getOutputStream());
正如标题所说,当我从文件夹下载 excel sheet 时,我收到此消息
这是我的代码
RequestMapping(value = "/descargar-datos-entrada/{idSimulacion}", method = RequestMethod.GET)
public void descargarDatosEntrada(@PathVariable("idSimulacion") String idSimulacion, HttpServletResponse response)
throws IOException {
Properties properties = new Properties();
properties = Util.getProperties("mongo");
FileInputStream inputStream = null;
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=Hoja-Resultados-Descarga.xls");
try {
Simulacion simulacion = simulacionService.finById(idSimulacion);
inputStream = new FileInputStream(
properties.getProperty("ruta.copia.resultados.excel") + idSimulacion + ".xls");
int c;
while ((c = inputStream.read()) != -1) {
response.getWriter().write(c);
}
} catch (SimulacionException | IOException e) {
Util.autoLogError(e);
} finally {
if (inputStream != null)
inputStream.close();
response.getWriter().close();
}
}
结果 .xls 文件如下:
我将不胜感激一些帮助或建议,在此先感谢,这是我的第一个问题,如果我问得不正确,请原谅。
使用 getOutputStream
进行二进制输出,而不是文本输出 getWriter
:
Path path = Paths.get(properties.getProperty("ruta.copia.resultados.excel")
+ idSimulacion + ".xls");
Files.copy(path, response.getOutputStream());