1. 程式人生 > >有關Java從資料庫查詢出的資料匯出Excel POI分頁功能總結

有關Java從資料庫查詢出的資料匯出Excel POI分頁功能總結

這幾天一直在做Java從資料庫查詢出的資料匯出Excel 的功能;做著做著發現:

當 row 超過65535的時候會報異常,該怎麼解決呢?

首先宣告一下,我的專案是基於Struts+ spring + mybatis的:以下方法僅供參考!

那麼我們先從jsp傳值開始看起吧

----jsp中主要程式碼

 $('#exportBtn').click(function(){						    	
				 param0 = getFormJson("#queryForm");
						 	    	 
				 flag =1 ;
				 var m =param0.m;
				 var startTime = param0.startTime; 
				 var endTime = param0.endTime; 
				 var siteid = param0.siteid;
						 	    	
window.location.href = "${ctx}/dataexport!getExportView.ce?m="+m+"&startTime="+ startTime + "&endTime=" + endTime+ "&siteid=" + siteid;
				 });

注:exportBtn是匯出按鈕的ID;queryForm是查詢所在的Form表單的ID;param0.startTime對應著你要獲取東西的ID;ID必須保持一致

----DataexportMapper.java 中的 interface

public List<Map<String, Object>> getExportList(Map<String, Object> map);

public int getListCount(Map<String, Object> map);
注:建立List的物件getExportList ;List可以理解為連結串列;getExportList這個錶鏈的元素是map型別的元素,map是由String到Object的對映

