我的用例是让我的应用程序从服务器下载excel(.xls)。 excel应该有图表。
这是它的服务器端代码
var objectArray = [{id_5:"100"},
{id_1:"300"},
{id_2:"500"},
{id_4:"700"},
{id_3:"200"}];
var normalArray = ["id_2","id_5","id_4"];
var newArray=objectArray.filter(function(item){
return normalArray.indexOf(Object.keys(item)[0]) == -1;
}).sort(function(a,b){
return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});
console.log(newArray);
打开excel时,我收到一条警告消息,提示“文件错误:数据可能已丢失”。而且,我无法在下载的Excel中看到图表。
我还检查过将内容类型设置为'OCTET-STREAM',但没有运气。
@RequestMapping(value="/downloadExcel", method=RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response) {
String fileName = "excel.xls";
response.setContentType("APPLICATION/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
try {
Files.copy(new File(fileName), (OutputStream)response.getOutputStream());
response.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
如何在不丢失数据的情况下传输Excel文件?
答案 0 :(得分:0)
我使用此代码,我可以下载带图形的excel文件
void copyFileToResponse(HttpServletResponse response, File file) throws IOException {
if(file != null) {
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
logger.debug("mimetype is not detectable, will take default");
mimeType = "application/octet-stream";
}
logger.debug("mimetype : {}", mimeType);
response.setContentType(mimeType);
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
response.setContentLength((int) file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}