Java导出数据生成Excel表格

时间:2022-01-01 00:19:55

事先准备:

工具类:

Java导出数据生成Excel表格

package com.wazn.learn.util.export;

import java.sql.Connection;
import java.sql.DriverManager; public class DbUtil {
private String dbUrl="jdbc:mysql://localhost:3306/basepro";
private String dbUserName="user";
private String dbPassword="user";
private String jdbcName = "com.mysql.jdbc.Driver"; public Connection getCon() throws Exception {
Class.forName(jdbcName);
Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
return con;
} public void closeCon(Connection con) throws Exception {
if (con != null) {
con.close();
}
}
}
package com.wazn.learn.util.export;

import java.sql.ResultSet;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; public class ExcelUtil {
public static void fillExcelData(ResultSet rs, Workbook wb, String[] headers) throws Exception {
int rowIndex = 0; //定义行的初始值
Sheet sheet = wb.createSheet(); //创建sheet页
Row row = sheet.createRow(rowIndex++); //行数自增+1
//将头信息填进单元格
for (int i = 0; i < headers.length; i++) {
row.createCell(i).setCellValue(headers[i]);
} while (rs.next()) {
row = sheet.createRow(rowIndex++); //增加行数
System.out.println(row);
for (int i = 0; i < headers.length; i++) { // 添加内容
row.createCell(i).setCellValue(rs.getObject(i + 1).toString());
}
}
}
}
package com.wazn.learn.util.export;

import java.io.OutputStream;
import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Workbook; public class ResponseUtil {
public static void write(HttpServletResponse response, Object o) throws Exception {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(o.toString());
out.flush();
out.close();
} public static void export(HttpServletResponse response, Workbook wb, String fileName) throws Exception{
//设置头 固定格式
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1")); response.setContentType("text/html;charset=utf-8"); OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
} }

Controller层:

package com.wazn.learn.controller.teachclass;

