public String down(HttpServletRequest request, HttpServletResponse response){
byte[] data;
List<Object> list = new ArrayList<Object>();
try {
data = excel(list);
String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String filename = formatDate + ".xls";
download(request, response, data, filename);
} catch (Exception e) {
e.printStackTrace();
return "saleru/DownError";
}
return "";
}
private byte[] excel(List<Object> list) throws RowsExceededException, WriteException, IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建excel文件
WritableWorkbook book = null;
book = Workbook.createWorkbook(out);
// 生成表名为sheel的第一页
WritableSheet sheet = book.createSheet("sheel", 0);
// 字体格式化
WritableFont wf = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.BOLD, false);
jxl.format.CellFormat cf = new WritableCellFormat(wf);
// 设置列宽
sheet.setColumnView(0, 15);// 金额
sheet.setColumnView(1, 15);// 方式(1-额度代付,2-普通代付)
sheet.setColumnView(2, 35);// 账户名
sheet.setColumnView(3, 15);// 账户号
sheet.setColumnView(4, 15);// 银行名称
sheet.setColumnView(5, 15);// 银行联行号
sheet.setColumnView(6, 15);// 备注
sheet.setColumnView(7, 30);// 类型
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)以及单元格内容为""
// 将定义好的Label单元格添加到工作表中
sheet.addCell(new Label(0, 0, "金额(元)", cf));
sheet.addCell(new Label(1, 0, "方式(1-额度代付,2-普通代付)", cf));
sheet.addCell(new Label(2, 0, "账户名", cf));
sheet.addCell(new Label(3, 0, "账户号", cf));
sheet.addCell(new Label(4, 0, "银行名称 ", cf));
sheet.addCell(new Label(5, 0, "银行联行号", cf));
sheet.addCell(new Label(6, 0, "备注(商户结算款)", cf));
sheet.addCell(new Label(7, 0, "类型(1-对公 2-对私)", cf));
sheet.addCell(new Label(0, 1,"100"));
sheet.addCell(new Label(1, 1,"1"));
sheet.addCell(new Label(2, 1,"张三"));
sheet.addCell(new Label(3, 1,"6228480055555555555"));
sheet.addCell(new Label(4, 1,"中国工商银行"));
sheet.addCell(new Label(5, 1,"102308809010"));
sheet.addCell(new Label(6, 1,"商户结算款"));
sheet.addCell(new Label(7, 1,"2"));
book.write();
book.close();
return out.toByteArray();
}
private void download(HttpServletRequest request, HttpServletResponse response, byte[] context, String filename)
throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("file");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setHeader("Content-Length", context.length + "");
BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(context));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}