----DataexportMapper.xml  寫的是動態SQL語句

 <!-- 根據siteid獲取 MAC資訊-->
	  <select id="getMacExportList" resultType="hashmap" parameterType="hashmap">
	  		select * from (
	  			select * from (
	  				select c.m,
	  				to_char(c.starttime, 'yyyy-mm-dd hh24:mi:ss') starttime,
	  				b.sitename, 
	  				rownum row_num
            from dbuser.hot_dict_m a, dbuser.hot_dict_s b,dbuser.hot_w c
      where a.wsiteid = b.siteid
          and a.wagentid = c.siteagent
			    		
			       <if test="@
[email protected]
(siteid) "> and b.siteid=#{siteid} </if> <if test="@[email protected](siteid2) "> and b.siteid=#{siteid2} </if> <if test="@[email protected](m) "> and M like '${m}%' </if> <if test="@[email protected](startTime) "> <![CDATA[ and c.starttime >= to_date(#{startTime}, 'yyyy-mm-dd hh24:mi:ss') ]]> </if> <if test="@[email protected](endTime) "> <![CDATA[ and c.starttime < to_date(#{endTime}, 'yyyy-mm-dd hh24:mi:ss') ]]> </if> ) p1 where <![CDATA[ rownum<= #{endIndex,jdbcType=INTEGER} ]]> )p2 where <![CDATA[ row_num>= #{beginIndex,jdbcType=INTEGER} ]]> </select>
 <select id="getListCount" resultType="int" parameterType="hashmap">
	    	select count(*)
            from dbuser.hot_dict_m a, dbuser.hot_dict_s b,dbuser.hot_wi c
        where a.wsiteid = b.siteid
          and a.wagentid = c.siteagent
         		   <if test="@[email protected](siteid) ">
			    			and  b.siteid=#{siteid}		
			        </if>	
			         <if test="@[email protected](siteid2) ">
			    			and  b.siteid=#{siteid2}		
			        </if>	
	
			        <if test="@[email protected](m) ">
			    			and M like '${m}%'
			        </if>
			         <if test="@[email protected](startTime) ">
							 <![CDATA[  
									and c.starttime >=
							          to_date(#{startTime}, 'yyyy-mm-dd hh24:mi:ss')
							]]>
					 </if>
					 <if test="@[email protected](endTime) ">
							<![CDATA[  
								and c.starttime <
							    to_date(#{endTime}, 'yyyy-mm-dd hh24:mi:ss')
						   ]]>
				     </if>
	  </select>


注:row_num 是做分頁處理的;select中ID的名字一定要和ataexportMapper.java中的方法一致

----DataexportAction.java  

@Controller("DataexportAction")
@Scope("prototype")
@Results({
	@Result(name="getMacExportView",location="/WEB-INF/views/home/mapHotphoneMAC.jsp"),

public void getMacExportView(){
		Map<String,Object> params = getMapParams();
		
		params.put("userID", this.getUserContext().getUserId());
		params.put("beginIndex", 1);//起始行
		params.put("endIndex", dataServices.getListCount(params));//結束行
		HttpServletResponse response = ServletActionContext.getResponse();//取得response例項
		response.setCharacterEncoding("utf-8");//設定輸出的編碼
		dataexportServices.getExportList(params,response);
		
	}

注:資料查詢匯出工具action,結束行是呼叫以前寫的方法,就是獲取總數的Count

下面是最主要的部分了:

----DataexportServices.java    匯出查詢資料及POI的分頁

int pageSize = 65533;
	
	public void getExportList(Map<String, Object> map,
			HttpServletResponse response) {
		HttpServletResponse response1 = response;
		List<Map<String,Object>> list = dataexportMapper.getExportList(map);
		
		DataExcelCreate(list,response1);
	}

	public void DataExcelCreate(List<Map<String, Object>> list,
			HttpServletResponse response) {
		HttpServletResponse response1 = response;
		String sheetname="sheet";
		HSSFWorkbook wb = new HSSFWorkbook();//建立HSSFWorkbook物件
		int size = list.size();
		if(response1 != null && size>0){
			int sheetCount = size % pageSize == 0? size / pageSize : size /pageSize + 1;
			for(int i = 1;i <= sheetCount;i++){
				HSSFSheet sheet = null;//建立新的sheet物件(Excel的表單)
				
				
				if (!StringUtils.isEmpty(sheetname)){
					sheet = wb.createSheet(sheetname+i);
				}else{
					sheet = wb.createSheet();
				}
				sheet.setDefaultRowHeightInPoints(20);//設定預設列高
				sheet.setDefaultColumnWidth(20);//設定預設列寬
				HSSFRow row1 = sheet.createRow(0);//建立索引行
				HSSFCell cell = row1.createCell(0);//建立單元格
				cell.setCellValue("MAC表");
				//合併單元格CellRangeAddress構造引數依次是:起始行,,截至行,起始列,截至列
				sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));
				HSSFRow row2 =sheet.createRow(1);
				row2.createCell(0).setCellValue("M");   
				row2.createCell(1).setCellValue("開始時間");
				row2.createCell(2).setCellValue("名稱");
				int begin =(i-1)*pageSize;
				int end = begin + pageSize;
				int rowCount=2;
				if(end>size){
					end = size;
				}else{
					end =i* pageSize;
				}
				for(int j=begin;j<end;j++){
			    	HSSFRow row=sheet.createRow(rowCount); 
					rowCount++;
					Map map = list.get(j);
				    row.createCell(0).setCellValue((String) map.get("M"));
				    row.createCell(1).setCellValue((String) map.get("STARTTIME"));
				    row.createCell(2).setCellValue((String) map.get("SITENAME"));
			    }
			}
		}
		
	        OutputStream output;
	    try {
			output=response.getOutputStream();
			response.reset();
			response.setHeader("Content-disposition", "attachment;filename=details.xls");
			response.setContentType("application/msexcel");
			wb.write(output);
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


友情提示:大家在呼叫方法的時候不要寫錯了,要對應起來

注:如果有什麼問題,可以提出,大家一起進步微笑

相關推薦

有關Java資料庫查詢資料匯出Excel POI功能總結

這幾天一直在做Java從資料庫查詢出的資料匯出Excel 的功能;做著做著發現: 當 row 超過65535的時候會報異常,該怎麼解決呢? 首先宣告一下,我的專案是基於Struts+ spring + mybatis的:以下方法僅供參考! 那麼我們先從jsp傳值開始看起吧

java 三層架構 實現資料的顯示和功能

  /*    *  <!-- 隱藏域 false:表示點選的是上頁下頁   true:表示點選的是 "搜尋" 按鈕 -->             <input type="hidden"  name="flag" id="flag"  value="true" >    */   

Java基於POI實現excel任意多級聯動下拉列表——支援資料庫查詢多級資料後直接生成【附原始碼】

 Excel相關知識點 (1)名稱管理器——Name Manager 【CoderBaby】首先需要建立多個名稱(包含key及value),作為下拉列表的資料來源,供後續通過名稱引用。可通過選單:“公式”---“名稱管理器&rdquo

Java資料庫表中資料匯出Excel表格

        在我們學習和使用Java的過程中,會有匯出資料庫中的資料(或其他資料)到表格中的需求。比如你建了一個部落格網站,也寫了很多篇部落格,那麼就想把寫的所有部落格匯出到xls表格中。因為資料在伺服器可能會面臨資料丟失的風險(比如伺服器重灌系統,伺服器

詳細步驟!!!idea+springboot+mybatis+jsp+bootstrap實現mysql查詢資料並顯示(原始碼)

實現效果: 資料庫對應資料: 開發環境: IntelliJ IDEA 2017.2.5 x64 java version "1.8.0_151" x64 mysql 6.0.11-alpha-community x64 步驟: 1.建立工程: file--new-

java資料庫裡的資料匯出excel

package com.hui10.app.controller.merchant;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Collection;import ja

通過ajax方式後臺查詢資料並填入前臺的select中

首先需要清空之前下拉框中的內容,否則會出現選項重複的情況,根據url的路徑查詢出select中所要展示的list,判斷list是否為空,如為空,需要置入空行,如不為空,用jquery取到select後將整個list用append的方式置入,程式碼如下,附抽出的ajax提交方

資料庫查詢到的資料匯出excel

        步驟一:封裝資料 List<Map<String, String>> result = new ArrayList<>(); Map<String, String> map = new Link

Java程式設計中怎麼將資料庫查詢出來的資料導成Excel檔案?

import jxl.*; import jxl.write.*; import java.io.*; import java.io.File.*; import java.util.*; public class excel {

資料庫查詢資料並輸出到前臺頁面

<?php        //獲取資料庫中的所有留言           require_once("connect.php");   &nbs

Java 資料庫匯出 Excle 表

目錄   一、效果圖 二、excle 生成的工具類原理 三、excle 生成的工具類原始碼 四、在 Controller 層中如何使用? 五、測試 一、效果圖 二、excle 生成的工具類原理 通過呼叫工具類,先判斷在伺服器中指定的資料夾中有沒

IE中在js中將查詢資料匯出excel表格

<input style="width: 70px; height: 22px;margin-left: 10%;font-family: \"微軟雅黑\" ; font-size: 12px; color:#2587D2 " type="button" onclick="move('exec

LBS中資料庫查詢某經緯度2KM範圍內的資料

之前很啥很天真地以為無非就是逐個計算距離,然後比較出來就行了,然後當碰到訪問使用者很多,而且資料庫中經緯度資訊很多的時候,計算量的迅速增長,能讓伺服器完全傻逼掉,還是老前輩的經驗比我們豐富,給了我很大的啟示。 MySQL效能調優 – 使用更為快速的演算法進行距離計算

如果將Java資料庫查詢到的結果集轉換為Json陣列形式

package util; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.Date; import net.sf.json.JSONArray; import n

第一篇 部落格:java資料庫讀取資料,並寫入到excel表格中

  今天,組長分配了查詢資料庫記錄,並把這些記錄寫入到excel表格中,以前沒有嘗試過,借鑑了一些別人的程式碼,最終實現了功能,寫一篇部落格,總結一下這個過程。1.準備需要用到的jar包    1.jxl.jar     2.mysql-connector-java-5.1.

是用JDBC資料庫中獲取資料並以java物件返回

/** * * @param c * for example Person.class * @param primaryKeys * primaryKeys為主鍵,引數順序和表中保持一致 如果id, name

資料庫查詢得到的列舉資料列,int轉成對應的列舉欄位

列舉型別public enum Emotion{未分析,正面,中立,負面}這裡使用的是MiniDao@MiniDao("emotionMiniDao")public interface EmotionMiniDao {@Sql("SELECT CONCAT(emotion)

oracle資料庫查詢只包含數字的資料集合。

1.查詢所有資料 select malCode from eam_run_malCode ; 2.查詢只包含數字的資料 select  malCode   from eam_run_malcode

Java Web系統初始化時資料庫中載入資料到文字(ibatis,spring)

有一些特殊情況,需要在系統初始化時載入一些配置屬性到本地文字中 web.xml <listener> <listener-class> org.springfra

JAVA實踐-mybatis中junit查詢無結果返回,資料庫查詢資料

問題如圖所示:用字元匹配查詢,junit無結果返回,但資料庫直接查詢是有資料的。 跟著程式碼一步步debug進去之後,發現最後的查詢語句,中文部分被替換成了“?”。說明是存在編碼問題,再回過頭看db.properties的設定: 請乖乖加上字元編碼限制: 新手所犯的低