import java.sql.Connection;
import java.sql.ResultSet; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.wazn.learn.dao.impl.ExportDao;
import com.wazn.learn.util.export.DbUtil;
import com.wazn.learn.util.export.ExcelUtil;
import com.wazn.learn.util.export.ResponseUtil;
import com.wordnik.swagger.annotations.ApiOperation; @Controller
@Scope("prototype")
@RequestMapping("/teach")
public class ExportController {
ExportDao exportDao;
ExcelUtil excelUtil; @GetMapping("/page")
public String stulook() {
return "teach/course/export";
}
@SuppressWarnings("static-access")
@ApiOperation(value = "导出Excel")
@RequiresPermissions("upms:system:export")
@RequestMapping(value = "/export", method = RequestMethod.GET)
@ResponseBody
public String export(HttpServletResponse response,String sdate,String edate) throws Exception {
ExportDao exportDao = new ExportDao();
DbUtil dbUtil = new DbUtil();
Connection con = null;
ExcelUtil excelUtil = new ExcelUtil();
try {
con = dbUtil.getCon();
Workbook wb = new HSSFWorkbook();
String headers[] = {"编号","学号","签到时间", "签到日期", "用户名","所属公司","职业"}; ResultSet rs = exportDao.exportSign(con,sdate,edate);
excelUtil.fillExcelData(rs, wb, headers);
ResponseUtil.export( response, wb, "签到管理.xls");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null; }
@SuppressWarnings("static-access")
@ApiOperation(value = "导出Excel")
@RequiresPermissions("upms:system:export")
@RequestMapping(value = "/export2", method = RequestMethod.GET)
@ResponseBody
public String export2(HttpServletResponse response) throws Exception {
ExportDao exportDao = new ExportDao();
DbUtil dbUtil = new DbUtil();
Connection con = null;
ExcelUtil excelUtil = new ExcelUtil();
try {
con = dbUtil.getCon();
Workbook wb = new HSSFWorkbook();
String headers[] = { "签到日期","签到人数","请假人数"}; ResultSet rs = exportDao.exportSign2(con);
excelUtil.fillExcelData(rs, wb, headers);
ResponseUtil.export( response, wb, "签到综合.xls");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null; } }

dao层:

package com.wazn.learn.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; public class ExportDao {
public ResultSet exportSign(Connection con, String sdate, String edate) throws Exception{ String sql="select s.id,u.stunum, FROM_UNIXTIME(s.signtime/1000),s.signdate,u.nickname,u.company,u.job from teach_sign s join sys_user u on s.user_id=u.id ";
if(sdate!=null&&sdate!=""){
if(edate!=null&&edate!=""){
sql+=" where s.signdate>='"+sdate+"' and s.signdate<='"+edate+"' ";
}else{
sql+=" where s.signdate>='"+sdate+"' ";
}
}else{
if(edate!=null&&edate!=""){
sql+=" where s.signdate<='"+edate+"' ";
}else{ }
}
StringBuffer sb = new StringBuffer(sql);
PreparedStatement pstmt = con.prepareStatement(sb.toString());
return pstmt.executeQuery();
} public ResultSet exportSign2(Connection con) throws Exception{ String sql="select signdate as signdate, count(distinct user_id)-count(leave1) as countuser,count(leave1) as countleave from teach_signs group by signdate";
StringBuffer sb = new StringBuffer(sql);
PreparedStatement pstmt = con.prepareStatement(sb.toString());
return pstmt.executeQuery();
}
}

前台页面:

两个不同的,传参数根据日期和不传参数

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page
import="org.springframework.security.core.context.SecurityContextHolder"%>
<%@ page import="com.wazn.learn.configure.security.CustomerUser"%>
<%
String basePath = request.getContextPath();
CustomerUser user = (CustomerUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>选择导出日期</title>
<script type="text/javascript"
src="<%=basePath%>/res/js/jquery-1.12.4.min.js"></script>
<script src="<%=basePath%>/res/layui/layui.js" charset="utf-8"></script>
<link rel="stylesheet" href="<%=basePath%>/res/layui/css/layui.css"
media="all">
</head>
<style type="text/css"> </style>
<body class="gray-bg">
<div class="layui-form-item " >
<label class="layui-form-label">开始日期:</label>
<div class="layui-input-block">
<input type="text" class="layui-input" placeholder="请选择开始时间" id="sdate1" name="sdate1">
</div>
</div>
<div class="layui-form-item" >
<label class="layui-form-label">结束日期:</label>
<div class="layui-input-block">
<input type="text" class="layui-input" placeholder="请选择截止时间" id="edate1" name="edate1">
</div>
</div>
<div class="layui-input-block">
<a class="waves-effect waves-button" href="javascript:;" onclick="exportAction()"><button class="layui-btn" style="transform: translateY(-3px);"
data-type="reload">导出签到表格</button></a> </div>
<script>
//导出Excel文件
function exportAction(){
var s = $('#sdate1').val();
var e = $('#edate1').val();
var str="sdate='"+s+"'&&edate='"+e+"'";
window.open("<%=basePath%>/teach/export?sdate="+s+"&&edate="+e+" ");
}
layui.use(['table','form','laydate'], function(){
var table = layui.table,
form = layui.form,
laydate = layui.laydate;;
laydate.render({
elem: '#sdate1',
type: 'date'
});
laydate.render({
elem: '#edate1',
type: 'date'
});
}); </script>
</body> </html>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="org.springframework.security.core.context.SecurityContextHolder"%>
<%@ page import="com.wazn.learn.configure.security.CustomerUser"%>
<%
String basePath = request.getContextPath();
CustomerUser user = (CustomerUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript" src="<%=basePath%>/res/js/jquery-1.12.4.min.js"></script>
<script src="<%=basePath%>/res/layui/layui.js" charset="utf-8"></script>
<link rel="stylesheet" href="<%=basePath%>/res/layui/css/layui.css" media="all"> <title>数据报表</title>
</head>
<body> <div style="margin: 0px; background-color: white; margin: 0 10px;">
<blockquote class="layui-elem-quote" style="height: 45px"> <div class="layui-col-md2">
<a class="waves-effect waves-button" href="javascript:;" onclick="exportAction()"><button class="layui-btn" style="transform: translateY(-3px);"
data-type="reload">导出签到表格</button></a>
</div> </blockquote>
</div> <table class="layui-table"
lay-data="{url:'<%=basePath%>/teach/course/getsignreport', page:true, id:'idTest', limit: 10,limits: [10,20,30]}"
lay-filter="demo">
<thead>
<tr>
<th lay-data="{field:'signdate', width:'30%',align:'center', sort: true}">签到日期</th>
<th lay-data="{field:'user', width:'30%',align:'center',toolbar: '#bar1'}">签到人数</th>
<th lay-data="{field:'leave', width:'30%',align:'center' ,toolbar: '#bar2'}">请假人数</th> </tr>
</thead>
</table>
<script>
//导出Excel文件
function exportAction(){
window.open("<%=basePath%>/teach/export2");
}
</script>
<script type="text/html" id="bar1">
<a class="layui-btn layui-btn-primary layui-btn-xs" id="test" lay-event="sign">{{d.countuser}}</a>
</script>
<script type="text/html" id="bar2">
<a class="layui-btn layui-btn-primary layui-btn-xs" id="test" lay-event="leave">{{d.countleave}}</a>
</script>
<script>
layui.use(['table','form','laydate','layer'], function(){
var table = layui.table,
form = layui.form,
layer=layui.layer, laydate = layui.laydate;; laydate.render({
elem: '#edate',
type: 'datetime'
});
laydate.render({
elem: '#sdate',
type: 'datetime'
});
laydate.render({
elem: '#sdate1',
type: 'date'
});
laydate.render({
elem: '#edate1',
type: 'date'
}); //监听工具条
table.on('tool(demo)', function(obj){
var data = obj.data;
if(obj.event === 'sign'){
layer.open({
title : "签到详情",
type : 2,
area: ['70%', '80%'],
content : "<%=basePath%>/teach/course/signlook?leave=0&date="+data.signdate,
})
}else if(obj.event==='leave'){
layer.open({
title : "请假详情",
type : 2,
area: ['80%', '80%'],
content : "<%=basePath%>/teach/course/signlook?leave=1&date="+data.signdate,
})
}
}); var $ = layui.$, active = {
reload: function(){ var demoReload = $('#demoReload'); //执行重载
table.reload('idTest', {
page: {
curr: 1 //重新从第 1 页开始
},
where: {
name: demoReload.val(),
sdate:$('#sdate').val(),
edate:$('#edate').val()
}
});
}
}; $('.demoTable .layui-btn').on('click', function(){
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
}); });
</script> </body>
</html>

Java导出数据生成Excel表格的更多相关文章

  1. Java操作Jxl实现导出数据生成Excel表格数据文件

    实现:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js.Css文件.页面:Jsp.拦截请求:Servlet.逻辑处理:ClassBean.数据库:SQLserver. 注意: ...

  2. 导出数据到Excel表格

    开发工具与关键技术:Visual Studio 和 ASP.NET.MVC,作者:陈鸿鹏撰写时间:2019年5月25日123下面是我们来学习的导出数据到Excel表格的总结首先在视图层写导出数据的点击 ...

  3. Python导出数据到Excel表格-NotImplementedError&colon; formatting&lowbar;info&equals;True not yet implemented

    在使用Python写入数据到Excel表格中时出现报错信息记录:“NotImplementedError: formatting_info=True not yet implemented” 报错分析 ...

  4. Java使用poi从数据库读取数据生成Excel表格

    想要使用POI操作以xsl结尾的Excel,首先要下载poi相关的jar包,用到的jar有: poi-3.9.jar poi-ooxml-3.9.jar poi-ooxml-schemas-3.9.j ...

  5. 数据库数据生成Excel表格(多用在导出数据)

    最近在项目开发中遇到这样一个需求,用户聊天模块产品要求记录用户聊天信息,但只保存当天的,每天都要刷新清空数据,但聊天记录要以Excel的形式打印出来,于是就引出了将数据库的数据导出成Excel表格的需 ...

  6. Java 利用poi生成excel表格

    所需jar包,如下所示 写一个excel工具类 ExcelUtils .java import java.lang.reflect.Field; import java.util.Iterator; ...

  7. php动态导出数据成Excel表格

    一.封装 Excel 导出类 include/components/ExecExcel.php <?php /*** * @Excel 导入导出类. */ class ExecExcel { / ...

  8. spring boot 使用POI导出数据到Excel表格

    在spring boot 的项目经常碰到将数据导出到Excel表格的需求,而POI技术则对于java操作Excel表格提供了API,POI中对于多种类型的文档都提供了操作的接口,但是其对于Excel表 ...

  9. Java导出数据为EXCEL的两种方式JXL和POI

    JXL和POI导出数据方式的比较 POI支持excel2003和2007,而jxl只支持excel2003. 下面为测试代码: public class TestCondition { /** * 生 ...

随机推荐

  1. 判断Activity是否正在退出 isFinishing&lpar;&rpar;

    boolean android.app.Activity.isFinishing()           Added in API level 1 Check to see whether this ...

  2. 安装vim的ycm

    环境centos 6.7 vim 7.3 安装vundle Vundle(Vim bundle)是一个Vim的插件管理器.它是把git操作整合进去,用户需要做的只是去GitHub上找到自己想要的插件的 ...

  3. SQL里面如何取得前N条数据?

    select * from table order by id limit 10 运用limit可以获取前N个数据

  4. 山东省第四届ACM省赛

    排名:http://acm.sdut.edu.cn/sd2012/2013.htm 解题报告:http://www.tuicool.com/articles/FnEZJb A.Rescue The P ...

  5. android开发 解决启动页空白或黑屏问题

    遇到的情况: app启动时进入启动页时出现白屏页,然后大概一秒之后就出现了背景图片. 原因:app启动时加载的是windows背景,之后再加载布局文件的,所以开始的黑屏/白屏就是windows的背景颜 ...

  6. LoadRunner error -27498

    URL=http://172.18.20.70:7001/workflow/bjtel/leasedline/ querystat/ subOrderQuery.do错误分析:这种错误常常是因为并发压 ...

  7. jq 选项卡

    <!doctype html> <html> <head> <meta charset="utf-8"> <style> ...

  8. WordPress BuddyPress Extended Friendship Request插件跨站脚本漏洞

    漏洞名称: WordPress BuddyPress Extended Friendship Request插件跨站脚本漏洞 CNNVD编号: CNNVD-201307-609 发布时间: 2013- ...

  9. DB层级

    最上层:              业务层 负载均衡:            LVS 代理层:           DB-PROXY DB层:            DB主库   DB从库 随着DB出 ...

  10. Spring入门介绍-AOP&lpar;三&rpar;

    AOP的概念 AOP是面向切面编程的缩写,它是一种编程的新思想.对我们经常提起的oop(面对对象编程)有一定的联系. AOP和OOP的关系 AOP可以说是oop的某一方便的补充,oop侧重于对静态的属 ...