记录一次导出excel代码:
html代码:
<button id="export_seal" class="u-btn-search2" onclick="exportSeal('{$T.param.menuCode}','{$T.param.menuName}');" >导出</button>
js:
var exportSeal=function () {
window.location.href = "${ctx}/oa/sealManage/exp.htm?locationCode="+$("select[name='locationCode']").val();
};
后台代码:
/**
* 管理员导出月报
*/
@RequestMapping(value = "/exp.htm")
public JSON exp(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
String locationCode = request.getParameter("locationCode");
HashMap map = new HashMap();
//判断是否是管理员
map.put("locationCode",locationCode);
List<SealManageView> list =this.baseService.expEle(map);
// 表头
String[] outColName = {"序号","印章名称","主要用途","印章授权审批人","保管部门","管理员","所在职场"};
String[] outCol = {"num","name","use","approver","department","manager","workplace"};
// 获得该类的所有属性的长度
Field[] colName = new Field[outCol.length];
for (Object obj : list) {
for (int i =0; i < outCol.length; i++) {
colName[i] = obj.getClass().getDeclaredField(outCol[i]);
}
}
// 创建一个excel文档
WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
// 设置响应方式
response.setContentType("application/vnd.ms-excel;charset=utf-8");
Calendar ca = Calendar.getInstance();
String names = null;
names = URLEncoder.encode(
"印章信息" + ca.get(Calendar.YEAR) + "-" + (ca.get(Calendar.MONTH) + 1) + "-"
+ ca.get(Calendar.DATE) + ".xls", "UTF-8");
response.addHeader("Content-Disposition",
"attachment;filename=" + names + ";"
+ "filename*=UTF-8''" + names);
// 创建sheet工作表
WritableSheet sheet = book.createSheet("印章信息", 0);
// 创建字体对象
WritableFont font = new WritableFont(WritableFont.createFont("宋体"), 15);
//标题
WritableCellFormat titleFormat = new WritableCellFormat();
titleFormat.setAlignment(Alignment.CENTRE);
titleFormat.setFont(font);
// 创建表头数据行格式化对象
WritableCellFormat format = new WritableCellFormat();
// 设置字体
format.setFont(font);
// 设置居中
format.setAlignment(Alignment.CENTRE);
//设置表头背景色
format.setBackground(Colour.GRAY_25);
// 设置自动换行
format.setWrap(true);
format.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
// 设置单元格格式
for (int i = 0; i < outColName.length; i++) {
Label lab = new Label(i, 0, outColName[i]);
lab.setCellFormat(format);
if(i==0){
sheet.setColumnView(i, 10);
}else if(i==2){
sheet.setColumnView(i, 50);
}else {
sheet.setColumnView(i, 30);
}
// 添加表头
sheet.addCell(lab);
}
// 添加表格体
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < colName.length; j++) {
colName[j].setAccessible(true);
String s = "";
s = colName[j].get(list.get(i)) != null ? colName[j].get(list.get(i)) + "" : "";
sheet.addCell(new Label(j, i + 1, s));
}
}
book.write();
book.close();
return ResultData.successToJson("导出成功!");
} catch (Exception e) {
e.printStackTrace();
}
return ResultData.failureToJson("导出失败!");
}