错误详细信息
![](https://img-blog.csdnimg.cn/direct/dc6e557ee77f4aa2b7a1e3cc3b6fc879.png)
Controller层代码
@GET
@Path("/test2")
@Produces({"application/octet-stream"})
public Response fileDownload1(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
//文件夹不为空
List<Map<String, String>> list = RecordSetUtils.executeSql("select * from hrmresource");
SXSSFWorkbook workBook = getWorkBook(list);
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test1.xlsx", "UTF-8"));
writeBytes(workBook,response.getOutputStream());
return Response.status(Response.Status.OK).build();
}
关键代码:
public static void writeBytes(SXSSFWorkbook workbook, OutputStream os) {
InputStream fi = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] barray = bos.toByteArray();
fi = new ByteArrayInputStream(barray);
byte[] b = new byte[1024];
int length;
while ((length = fi.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fi != null) {
try {
fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public SXSSFWorkbook getWorkBook(List<Map<String,String>> list) throws IOException {
//创建工作目录
SXSSFWorkbook workbook = new SXSSFWorkbook();
//创建Sheet页
SXSSFSheet sheet = workbook.createSheet();
//解除Sheet页长度限制
sheet.setRandomAccessWindowSize(-1);
//迭代数据
Iterator<Map<String, String>> iterator = list.iterator();
//当前页
int currentRow = 0;
while (iterator.hasNext()){
//创建 行 (i 表示第几行)
SXSSFRow row = sheet.createRow(currentRow);
Map<String, String> map = null;
Map<String, String> head = list.get(0);
Set<String> set = head.keySet();
Iterator<String> key = set.iterator();
if(currentRow != 0 ){
map = iterator.next();
}
for (int i = 0; i < list.get(0).size() ; i++) {
SXSSFCell cell = row.createCell(i);
if(currentRow == 0 ){
cell.setCellValue(key.next());
}else{
//map = iterator.next();
cell.setCellValue(map.get(key.next()));
}
}
currentRow++;
}
return workbook;
}