在Java Web项目中,文件下载很常见的功能,通过点击一个连接,访问Controller,生成文件,进行下载
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<a type="button" class="btn btn-info"
href="<%=basePath %>car/download" target="_blank">热点区域分析</a>
@RequestMapping(value = "/download")
public String analysisHot(HttpServletResponse response ) {
// 创建HSSFWorkbook对象(excel的文档对象)
HSSFWorkbook wkb = new HSSFWorkbook();
// 建立新的sheet对象(excel的表单)
HSSFSheet sheet1 = wkb.createSheet("热点区域分析(上午)");
// 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
sheet1.setDefaultRowHeightInPoints(60);
sheet1.setDefaultColumnWidth(50);//设置缺省列宽
HSSFRow row1 = sheet1.createRow(0);
// 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
HSSFCell cell = row1.createCell(0);
// 设置单元格内容
cell.setCellValue("热点区域分析(上午)");
HSSFCellStyle style=wkb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cell.setCellStyle(style);
// 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
// 在sheet里创建第二行
HSSFRow row2 = sheet1.createRow(1);
// 创建单元格并设置单元格内容
row2.createCell(0).setCellValue("出发区域");
row2.createCell(1).setCellValue("car2go 使用量");
// 在sheet里创建其他行
List<Car> hot = new ArrayList<Car>(); //模拟, 自行查询数据
int i=2;
for (Car cto : hot) {
HSSFRow row3 = sheet1.createRow(i);
..... //写入文件
row3.createCell(0).setCellValue()
row3.createCell(1).setCellValue()
i++;
}
// 建立新的sheet对象(excel的表单)
HSSFSheet sheet2 = wkb.createSheet("热点区域分析(下午)");
// 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
sheet2.setDefaultRowHeightInPoints(60);
sheet2.setDefaultColumnWidth(50);// 设置缺省列宽
HSSFRow r1 = sheet2.createRow(0);
// 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
HSSFCell c = r1.createCell(0);
// 设置单元格内容
c.setCellValue("热点区域分析(下午)");
c.setCellStyle(style);
// 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet2.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
// 在sheet里创建第二行
HSSFRow r2 = sheet2.createRow(1);
// 创建单元格并设置单元格内容
r2.createCell(0).setCellValue("出发区域");
r2.createCell(1).setCellValue("car2go 使用量");
// 在sheet里创建其他行
List<Car> hot2 = new ArrayList<Car>(); //模拟, 自行查询数据
i = 2;
for (Car cto : hot2) {
HSSFRow row3 = sheet2.createRow(i);
row3.createCell(0).setCellValue(....);
row3.createCell(1).setCellValue(....);
i++;
}
// 输出Excel文件
java.io.OutputStream output;
try {
output = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition",
"attachment; filename=details.xls");
// response.setContentType("application/msexcel");
response.setContentType("application/octet-stream");
wkb.write(output);
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}