您的位置:首页 > Web前端 > JavaScript

jsp创建excel文件 ,并指定下载路径

2015-12-07 09:56 337 查看
//下载excel文件
@RequestMapping(value="loadExcel.do",method=RequestMethod.GET)
public void loadTxt(HttpServletRequest request,HttpServletResponse response){
List<Domain> xls = new ArrayList<Domain>();
Domain d1 = new Domain();
Domain d2 = new Domain();
d1.setDomain("***");
d1.setDomain_type("***");
xls.add(d1);
d2.setDomain("***");
d2.setDomain_type("***");
xls.add(d2);

int n = 1 ;
// 获取总列数
int CountColumnNum = 2;
// 创建Excel文档
HSSFWorkbook hwb = new HSSFWorkbook();
Domain domain = null;
// sheet 对应一个工作页
HSSFSheet sheet = hwb.createSheet("js3");
HSSFRow firstrow = sheet.createRow(0); // 下标为0的行开始
HSSFCell[] firstcell = new HSSFCell[CountColumnNum];
String[] names = new String[CountColumnNum];
names[0] = "**";
names[1] = "**";

for (int j = 0; j < CountColumnNum; j++) {
firstcell[j] = firstrow.createCell(j);
firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
}
for (int i = 0; i < xls.size(); i++) {
// 创建一行
HSSFRow row = sheet.createRow(i + 1);
// 得到要插入的每一条记录
domain = xls.get(i);
for (int colu = 0; colu <= 4; colu++) {
// 在一行内循环
HSSFCell xh = row.createCell(0);
xh.setCellValue(domain.getDomain());
HSSFCell xm = row.createCell(1);
xm.setCellValue(domain.getDomain_type());
}
}
// 创建文件输出流,准备输出电子表格
String excel_name = "**.xls";
OutputStream out = null;

response.setContentType("application/x-download");
response.setHeader("content-disposition", "attachment; filename="+excel_name);
response.setHeader("Content-type", "charset=UTF-8");
response.setContentType("");
try {
out=response.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
hwb.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: