导出表到EXCEL
<button type="button" class="btn btn-primary" onclick="exportExcel()">导出</button>
function exportExcel(){
document.SearchMajor.action="exportExcelMajor.do";
document.SearchMajor.submit();
}//不能用Ajax传,ajax只能xml、json、html等格式
SearchMajor是form的name
转到对应Action
public String exportExcel() {
//先查询出List<object>
String orgnId=Constant.getOrgnId();
int endIndex = orgnId.indexOf("_");
//String orgn = orgnId.substring(0, endIndex);
String orgn = orgnId.substring(endIndex+1, orgnId.length());
int count = qwingsService.adminCountOrgn(organization,orgn);
if (count > 0) {
setPager_totalCount(count);
organizations = qwingsService.adminSearchOrgn(1,
count, organization,orgn);
}
//文件名称
fileName = System.currentTimeMillis() + ".xls";
//创建列名
String[] th = {"序号", "机构编号", "机构名称" };
// 创建一个HSSFWorkbook
HSSFWorkbook workBook = new HSSFWorkbook();
// 创建sheet0
HSSFSheet sheet = workBook.createSheet("sheet1");
// 第一行把表头列出
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < th.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(th[i]);
}
// 追加数据
for (int i = 0; i < organizations.size(); i++) {
HSSFRow nextRow = sheet.createRow(i + 1);
Organzation orgn1 = organizations.get(i);
sheet.setColumnWidth(2, 50 * 256);
// 序号
HSSFCell cell = nextRow.createCell(0);
cell.setCellValue(i + 1);
// 用户ID
cell = nextRow.createCell(1);
if (!TextUtils.isEmpty(orgn1.getId()))
cell.setCellValue(orgn1.getId());
// 用户名
cell = nextRow.createCell(2);
if (!TextUtils.isEmpty(orgn1.getName()))
cell.setCellValue(orgn1.getName());
}
try {
// 将工作簿输出 浏览器进行下载
//String filename = "样品交接记录.xls";
/*File file = new File(inputPath);
FileOutputStream os = FileUtils.openOutputStream(file);
workBook.write(os);
os.close();*/
//response.setContentType("application/vnd.ms-excel");另外一个方法
response.setContentType(ServletActionContext.getServletContext().getMimeType(fileName));
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(URLEncoder.encode(fileName, "utf-8").replace("+"," ")));
workBook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}