Java 导出数据到Excel

项目开发, Excel表的导出是很常见的功能需求,如下图所示,需要将table的数据导出到Excel,功能实现详解如下:
1、本人是Java SSM框架下进行数据导出,界面如下图:
Java 导出数据到Excel_第1张图片
2、jsp的js代码;

 function importExcel() {
	window.location.href="${ctx}/sellerFinancialSettle/getImportSellerFinancialSettlejsp.do";
 }

3、后端Controller代码:
注:导出所依赖的jar包:poi3.17.jar

//导出到Excel
@RequestMapping("/exportSellerFinancialSettlejsp")
public void exportExcel(Page page, HttpServletResponse response) throws IOException
{
		//查询出需要导出的数据
		List listorder = sysSellerFinMapper.selectExportList(page);
		if(listorder.size()>0)
		{
			//创建excel文件
	        HSSFWorkbook wb = new HSSFWorkbook();
	        //创建sheet页
	        HSSFSheet sheet = wb.createSheet("商家财务结算记录");
	        
	        //创建标题行
	        HSSFRow titleRow = sheet.createRow(0);
	        titleRow.createCell(0).setCellValue("商家名称");
	        titleRow.createCell(1).setCellValue("商家编号");
	        titleRow.createCell(2).setCellValue("所属市场");
	        titleRow.createCell(3).setCellValue("结算订单");
	        titleRow.createCell(4).setCellValue("结算时间范围");
	        titleRow.createCell(5).setCellValue("共几天");
	        titleRow.createCell(6).setCellValue("结算总金额");
	        titleRow.createCell(7).setCellValue("转账日期");
	        //遍历将数据放到excel列中  
	       for (SysSellerFinancialSettle order : listorder) {
		       HSSFRow dataRow =sheet.createRow(sheet.getLastRowNum()+1);
		       dataRow.createCell(0).setCellValue(order.getSellerMc());
			   dataRow.createCell(1).setCellValue(order.getSellerCode());
		       dataRow.createCell(2).setCellValue(order.getMarket());
		       dataRow.createCell(3).setCellValue(order.getTallyOrder());
		       dataRow.createCell(4).setCellValue(order.getSettleTime());
		       dataRow.createCell(5).setCellValue(order.getDays());
			   dataRow.createCell(6).setCellValue(order.getSettleMoney().toString());
		       dataRow.createCell(7).setCellValue(order.getTransferAccountsTime());
	        }
	        // 设置下载时客户端Excel的名称  
	        String filename =new SimpleDateFormat("yyyyMMdd").format(new Date()) + "-rewards.xls"; 
	         //设置下载的文件
	        response.setCharacterEncoding("UTF-8");
	        response.setContentType("application/vnd.ms-excel");  
	        response.setHeader("Content-disposition", "attachment;filename=" + filename);  
	        OutputStream ouputStream = response.getOutputStream();//打开流
	        wb.write(ouputStream); //在excel内写入流 
	        ouputStream.flush();// 刷新流  
	        ouputStream.close();// 关闭流
	    }
}

导出的数据如下图:
Java 导出数据到Excel_第2张图片

你可能感兴趣的:(Java 导出数据到Excel)