java實現導出網頁數據到excel


寫東西,遇到需要導出所顯示的表格內容到excel,研究了一陣子,完成。記錄一下!

項目使用的是spring+springMVC+ibatis框架。

首先是在頁面根據導出按鈕的點擊進入js控制代碼,去控制層獲取excel導出所需要的數據源,

頁面代碼如下:

jsp頁面代碼實現:

<input type="button" class="newBtn" onclick="exportTable()" value="導出Excel">


function exportTable(){
    var userName = $.trim($("#fuserName").val());
    var className = $.trim($("#fclassName").val());
var param = "userName="+userName+"&className="+className; window.open("<c:url value='/ceshi/getListForExcel.do?"+param+"'/>"); }

控制層代碼實現:

@RequestMapping("/getListForExcel")
    public String getgetListForExcel(HttpServletRequest request,HttpServletResponse response){
        
        try {
        //查詢的條件...... String userName
= RequestHandler.getString(request, "userName"); String className = RequestHandler.getString(request, "className"); Ceshi ceshi = new ceshi(); ceshi.setUserName(userName); ceshi.setClassName(className); int total = ceshiService.getceshiCount(ceshi); List<Ceshi> ceshiList = null; if(total>0){
          //查出數據 ceshiList
= ceshiService.getceshiList(ceshi); }else{ ceshiList = new ArrayList<Ceshi>(); } request.setAttribute("ceshiList", ceshiList);
          //返回頁面
return "ceshi/exportCeshi"; } catch (Exception e) { e.printStackTrace(); } return null; }

在上面的控制層代碼里面得到了要導出來的所有的數據,通過return "ceshi/exportCeshi";返回這些數據到exportCeshi這個jsp頁面,組裝並生成excel表格。

exportCeshi頁面代碼:

<%@ page language="java"  contentType="text/html;charset=gb2312" %> 
<%@ page language="java" import="com.ceshi.domain.Ceshi" %>
<%@ page language="java" import="java.util.*,
    org.apache.poi.hssf.usermodel.HSSFWorkbook,
    org.apache.poi.hssf.usermodel.HSSFSheet,
    org.apache.poi.hssf.usermodel.HSSFRow,
    org.apache.poi.hssf.usermodel.HSSFCell" %>
<%@ page language="java" import="org.apache.poi.hssf.usermodel.HSSFCellStyle" %>
<%@ page language="java" import="org.apache.poi.hssf.util.*" %>
<%@ page language="java" import="org.apache.poi.hssf.usermodel.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title></title>
    
    <!--清除瀏覽器中的緩存,它和其它幾句合起來用,就可以使你再次進入曾經訪問過的頁面時,
        瀏覽器必須從服務端下載最新的內容,達到刷新的效果。-->
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    

  </head>
  
  <%
   response.setContentType( "APPLICATION/OCTET-STREAM" );
   List<Ceshi> list = (List<Ceshi>)request.getAttribute("ceshiList");
   String titleStr = "導出的excel的名稱";
   String title = new String(titleStr.getBytes("gb2312"),"iso-8859-1");
   response.setHeader( "Content-Disposition" ,"attachment;filename=\"" + title + ".xls" + "\"" );

   HSSFWorkbook wb = new HSSFWorkbook();
   HSSFFont font = wb.createFont();
   font.setFontHeightInPoints((short)14);
   font.setBoldweight((short)600);
   HSSFSheet sheet = wb.createSheet("sheet1");
   sheet.setColumnWidth((short)0,(short)(1500));
   sheet.setColumnWidth((short)1,(short)(4500));
   sheet.setColumnWidth((short)2,(short)(4500));
   sheet.setColumnWidth((short)3,(short)(4500));
   HSSFCellStyle style = wb.createCellStyle(); 
   style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
   HSSFCellStyle styleFont = wb.createCellStyle(); 
   styleFont.setAlignment(HSSFCellStyle.ALIGN_CENTER);
   styleFont.setFont(font);

   // 以下以寫表頭
   // 表頭為第一行 
   HSSFRow head = sheet.createRow((short)0);
   HSSFCell headCell = head.createCell((short)0);
   sheet.addMergedRegion(new Region(0,(short)0,0,(short)3));//合並單元格
   HSSFRow row = sheet.createRow((short)1);

   HSSFCell cell1 = row.createCell((short)0);
   HSSFCell cell2 = row.createCell((short)1);
   HSSFCell cell3 = row.createCell((short)2);
   HSSFCell cell4 = row.createCell((short)3);
   
   headCell.setEncoding(HSSFCell.ENCODING_UTF_16);
   headCell.setCellType(HSSFCell.CELL_TYPE_STRING);
   headCell.setCellStyle(styleFont);
   cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell1.setCellStyle(style);
   cell2.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell2.setCellStyle(style);
   cell3.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell3.setCellStyle(style);
   cell4.setEncoding(HSSFCell.ENCODING_UTF_16);
   cell4.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell4.setCellStyle(style);
   
   
   // 定義表頭的內容 
   headCell.setCellValue(titleStr);
   cell1.setCellValue("序號");
   cell2.setCellValue("姓名");
   cell3.setCellValue("班級");
   cell4.setCellValue("生日");

   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   
   for(int i=1; i<list.size()+1; i++){
       Ceshi ceshi = list.get(i-1);
       // 定義數據從第二行開始        
      row  =  sheet.createRow((short) i + 1);
      cell1  =  row.createCell((short)0);
      cell2  =  row.createCell((short)1);
      cell3  =  row.createCell((short)2);
      cell4  =  row.createCell((short)3);
      
      headCell.setEncoding(HSSFCell.ENCODING_UTF_16);
      headCell.setCellType(HSSFCell.CELL_TYPE_STRING);
      headCell.setCellStyle(styleFont);
      cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
      cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
      cell1.setCellStyle(style);
      cell2.setEncoding(HSSFCell.ENCODING_UTF_16);
      cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
      cell2.setCellStyle(style);
      cell3.setEncoding(HSSFCell.ENCODING_UTF_16);
      cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
      cell3.setCellStyle(style);
      cell4.setEncoding(HSSFCell.ENCODING_UTF_16);
      cell4.setCellType(HSSFCell.CELL_TYPE_STRING);
      cell4.setCellStyle(style);

      // 填充內容 
      cell1.setCellValue(i);

      if(ceshi.getUserName() != null){
          cell2.setCellValue(ceshi.getUserName()); 
      }else{
          cell2.setCellValue(""); 
      }
      if(ceshi.getClassName() != null){
          cell3.setCellValue(ceshi.getClassName()); 
      }else{
          cell3.setCellValue(""); 
      }
      if(ceshi.getBirth() != null){
          cell4.setCellValue(sdf.format(ceshi.getBirth())); //轉換數據庫出來的date類型為簡單日期格式
      }else{
          cell4.setCellValue(""); 
      }
      
  } 
  wb.write(response.getOutputStream());
  response.getOutputStream().flush();
  out.clear();
  response.getOutputStream().close();
  out.clear();
  out = pageContext.pushBody();
  %>
</html>

如果還有什么疑問,可以評論指出來。描述的不對的地方,還請各位諒解,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM