maven坐标如下:
org.apache.poi
poi-ooxml
3.9
OutputStream out = new FileOutputStream("E:/Members.xls");
则就保存在了本地 e 盘中。因为输出流是new出来的,和浏览器没有任何关系,那如果这一步的输出流来源和浏览器有关系不就有戏了吗?
response.getOutputStream();
然后response要告诉浏览器我这个响应是下载excel文件,所以需要设置一下,如下:
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");// 设置contentType为excel格式
response.setHeader("Content-Disposition", "Attachment;Filename="+ fileName+".xls");
其中的fileName是自己定义的,后面的完整代码中有东西。
workbook.write(fos);
其中workboo是操作excel的类,fos就是获取的输出流。这样就可以了。
@RequestMapping("info")
public void info(HttpServletRequest request, HttpServletResponse response){
Map map = new HashMap();
map.put("sequence", "0001");
map.put("date", "2018/01/04");
map.put("chetaihao", "1#");
map.put("productName", "产品名称");
map.put("specification", "规格");
map.put("memo", "备注");
map.put("inspectRecordBizList", "一个list");
HSSFWorkbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("测试表");
Row row = sheet.createRow(0);
int i = 0;
for(String key : map.keySet()){
Cell cell = row.createCell(i);
cell.setCellValue((String) map.get(key));
i++;
}
OutputStream fos = null;
try {
fos = response.getOutputStream();
String userAgent = request.getHeader("USER-AGENT");
String fileName = "test";
try {
if(StringUtils.contains(userAgent, "Mozilla")){
fileName = new String(fileName.getBytes(), "ISO8859-1");
}else {
fileName = URLEncoder.encode(fileName, "utf8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");// 设置contentType为excel格式
response.setHeader("Content-Disposition", "Attachment;Filename="+ fileName+".xls");
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}