温馨提示:您的每一次转载,体现了我写此文的意义!!!烦请您在转载时注明出处http://www.blogjava.net/sxyx2008/谢谢合作!!!

雪山飞鹄

温馨提示:您的每一次转载,体现了我写此文的意义!!!烦请您在转载时注明出处http://www.blogjava.net/sxyx2008/谢谢合作!!!

BlogJava 首页 新随笔 联系 聚合 管理
  215 Posts :: 1 Stories :: 674 Comments :: 0 Trackbacks
页面代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html; charset=utf-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path 
= request.getContextPath();
%>
<html>
<head>
    
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
<link rel="stylesheet" type="text/css" href="<%=path %>/css/style.css">
    
<link rel="stylesheet" type="text/css" href="<%=path %>/css/easyui.css">
    
<link rel="stylesheet" type="text/css" href="<%=path %>/css/icon.css">
    
<script type="text/javascript" src="<%=path %>/js/jquery.js"></script>
    
<script type="text/javascript" src="<%=path %>/js/jquery.easyui.min.js"></script>
    
<script type="text/javascript" src="<%=path %>/js/mouseEvnet.js"></script>
    
<script type="text/javascript" src="<%=path %>/js/page.js"></script>
    
<script type="text/javascript" src="<%=path %>/js/sorttable.js"></script>
    
<script type="text/javascript">
      function export_report(type,title)
{
          var tableHeader
="";
          var tableBody
="";
          
//获取表格信息
          $("#tableResult tr").each(function(i,_tr){
              $(_tr).children().each(function(k,_td)
{
                  
if(i==0){
                      tableHeader
+=$.trim($(_td).text())+",";
                  }
else{
                      tableBody
+=$.trim($(_td).text())+"##";
                  }

              }
);
              
if(i>0){
                   tableBody
+="@@";
              }

          }
);
          
if(tableHeader==""){
              alert(
"表头未初始化!");
              
return false;
          }

          
if(tableBody==""){
              alert(
"表格体没内容!");
              
return false;
          }

          $(
"#report_title").val(title);
          $(
"#report_type").val(type);
          $(
"#report_tableHeader").val(tableHeader);
          $(
"#report_tableBody").val(tableBody);
          $(
"#report_form").submit();
             
      }

    
</script>
</head>
    
<body>
<form action="#" method="post" target="_self" name="naturalPerson" id="naturalPerson">
<c:if test="${list==null||empty list}" var="val">
    
<center><font color='red' size=3>对不起,没有你要查询的记录!!!</font></center>
</c:if>
<c:if test="${!val}">
    
<div class="dispaly-div" >
    
<table id="tableResult" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" style="border-collapse: collapse;" class="sortable">
      
<thead>
          
<tr style="cursor: pointer;">
        
<td  height="28" align="center" class="td_LTBG">户人编号</td>
        
<td  height="28" align="center" class="td_LTBG">户编号</td>
        
<td  height="28" align="center" class="td_LTBG">姓名</td>
        
<td  height="28" align="center" class="td_LTBG">性别</td>
        
<td  height="28" align="center" class="td_LTBG">现居住地</td>
        
<td  height="28" align="center" class="td_LTBG">户籍所在地</td>
        
<td  height="28" align="center" class="td_LTBG">公民身份证号码</td>
        
<td  height="28" align="center" class="td_LTBG">出生日期</td>
        
<td  height="28" align="center" class="td_LTBG">民族</td>
        
<td  height="28" align="center" class="td_LTBG">文化程度</td>
        
<td  height="28" align="center" class="td_LTBG">户口性质</td>
        
<td  height="28" align="center" class="td_LTBG">婚姻状况</td>
      
</tr>
      
</thead>
      
<c:forEach items="${list}" var="naturalPerson">
           
<tr>
               
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.hrbh}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.hbh}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.xm}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.xb}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.xjzd}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.hjszd}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.gmsfzhm}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.csrq}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.mz}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.whcd}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.kuxz}"/></td>
            
<td  height="28" align="center" class="td_TRB"><c:out value="${naturalPerson.hyzk}"/></td>
           
</tr>
      
</c:forEach>
     
</table>
     
</div>
    
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
        
<tr>
            
<td height="25" align="right" class="td_RB">
             
<span style="margin-right: 20%;">
                 
<a id="expor_pdf" onclick="return export_report('pdf','自然人基本信息');" style="cursor: pointer;">导出PDF</a> | 
                 
<a  id="expor_excel" onclick="return export_report('excel','自然人基本信息');" style="cursor: pointer;">导出Excel</a>
             
</span>
            
              共
<font color="red" size="2">${page.rowCounts}</font>&nbsp;&nbsp;
              当前
<font color="red" size="2">${page.currPageNum}</font>/<font color="red" size="2">${page.pageCount}</font>&nbsp;
              
