码迷,mamicode.com
首页 > 编程语言 > 详细

【java类方法】下载Excel格式数据

时间:2021-03-31 12:24:47      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:on()   对象   生成文件   result   row   urlencode   点击下载   int   file   

页面点击下载查询数据库数据写入到SXSSFWorkbook(工作簿)中的`Sheet sheet = xswb.createSheet();`(工作表)

  1. 前端发送请求到servlet,把需要的参数传递到后台【我这里把response对象也封装到了(EiInfo inInfo)对象中】(此步骤省略...)

  2. 接收参数,通过jdbc的方法(jdbc连接数据库步骤省略...)查询数据库数据,`getMetaData()`直接操作数据库便捷,但效率可能较低

  3. 通过response对象获得输出流,将SXSSFWorkbook写入到浏览器

    	//jdbc方式保存到excel
    	public EiInfo downData(EiInfo inInfo) {
    		String sql = convertToSQL(date_PRC1, date_PRC2, type);
    		String sheetName = convertToSheetName(type);
    		HttpServletResponse response =(HttpServletResponse) inInfo.get("response");
    		SXSSFWorkbook xswb;
    		try {
    			// 创建xlsx
    			xswb = createXlsx(sql, sheetName);
    			
    			// 生成文件
    			response.setContentType("application/vnd.ms-excel");
    			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sheetName, "utf-8"));
    			OutputStream outputStream;
    			outputStream = response.getOutputStream();
    			xswb.write(outputStream);
    			outputStream.flush();
    			outputStream.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    			inInfo.set("status", false);
    			inInfo.set("msg", "导出失败!");
    			return inInfo;
    		}
    		return inInfo;
    	}
    

      

/*
* 传入sql语句,和需要的命名
* 返回工作簿对象
*/
private
SXSSFWorkbook createXlsx(String sql, String sheetName) throws Exception { SXSSFWorkbook xswb = null; Connection con = null; Statement st = null; ResultSet rs = null; try { con = JDBCUtils.getConnection(); st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); xswb = new SXSSFWorkbook(); // 创建工作表 Sheet sheet = xswb.createSheet(); xswb.setSheetName(0, sheetName); // 查询数据 rs = st.executeQuery(sql); System.out.println(rs); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // 创建表头 Row head = sheet.createRow(0); for (int i = 0; i < columnCount; i++) { Cell cell = head.createCell(i); cell.setCellValue(metaData.getColumnName(i + 1)); } // 获取总行数 rs.last(); int rowCount = rs.getRow(); rs.beforeFirst(); // 创建标题 for (int i = 1; i <= rowCount; i++) { rs.next(); Row row = sheet.createRow(i); for (int j = 0; j < columnCount; j++) { Cell cell = row.createCell(j); cell.setCellValue(rs.getString(j + 1)); } } } catch (Exception e) { throw new Exception(e); } finally { JDBCUtils.colseResource(con, st, rs); } return xswb; }

 

【java类方法】下载Excel格式数据

标签:on()   对象   生成文件   result   row   urlencode   点击下载   int   file   

原文地址:https://www.cnblogs.com/lwl-ong/p/14598785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!