ExportExcel.java类
package com.pro.lottery.action;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import com.pro.lottery.dao.DataSourceFactory;
import com.pro.lottery.modle.ReqLottery;
/**
*
* @author Caixu
*
*/
public class ExportExcel extends BaseAction {
/**
*
*/
private static final long serialVersionUID = -3297347144890990614L;
public static double totalCount = 0; //总共有多少条数据
public static double execCount = 0; //已经处理的数据
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param fieldName
* [] 导出到excel文件里的表头名
* @param columnIt
* [] 导出到excel文件里的表头NAME
* @param sheetName
* 工作表的名称
* @param sheetSize
* 每个sheet中数据的行数,此数值必须小于65536
* @param output
* java输出流
*/
public static boolean exportExcel(List<?> list, String[] fieldName,
Object[] columnIt, String sheetName, int sheetSize,
OutputStream output) {
HSSFWorkbook workbook = new HSSFWorkbook();// 产生工作薄对象
if (sheetSize >= 65536) {
sheetSize = 65536;
}
double sheetNo = Math.ceil(list.size() / sheetSize);
for (int index = 0; index <= sheetNo; index++) {
HSSFSheet sheet = workbook.createSheet();// 产生工作表对象
workbook.setSheetName(index, sheetName+index);//设置工作表的名称.
HSSFRow row = sheet.createRow(0);// 产生一行
HSSFCell cell;// 产生单元格
//表头样式
HSSFCellStyle headerStyle = (HSSFCellStyle) workbook .createCellStyle();// 创建标题样式
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //设置垂直居中
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置水平居中
HSSFFont headerFont = (HSSFFont) workbook.createFont(); //创建字体样式
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
headerFont.setFontName("Times New Roman"); //设置字体类型
headerFont.setFontHeightInPoints((short) 10); //设置字体大小
headerStyle.setFont(headerFont); //为标题样式设置字体样式
headerStyle.setFillBackgroundColor((short) 2);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
headerStyle.setWrapText(true); // 设置为自动换行
headerStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置背景色
headerStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置前景色
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//表body样式
HSSFCellStyle cellStyle = (HSSFCellStyle) workbook .createCellStyle();
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //设置垂直居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置水平居中
cellStyle.setWrapText(true); // 设置为自动换行
// 写入各个字段的名称
for (int i = 0; i < fieldName.length; i++) {
cell = row.createCell(i); // 创建第一行各个字段名称的单元格
row.setHeight((short) 450);
cell.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置单元格内容为字符串型
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// //为了能在单元格中输入中文,设置字符集为UTF_16
cell.setCellValue(fieldName[i]); // 给单元格内容赋值
cell.setCellStyle(headerStyle);
}
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size());
// 写入各条记录,每条记录对应excel表中的一行
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 - startNo);
row.setHeight((short) 350);
sheet.setColumnWidth(i, 4500);
HashMap map = (HashMap) list.get(i);
for (int j = 0; j < columnIt.length; j++) {
cell = row.createCell(j);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(cellStyle);
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
Object value = map.get(columnIt[j]);
if (value != null) {
cell.setCellValue(map.get(columnIt[j]).toString());
} else
cell.setCellValue("");
}
execCount = execCount + 1;
}
}
try {
//为了让百分比不显示100%
execCount = execCount - (totalCount * 0.02);
workbook.write(output);
execCount = execCount + (totalCount * 0.02);
output.flush();
output.close();
return true;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Output is closed ");
System.out.println("清除了。。。。。。。。。。。");
execCount = 0;
return false;
}
}
public String exportExcelAction(){
HttpServletResponse response = this.getResponse();
HttpServletRequest request = this.getRequest();
response.setCharacterEncoding("utf-8");
String fileName = request.getParameter("fileName");
// 初始化数据
/* List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
for (int i = 0; i < 53333; i++) {
Map<Object,Object> map = new HashMap<Object,Object>();
map.put("id", i);
map.put("name", "姓名" + i);
map.put("age", 20+ i);
list.add(map);
} */
long count = DataSourceFactory.getInstance().findCount("select count(1) from lotteryInfo where 1=1 ");
List<ReqLottery> lotterInfo = DataSourceFactory.getInstance().getObjListByProcedure(ReqLottery.class, "PUBLIC_FINDVIEWPAGE_FIND", new Object[]{"lotteryInfo",
"1", String.valueOf(count), "lotteryissue", "*", "0", "1", "1=1 " });
List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
for (ReqLottery lottery : lotterInfo) {
Map<Object,Object> map = new HashMap<Object,Object>();
if(lottery.getLotteryId() == 1001){
map.put("lotteryId", "重庆时时彩");
}else{
map.put("lotteryId", "江西时时彩");
}
map.put("lotteryNum", lottery.getLotteryNum());
map.put("lotteryIssue", lottery.getLotteryIssue());
String str = df.format(lottery.getLotteryDate());
map.put("lotteryDateStr", str);
map.put("lotteryType1", lottery.getLotteryType1());
map.put("lotteryType2", lottery.getLotteryType2());
map.put("lotteryType3", lottery.getLotteryType3());
list.add(map);
}
totalCount = list.size();
String[] alias = { "彩种类型", "开奖号码", "期号", "日期", "前三", "中三", "后三" };// excel的列头
String[] names = { "lotteryId", "lotteryNum", "lotteryIssue", "lotteryDateStr", "lotteryType1", "lotteryType2", "lotteryType3" };// 数据List中的Map的key值.
/* String[] alias = { "编号", "姓名", "年龄" };// excel的列头
String[] names = { "id", "name", "age"};*/
OutputStream os = null;
try {
os = response.getOutputStream();
//FileOutputStream out = null;
// out = new FileOutputStream("C:\\Work\\e.xls");
//设置对话框
response.setHeader("Content-disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1"));
//设置 MIME(Excel)
response.setContentType("application/vnd.ms-excel");
//设置编码
response.setCharacterEncoding("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
exportExcel(list, alias, names, "学生信息表", 60000, os);
System.out.println("成功");
return null;
}
/**
* 得到进度条的百分比
* @return
* @throws IOException
*/
public String getProgressVal() throws IOException{
HttpServletResponse response = this.getResponse();
HttpServletRequest request = this.getRequest();
response.setCharacterEncoding("utf-8");
PrintWriter out = getResponse().getWriter();
//第一次请求将已经处理的条数清0
System.out.println("execCount:"+execCount+" totalCount:"+totalCount);
if(execCount == 0){
out.print(0.01);
return null;
}
try {
double val = (execCount / totalCount) * 100;
//DecimalFormat df = new DecimalFormat("#.00");
//System.out.println("valule:"+df.format(val));
if(val >= 100){
System.out.println("val >= 100清除了。。。。。。。。。。。");
execCount = 0;
}
if(execCount >= totalCount){
System.out.println("execCount >= totalCount 清除了。。。。。。。。。。。");
execCount = 0;
}
out.print(val);
return null;
} catch (Exception e) {
e.printStackTrace();
execCount = 0;
out.print(0);
return null;
}finally{
out.flush();
out.close();
}
}
public static void main(String[] args) {
// 初始化数据
List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
for (int i = 0; i < 65536; i++) {
Map<Object,Object> map = new HashMap<Object,Object>();
map.put("id", i);
map.put("name", "姓名" + i);
map.put("age", 20+ i);
list.add(map);
}
String[] alias = { "编号", "姓名", "年龄" };// excel的列头
String[] names = { "id", "name", "age" };// 数据List中的Map的key值.
FileOutputStream out = null;
try {
out = new FileOutputStream("C:\\Work\\e.xls");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
exportExcel(list, alias, names, "学生信息表", 60000, out);
System.out.println("----执行完毕----------");
}
}
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="/Lottery/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="/Lottery/easyui/themes/icon.css">
<style type="text/css">
* {
font-size: 12px;
a {
text-decoration: none;
}
body {
margin: 0px;
padding: 0px;
height: 100%;
}
#fm {
margin: 0;
padding: 10px 30px;
}
.ftitle {
font-size: 14px;
font-weight: bold;
color: #666;
padding: 5px 0;
margin-bottom: 10px;
border-bottom: 1px solid #ccc;
}
.fitem select{
width:150px;
}
.fitem input{
width:150px;
}
.fitem label {
display: inline-block;
width: 160px;
text-align: right;
}
#searchbox {
clear:both;
padding-left:20px;
padding-bottom: 5px;
}
</style>
</head>
<script type="text/javascript" src="/Lottery/js/jquery-1.6.min.js"></script>
<script type="text/javascript" src="/Lottery/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/Lottery/easyui/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="/Lottery/js/My97DatePicker/calendar.js"></script>
<script type="text/javascript" src="/Lottery/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="/Lottery/js/mask.js"></script>
<script type="text/javascript">
$(function(){
$('#datagrid').datagrid({
url : '<%=path%>/lottery/viewLottery_findLotteryInfo.action',
title:'开奖信息',//表格标题
iconCls:'icon-search',//表格图标
nowrap: false,//是否只显示一行,即文本过多是否省略部分。
striped: true,
sortName: 'createTime',
sortOrder: 'desc',
idField:'terminalID',
loadMsg:'拼命加载中 请稍后...',
fitColumns:true,
fit:true,
pagination:true, //包含分页
toolbar : '#tab-tools',//工具栏
frozenColumns : [[
{checkbox:true},
{
field : 'lotteryId',
title : '彩种类型',
width : 150,
align : 'center',
formatter:function(v,d,i){
switch (parseInt(v)) {
case 1001:
return '重庆时时彩';
case 1002:
return '江西时时彩';
default:
return '未定义';
}
}
}, {
field : 'lotteryIssue',
title : '期号',
width : 150,
align : 'center'
}, {
field : 'lotteryNum',
title : '开奖号码',
width : 120,
align : 'center'
}
]],
columns : [[
{
field : 'lotteryDateStr',
title : '开奖时间',
width : 150,
align : 'center'
}, {
field : 'lotteryType1',
title : '前三形态',
width : 100,
align : 'center'
}, {
field : 'lotteryType2',
title : '中三形态',
width : 100,
align : 'center'
}, {
field : 'lotteryType3',
title : '后三形态',
width : 100,
align : 'center'
}
]],//单选
onCheck:function(rowIndex,row){
//if(row.auditState == 1002){
//取消选择
// $('#datagrid').datagrid('unselectRow',rowIndex).datagrid('uncheckRow',rowIndex);
//}
},
onClickRow:function(rowIndex,row){
//if(row.auditState == 1002){
//取消选择
// $('#datagrid').datagrid('unselectRow',rowIndex).datagrid('uncheckRow',rowIndex);
//}
},
//全选
onCheckAll:function(rows){
//判断能不能选中
//for(var i=0;i<rows.length;i++){
//var row = rows[i];
//if(row.auditState == 1002){
//取消选择
// var rowIndex = $('#datagrid').datagrid('getRowIndex',row);
// $('#datagrid').datagrid('unselectRow',rowIndex).datagrid('uncheckRow',rowIndex);
//}
//}
},
pagination:true, //包含分页
pageList: [10,20,30,50],//可以设置每页记录条数的列表
rownumbers:true,
singleSelect:false,
toolbar:[
{
text:'添加开奖信息',
iconCls:'icon-add',
handler:function(){
$('#dlg').dialog('open').dialog('setTitle','添加收货地址');
$('#fm').form('clear');
submitType="add";
}
},'-',
{
text:'修改开奖信息',
iconCls:'icon-edit',
handler:function(){
var row = $('#datagrid').datagrid('getSelected');
if (row){
submitType="update";
$('#dlg').dialog('open').dialog('setTitle','修改收货地址');
$('#fm').form('load',row);
}else{
$.messager.alert('提示信息','请选选择一个进行修改!','info');
}
}
}
],onLoadSuccess:function(data){
if(data.result == "error"){
$.messager.show({title:'提示信息',msg:data.errorMsg,timeout:3000});
}
},onLoadError:function(data){
$.messager.alert('提示信息','请求服务器失败!');
}
});
$('#datagrid').datagrid('getPager').pagination({
pageSize: 10,//每页显示的记录条数,默认为10
pageList: [10,20,30,50],//可以设置每页记录条数的列表
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录'
});
$(".datagrid-toolbar").append($("#searchbox"));
$(".search_btn").click(function(){
$('#datagrid').datagrid('load',{
lotteryId: $("#lotteryId").val(),
lotterydate: $("#lotterydate").val(),
lotteryIssue:$("#lotteryIssue").val()
});
});
//导出报表
var clearInterval;
$(".print_btn").click(function(){
window.location.href="<%=path%>/lottery/expExcel_exportExcelAction.action?fileName=Student.xls";
$('#p').progressbar('setValue', 0);
$(document).mask('正在导出报表...');
$('#p').css({"display":"block"});
//value += Math.floor(Math.random() * 10);
//$('#p').progressbar('setValue', value);
clearInterval = setInterval(reqProgressVal, 200);
})
});
//得到进度条百分
function reqProgressVal(){
var value = $('#p').progressbar('getValue');
if(value == 100){
clearInterval(clearInterval);
$(document).unmask();
$('#p').css({"display":"none"});
return;
}
$.ajax({
type : "post", // 以post方式与后台沟通
url : '<%=path%>/lottery/expExcel_getProgressVal.action',
dataType : "json",
async : false,
data: {},
success : function(data) {
$('#p').progressbar('setValue', data.toFixed(2));
},
error : function() {
alert("请求服务器失败");
}
});
}
</script>
<body class="ContentBody">
<!-- 进度条 -->
<div id="p" class="easyui-progressbar" style="width:400px; display:none"></div>
<table id="datagrid"></table>
<div id="searchbox">
<form id="search_fm" method="post">
<div class="fitem">
彩种类型:<select name="" id="lotteryId">
<option value="">==请选择==</option>
<option value="1001">重庆时时彩</option>
<option value="1002">江西时时彩</option>
</select>
开奖时间:<input type="text" name="" id="lotterydate" readonly="readonly" size="10" οnclick="WdatePicker({dateFmt:'yyyy-MM-dd'})" maxlength="10" />
开奖期号:<input type="text" name="" id="lotteryIssue"/>
<br/><br/>
<a href="#" class="easyui-linkbutton search_btn" iconCls="icon-search">查询</a>
<a href="#" class="easyui-linkbutton print_btn" iconCls="icon-print">导出报表</a>
<!-- <input type="button" value="点我" οnclick="$(document).mask('加载...').click(function(){$(document).unmask()})" /> -->
</div>
</form>
</div>
</body>
</html>
效果图如下: