导出选中的日志为excel文件

来源:互联网 发布:淘宝男装排行榜 编辑:程序博客网 时间:2024/04/29 02:53

用到了jar包jxl.jar。

bhlLog.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.bhl.application.core.bo.TreeNodeModel" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
List<TreeNodeModel> treeNodeList=(List<TreeNodeModel>)request.getAttribute("treeNodeList");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html>
<head>
<title>系统日志</title>
<%@ include file="/css&js.jsp" %>
<script type="text/javascript">
bhlPageSize = ${sessionScope.bhlSessionPageSize};
$(document).ready(function(){
tableShow();
//系统参数,日期分隔符
bhlDateSep = '${sessionScope.bhlSessionDateSeq}';
toolbar = new dhtmlXToolbarObject("bhlLogBar");
toolbar.setIconsPath("<c:url value='/images/toolbar/'/>");
toolbar.loadXML("<c:url value='/js/dhtmlx/tbxml/bhlLogBar.xml'/>?etc="+new Date().getTime());
addRedStart();
});


function tableShow(){
$('#showData').datagrid({
width:'100%',//宽度
height:'auto',//高度
pageList:[bhlPageSize,bhlPageSize*2,bhlPageSize*3],
pageNumber:1,
pageSize:bhlPageSize,
nowrap:true,
striped:true,
collapsible:true,
url:null,
loadMsg:'数据装载中.....',
//idField:'ID',
remoteSort:false,
fitColumns:true,//true就会自动扩大或缩小列的尺寸以适应表格的宽度并且防止水平滚动
pagination:true,
columns:[[
{field:'SID',title:'全选',width:50,checkbox:true},
{field:'operateModule',title:'操作模块',width:200,align:'left',sortable:true},
{field:'operateType',title:'操作名称',width:200,align:'left',sortable:true},
{field:'operateContent',title:'操作内容',width:400,align:'left',sortable:true},
{field:'userName',title:'操作人',width:200,align:'left',sortable:true},
{field:'showTime',title:'操作时间',width:200,align:'center',sortable:true},
{field:'userIp',title:'操作IP地址',width:200,align:'center',sortable:true},
{field:'id',title:'Id',width:60,align:'left',sortable:false,hidden:true}
]],
onLoadSuccess:function(){
disabledButton('icon-search',false);
//$("[iconCls='icon-search']").attr("disabled",false);
$('#showData').datagrid("clearSelections");
},
onLoadError:function(){
disabledButton('icon-search',false);
//$("[iconCls='icon-search']").attr("disabled",false);
}
});
searchBhLLog();
}
var beginTime="";
var endTime="";
var operatePerson="";
var operateModule="";
var operateName="";
var operateContent="";
function searchBhLLog(){
//移除焦点,非绑定了enter键方法时,不需要按enter执行查询
  //$("input").get(0).focus();
  //控制按钮,防止重复点击提交
  $("input[type!=hidden][disabled!=true][readonly!=true]").get(0).focus();
  disabledButton('icon-search',true);
  //$("[iconCls='icon-search']").attr("disabled",true);
if(vali("")){
beginTime=$('#beginTime').val();
endTime=$('#endTime').val();
if(beginTime>endTime){
$.messager.alert('提示信息','起始时间不得晚于结束时间!','info',function(){
disabledButton('icon-search',false);
//$("[iconCls='icon-search']").attr("disabled",false);
});
}else{
operatePerson=$('#operatePerson').val();
operateModule=$('#operateModule').val();
operateName=$('#operateName').val();
operateContent=$('#operateContent').val();
$('#showData').datagrid({url:'bhlLogAction!searchLog.action',
pageNumber:1,
queryParams:{
beginTime:beginTime,
endTime:endTime,
operatePerson:operatePerson,
operateModule:operateModule,
operateName:operateName,
operateContent:operateContent
    }
});
$('#showData').datagrid('clearSelections');
$('#tool').show();
}
}else{
$("[iconCls='icon-search']").attr("disabled",false);
}
}
//删除操作
function deletLog(){
var rows=$('#showData').datagrid("getSelections");
var rows2=$('#showData').datagrid("getRows");
var ids="";
if(rows.length<=0){
$.messager.alert('提示信息','请选择您需要删除的日志信息!','info');
return false;
}
if(rows2.length>0){
for(var i=0;i<rows.length;i++){
ids+=rows[i]['id'];
ids+=",";
}
if(ids!=""){
$.messager.confirm('提示信息', "您确认要进行删除操作吗?", function(r){
if (r){
$.ajax({
url:'bhlLogAction!deletLog.action',
type:"POST",
dataType:"json",
data:{
ids:ids
},
beforeSend: function(XMLHttpRequest){
},
success:function (data, textStatus){
if(data.success){
reflshTable(rows);
$.messager.alert('提示信息','您的删除操作已成功!','info');
}
},
error:function (XMLHttpRequest, textStatus, errorThrown){
$.messager.alert('提示信息','对不起,您的请求操作失败!','error');
}
});
}
});
}
}

}
//删除后刷新数据
  function reflshTable(rows){
  /*for(var i=0; i<rows.length; i++){
  var index = $('#showData').datagrid('getRowIndex',rows[i]);
  $('#showData').datagrid('deleteRow',index);
  }*/
  //重新加载数据
  $('#showData').datagrid({url:'bhlLogAction!searchLog.action',
queryParams:{
beginTime:beginTime,
endTime:endTime,
operatePerson:operatePerson,
operateModule:operateModule,
operateName:operateName,
operateContent:operateContent
}
});
  $('#showData').datagrid('clearSelections');
}

//导出日志
function exportLog(){
var rows=$('#showData').datagrid("getSelections");
var rows2=$('#showData').datagrid("getRows");
if (rows2.length <= 0) {
$.messager.alert('提示信息', '对不起,当前没有可导出的日志!', 'info');
return;
}
var ids="";
if(rows2.length>0){
for(var i=0;i<rows.length;i++){
ids+=rows[i]['id'];
ids+=",";
}

if(ids==""){
$.messager.confirm('提示信息', "您确认要导出所有的日志信息?", function(r){
if(r){//导出所有日志
document.forms['queryForm'].action = "bhlLogAction!exportLog.action?ids="+ids+"&beginTime="+beginTime+"&endTime="+endTime+"&operatePerson="+
operatePerson+"&operateModule="+operateModule+"&operateName="+operateName+"&operateContent="+operateContent;   
document.forms['queryForm'].submit();
}
});
}else{//导出用户选中的日志
$.messager.confirm('提示信息', "您确认要导出当前选中的"+rows.length+"条日志信息?", function(r){
if(r){
document.forms['queryForm'].action = "bhlLogAction!exportLog.action?ids="+ids+"&beginTime="+beginTime+"&endTime="+endTime+"&operatePerson="+
operatePerson+"&operateModule="+operateModule+"&operateName="+operateName+"&operateContent="+operateContent;  
document.forms['queryForm'].submit();
}
});
}
}
}
</script>
</head>


<body class="easyui-layout">

