从浏览器导出excel表单

这篇博客介绍了如何在网页中通过点击按钮实现Excel数据的导出。使用JavaScript的onclick事件触发导出,调用后台Java方法`exportExcel()`。该方法首先根据条件查询数据,然后创建并填充HSSFWorkbook对象,包括设置列名和具体数据。最后,将工作簿写入HTTP响应,以供浏览器下载。导出过程中涉及了文件名设定、列宽调整和UTF-8编码处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导出表到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;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值