<c:if test="${page.currPageNum==1}">
                  
<a id="first" name="first">首页</a>&nbsp;
              
</c:if>
              
<c:if test="${page.currPageNum!=1}">
                  
<a id="first" name="first" href="javascript:goPages('naturalPerson','/naturalPersonAction','1')">首页</a>&nbsp;
              
</c:if>
              
<c:if test="${page.currPageNum>1}">
                  
<a id="pre" name="pre" href="javascript:goPages('naturalPerson','/naturalPersonAction','${page.currPageNum-1}')">上一页</a>
              
</c:if>
              
<c:if test="${page.currPageNum<=1}">上一页</c:if>&nbsp;
              
<c:if test="${page.currPageNum<page.pageCount}">
                  
<a id="next" name="next" href="javascript:goPages('naturalPerson','/naturalPersonAction','${page.currPageNum+1}')">下一页</a>
              
</c:if>
              
<c:if test="${page.currPageNum>=page.pageCount}">下一页</c:if>&nbsp;
              
<c:if test="${page.currPageNum==page.pageCount}">
                  
<a id="last" name="last">未页</a>&nbsp;
              
</c:if>
              
<c:if test="${page.currPageNum!=page.pageCount}">
                  
<a id="last" name="last" href="javascript:goPages('naturalPerson','/naturalPersonAction','${page.pageCount}')">未页</a>&nbsp;
              
</c:if>
              转到
&nbsp;<select name="pageNum" id="pageNum" class="input_text_page_width" onchange="goPagesForSelect('naturalPerson','/naturalPersonAction',$('#pageNum')[0].value)">
                  
<c:forEach var="varName" begin="1" end="${page.pageCount}" step="1">
                      
<c:if test="${varName==page.currPageNum}">
                    
<option value="${varName}" selected>${varName}</option>
                    
</c:if>
                    
<c:if test="${varName!=page.currPageNum}">
                    
<option value="${varName}">${varName}</option>
                    
</c:if>
                
</c:forEach>
            
</select>
            
&nbsp;&nbsp;&nbsp;&nbsp;
            
</td>
        
</tr>
    
</table>
</c:if>
</form>

<form action="<%=path%>/exportServlet" method="post" id="report_form">
   
<input type="hidden" name="title" id="report_title"/>
   
<input type="hidden" name="type" id="report_type"/>
   
<input type="hidden" name="tableHeader" id="report_tableHeader"/>
   
<input type="hidden" name="tableBody" id="report_tableBody"/>
</form>

</body>
</html>
后台代码:
package com.future.util;


import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

/**
 * 功能描述:此servlet用于将当前页面表格内容导出到pdf和excel<br>
 * 参数说明:
 *          String type 为导出类型
 *          String title 报表中title
 *          String tableHeader 页面中表格的表头
 *          String tableBody 表格内容
 * 注解:其中页面数据是以特殊字符分隔传递过来的
 *         逗号(,)用来连接表头,后台用逗号来解析页面传递过来的表头
 *         @@用来分隔一条数据,后台用@@来解析每条数据
 *         ##用来分隔单元格,后台用##来解析每条数据对应的单元格             
 * 创建时间:2010-07-01
 * 
@author sxyx2008
 * 
@version 1.0.0
 
*/

@SuppressWarnings(
"serial")
public class ExportServlet extends HttpServlet {
    
    @Override
    
protected void service(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        request.setCharacterEncoding(
"utf-8");
        response.reset();
        
//导出类型
        String type=request.getParameter("type");
        
//报表标题
        String title=request.getParameter("title");
        
//表头
        String tableHeader=request.getParameter("tableHeader");
        
//表格内容
        String tableBody=request.getParameter("tableBody");
        
//文件名
        String fileName="";
        
        
if("pdf".equals(type)){
            
try {
                exportToPdf(title,tableHeader,tableBody,response);
            }
 catch (Exception e) {
                e.printStackTrace();
            }

        }
else if("excel".equals(type)){
            fileName 
= new String(new String((title + ".xls").getBytes(),"ISO-8859-1"));
            response.setContentType(
"application/vnd.ms-excel;charset=utf-8");
            response.setHeader(
"Content-Disposition""attachment;filename="+ fileName);
            InputStream inputStream
=exportToExcel(title, tableHeader,tableBody);
            ServletOutputStream out 
= response.getOutputStream();
            BufferedInputStream bis 
= null;
            BufferedOutputStream bos 
= null;
            
try {
                bis 
= new BufferedInputStream(inputStream);
                bos 
= new BufferedOutputStream(out);
                
byte[] buff = new byte[2048];
                
int bytesRead;
                
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 
0, bytesRead);
                }

            }
 catch (final IOException e) {
                
throw e;
            }
 finally {
                
if (bis != null)
                    bis.close();
                
if (bos != null)
                    bos.close();
            }

        }

    }

    
    
    
