页面:
表格下载:
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response, HttpSession session)
throws Exception {
ArrayList listTitle = new ArrayList();
listTitle.add("a");
listTitle.add("b");
listTitle.add("c");
listTitle.add("d");
listTitle.add("e");
// 创建表格及其第一行标题栏
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet1");
HSSFRow row0 = sheet.createRow(0);
for (int j = 0; j < 5; j++) {// 5列
HSSFCell cell = row0.createCell((short) j);
cell.setCellValue(listTitle.get(j).toString());
}
String maker = SystemUtil.getCureenUser(session);
List list = transportService.getlist(maker);
System.out.println(list.size());
// 从第二行输入
for (int i = 1; i <= list.size(); i++) { // 几行
HSSFRow row = sheet.createRow(i);
HSSFCell cell0 = row.createCell((short) 0);// 第n+1个
cell0.setCellValue(list.get(i - 1).getId().toString());
HSSFCell cell1 = row.createCell((short) 1);
cell1.setCellValue(list.get(i - 1).getContainerid().toString());
HSSFCell cell2 = row.createCell((short) 2);
cell2.setCellValue(list.get(i - 1).getIsocode().toString());
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
// 设置response参数,可以打开下载页面
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(("box" + ".xls").getBytes(), "iso-8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}