<div region="north" style="height:27px;overflow:hidden;border:0px;">
<div id="bhlLogBar" ></div>
</div>
<div region="center" style="border:0px;margin-top:2px;padding-bottom:3px;">
<div class="easyui-layout" fit="true">
<div region="center" style="width:100%;height:100%;overflow: hidden; border: 0px;overflow-y: auto;overflow-x: auto;">
<table width="99%" align="center">
<tr>
<td height="20%">
<form id="queryForm" name="queryForm" method="post">
<table width="100%" border="0" cellpadding="0" cellspacing="1"
bgcolor="white">
<tr >
<td class="F14T">操作模块:</td>
<td class="F14T"><input id="operateModule"/></td>
<td class="F14T">操作名称:</td>
<td class="F14T"><input id="operateName"/></td>
</tr>
<tr >
<td class="F14T">操作内容:</td>
<td class="F14T"><input id="operateContent"/></td>
<td class="F14T">操作人:</td>
<td class="F14T"><input id="operatePerson"/></td>
</tr>
<tr >
<td class="F14T">起始日期:</td>
<td class="F14T"><input id="beginTime" style="width:150px;height:20px;" class='Wdate easyui-validatebox' onfocus="_date()" onchange="validChoose('beginTime')" maxlength="10"/></td>
<td class="F14T">终止日期:</td>
<td class="F14T"><input id="endTime" style="width:150px;height:20px;" class='Wdate easyui-validatebox' onfocus="_date()" onchange="validChoose('endTime')" maxlength="10"/></td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td>
<a href="javascript:void(0)" id="mb1" class="easyui-linkbutton"
iconCls="icon-search" onclick="searchBhLLog()">查询</a>
</td>
</tr>
<tr>
<td height="80%">
<table id="showData" height="100%"></table>
</td>
</tr>
</table>
</div>

</div>
</div>
 </body>
</html>

==================================================================================================================

BhlLogAction.java

/**
*导出符合条件的日志
* @since 1.0
*/
public void exportLog(){
String beginTime=getServletRequest().getParameter("beginTime");
String endTime=getServletRequest().getParameter("endTime");
String operatePerson=getServletRequest().getParameter("operatePerson");
String operateModule=getServletRequest().getParameter("operateModule");
String operateName=getServletRequest().getParameter("operateName");
String operateContent=getServletRequest().getParameter("operateContent");
String ids = getServletRequest().getParameter("ids");

List<LogModel> loglist=new ArrayList<LogModel>();
if(ids==""||ids==null){
loglist=this.bhlLogService.getLogbyCondition(beginTime, endTime, operatePerson, operateModule, operateName, operateContent);
}else{
//ids 中id个数超过1000个的时候会报oracle的错误,因此要分开操作
String[] idArray = ids .split(",");
ArrayList<String> idsarray = new ArrayList<String>();
StringBuffer sb = new StringBuffer("");
for(int i=0;i<idArray.length;i++){
sb.append(idArray[i]).append(",");
if(i%900==899||i==idArray.length-1){
idsarray.add(sb.toString().substring(0,sb.length()-1));
sb = new StringBuffer("");
}
}
for(int j =0;j<idsarray.size();j++){
loglist.addAll(this.bhlLogService.getLogByIds(idsarray.get(j)));
}
}

LogModel bhllog = this.getBhlLog("系统日志","导出系统日志", "导出系统日志Excel");
this.bhlLogService.create(bhllog);

try {
response.reset();
response.setContentType("application/msexcel;");
String filename = "档案系统日志统计.xls";//文件标题
filename = new String(filename.getBytes("GBK"), "ISO8859-1");
if (request.getHeader("User-Agent").indexOf("MSIE 5.5") != -1) {
// MS IE5.5 有要作特别处理
response.setHeader("Content-Disposition", "filename=\""+ filename + "\"");
} else { // 非 IE5.5 的 Header 设定方式,IE 5.5 不能加上 attachment 这个关键词
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
}

ServletOutputStream output = response.getOutputStream();

this.write(output,loglist);//调用方法
output.flush();
output.close();


} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 设置导出
* @author:yangj
* @param output 输出流
* @param list 日志类型的list
* @since 1.0
*/
private void write(ServletOutputStream output,List<LogModel> list) {

        WritableWorkbook wwb = null;
        WritableSheet ws=null;
      
        try {
wwb= Workbook.createWorkbook(output);
       ws= wwb.createSheet("系统日志报表", 0);
       
       ws.setColumnView(0 , 40);//设置列宽度,
       ws.setColumnView(1 , 30);
       ws.setColumnView(2 , 25);
       ws.setColumnView(3 , 20);
       ws.setColumnView(4 , 20);
       ws.setColumnView(5 , 20);
       
       /** ----------设置标题样式begin------  */
/** 设置字的样式 */
WritableFont font1 = new WritableFont(WritableFont.createFont("楷体_GB2312"));
font1.setPointSize(16); // 设置字号
font1.setColour(Colour.BLACK); // 设置颜色
font1.setItalic(false);
/** 设置单元格的样式 */
WritableCellFormat cellFormat1 = new WritableCellFormat(font1);
cellFormat1.setBackground(Colour.SKY_BLUE); // 单元格背景色
cellFormat1.setBorder(Border.ALL, BorderLineStyle.THIN); // 单元格边框
cellFormat1.setAlignment(Alignment.CENTRE); // 水平居中
cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
cellFormat1.setWrap(true); // 自动换行
/** ----------设置标题样式end------  */

String filename = "档案管理系统——系统日志报表";//文件标题
//文件标题
Label label = null;
jxl.write.Number labelNum = null;

label = new Label(0, 0, filename, cellFormat1);
ws.addCell(label);
ws.mergeCells(0, 0, 5, 0);

/** ----------设置内容标题样式begin------  */
WritableFont font3 = new WritableFont(WritableFont.createFont("宋体"));
font3.setPointSize(10);
font3.setColour(Colour.BLACK); // 设置颜色
font3.setBoldStyle(WritableFont.NO_BOLD);
WritableCellFormat cellFormat3 = new WritableCellFormat(font3);
cellFormat3.setBackground(Colour.GRAY_25); // 单元格背景色
cellFormat3.setBorder(Border.ALL, BorderLineStyle.THIN); // 单元格边框
cellFormat3.setAlignment(Alignment.CENTRE); // 水平居中
cellFormat3.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
cellFormat3.setWrap(true); // 自动换行
/** ----------设置内容标题样式end------  */

/** ----------设置内容样式begin------  */
WritableFont font4 = new WritableFont(WritableFont.createFont("宋体"));
font4.setPointSize(10);
font4.setColour(Colour.BLACK); // 设置颜色
font4.setBoldStyle(WritableFont.NO_BOLD);
WritableCellFormat cellFormat4 = new WritableCellFormat(font4);
cellFormat4.setBorder(Border.ALL, BorderLineStyle.THIN); // 单元格边框
cellFormat4.setAlignment(Alignment.LEFT); // 
cellFormat4.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
cellFormat4.setWrap(true); // 自动换行
/** ----------设置内容标题样式end------  */
label = new Label(0, 1, "所在模块", cellFormat3);
ws.addCell(label);
label = new Label(1, 1, "操作名称", cellFormat3);
ws.addCell(label);
label = new Label(2, 1, "操作内容", cellFormat3);
ws.addCell(label);
label = new Label(3, 1, "操作人", cellFormat3);
ws.addCell(label);
label = new Label(4, 1, "操作时间", cellFormat3);
ws.addCell(label);
label = new Label(5, 1, "操作IP地址", cellFormat3);
ws.addCell(label);

//将值写入模板
if (list!=null && list.size()>0) {
for (int i = 0; i < list.size(); i++) {
LogModel log = (LogModel)list.get(i);
label = new Label(0, i+2, log.getOperateModule() , cellFormat4);
ws.addCell(label);
label = new Label(1, i+2, log.getOperateType(), cellFormat4);
ws.addCell(label);
label = new Label(2, i+2, log.getOperateContent(), cellFormat4);
ws.addCell(label);
label = new Label(3, i+2, log.getUserName(), cellFormat4);
ws.addCell(label);
label = new Label(4, i+2, log.getShowTime(), cellFormat4);
ws.addCell(label);
label = new Label(5, i+2, log.getUserIp(), cellFormat4);
ws.addCell(label);
}
}                    
            wwb.write();
            wwb.close();

}catch (WriteException e) {
System.out.println("ExpenseExcelAction write WriteException e="+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("ExpenseExcelAction write IOException e="+e.getMessage());
e.printStackTrace();

}




0 0