/**
     * 导出到excel表格
     
*/

    
private InputStream exportToExcel(String title,String tableHeader,String tableBody) {
        
        
// 创建工作表
        HSSFWorkbook wb = new HSSFWorkbook();
        
// 创建第一个工作区
        HSSFSheet sheet = wb.createSheet(title);
        
// 创建标题行
        HSSFRow row = sheet.createRow(0);
        
// 获取表头
        String[] header = tableHeader.split(",");
        
// 分隔每一行记录
        String[] content = tableBody.split("@@");
        
        
// 创建表头
        HSSFCell cell = null;
        
for (int i = 0; i < header.length; i++{
            cell 
= row.createCell(i);
            cell.setCellValue(header[i]);
        }

        
//循环每条记录
        for (int i = 0; i < content.length; i++{
            row 
= sheet.createRow(i + 1);
            
//取出每个单元格的值
            String[] value=content[i].split("##");
            
for (int j = 0; j < value.length; j++{
                cell 
= row.createCell(j);
                cell.setCellValue(value[j]);
            }

        }

        ByteArrayOutputStream os 
= new ByteArrayOutputStream();
        
try {
            wb.write(os);
        }
 catch (IOException e) {
            e.printStackTrace();
        }

        
byte[] contents = os.toByteArray();
        InputStream is 
= new ByteArrayInputStream(contents);
        
return is;
    }

    
    
    
    
    
    
/**
     * 导出到pdf
     * 
     
*/

    
private void exportToPdf(String title,String tableHeader,String tableBody,HttpServletResponse response) throws Exception{
        Document doc
=new Document(PageSize.A4,50,50,50,50);
        ByteArrayOutputStream byteArrayOutputStream
=new ByteArrayOutputStream();
        PdfWriter writer
=PdfWriter.getInstance(doc,byteArrayOutputStream);
        doc.addCreationDate();
        HeaderFooter footer
=new HeaderFooter(new Phrase(), true);
        
//设置页脚是否有边框
        
//0表示无
        
//1上边框
        
//2下边框
        
//3上下边框都有 默认都有

        footer.setBorder(
0);
        
//footer.setBorder(1);
        
//footer.setBorder(2);
        
//footer.setBorder(3);
        
        footer.setAlignment(Element.ALIGN_CENTER);
        doc.setFooter(footer);
        doc.open();
        
// 获取表头
        String[] header = tableHeader.split(",");
        
// 分隔每一行记录
        String[] content = tableBody.split("@@");
        
//根据传递进来的表头创建pdf的表头
        
        Paragraph paragraph
=new Paragraph(title,ChineseFont());
        paragraph.setAlignment(Element.ALIGN_CENTER);
        doc.add(paragraph);
        
        Table table
=new Table(header.length);
        table.setWidth(
100);
        table.setBorder(
1);
        
for (int i = 0; i < header.length; i++{
            Cell cell
=new Cell(new Phrase(header[i],ChineseFont()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            cell.setHeader(
true);
            cell.setBackgroundColor(
new Color(231,231,231));
            table.addCell(cell);
        }

        table.endHeaders();
        
//循环每条记录
        for (int i = 0; i < content.length; i++{
            Cell cell
=null;
            
//取出每个单元格的值
            String[] value=content[i].split("##");
            
for (int j = 0; j < value.length; j++{
                cell 
= new Cell(new Phrase(value[j],ChineseFont()));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
            }

            
        }

        doc.add(table);
        doc.close();
        writer.close();
        String fileName 
= new String(new String((title + ".pdf").getBytes(),"ISO-8859-1"));
        response.setContentType(
"application/pdf;charset=utf-8");
        response.setHeader(
"Content-Disposition""attachment;filename="+ fileName);
        ServletOutputStream outputStream
=response.getOutputStream();
        byteArrayOutputStream.writeTo(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    
    
    
/**
     * pdf中文字体设置
     * 
@return
     
*/

    
public static Font ChineseFont()
    
{
        BaseFont baseFont
=null;
        
try {
            baseFont
=BaseFont.createFont("STSong-Light","UniGB-UCS2-H"true);
        }
 catch (DocumentException e) {
            e.printStackTrace();
        }
 catch (IOException e) {
            e.printStackTrace();
        }

        Font chineseFont
=new Font(baseFont,8,Font.BOLD,Color.BLACK);
        
return chineseFont;
    }

    
    
    
    
    
}


posted on 2010-07-01 18:07 雪山飞鹄 阅读(2369) 评论(0)  编辑  收藏 所属分类: javase

只有注册用户登录后才能发表评论。


网站导航: