導航:首頁 > 編程語言 > java導出excel報表

java導出excel報表

發布時間:2023-02-09 17:40:38

java中怎麼樣導出表到excel中

如果是JSP頁面要導出成excel,依靠javascript就可以實現了,具體你試試上面的代碼 <input type="button" value="保存為 Excel"> <script language="javascript">
function AllAreaExcel() {
var title; title=document.getElementsByTagName("table")[0].childNodes.item(0).childNodes(0).childNodes(0).innerText; alert(title); var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;

//從excel的第5行開始插入
oSheet.Range("A5").select;

oWB .Worksheets(1).Activate;
oSheet.Cells(3,1).Value=title; //在第3行插入報表頭
oWB.Worksheets(1).Range("A3:I3").merge(); // 合並單元格區域 A3:I3
oWB.Worksheets(1).Range("A3:I3").HorizontalAlignment=3; //居中對齊A3:I3
var sel=document.body.createTextRange();
sel.moveToElementText(table1); //table 的ID值
sel.select();
sel.execCommand("Copy");
oSheet.Paste();

oXL.Visible = true;
} </script>

⑵ java將數據導出excel計算其文件大小

熱門頻道

首頁

博客

研修院

VIP

APP

問答

下載

社區
推薦頻道

活動

招聘

專題
打開CSDN APP
Copyright © 1999-2020, CSDN.NET, All Rights Reserved

打開APP

大數據導出excel大小限制_java 導出Excel 大數據量,自己經驗總結! 原創
2020-12-19 01:58:16

weixin_39655377
碼齡5年
關注
分析導出實現代碼,XLSX支持:

/*** 生成XLSX,2007版本的excel,每個sheet無6.5W的行數限制,但是到了一定數量,可能內存溢出,

* 次方法適合在預計10W以下的數據導出時使用,本機測試,14W可以導出。列數量在8列左右

*

*@paramfileOut

* 輸出流

*@paramsheetMap

* 要設置的數據信息

*@throwsSQLException*/

public static voidcreateXSLXByResultSet(OutputStream fileOut, WriteXLSBean... beans)throwsSQLException {try{//重點 Workbook

Workbook wb = newXSSFWorkbook();for (int i = 0, len = beans.length; i < len; i++) {

WriteXLSBean xlsBean=beans[i];

Sheet sheet=wb.createSheet(xlsBean.getSheetName());

ResultSet rs=xlsBean.getRs();

ResultSetMetaData rsmd=rs.getMetaData();

TypeHandlerRegistry tr=BeanContext.tr;

Map th =xlsBean.getTh();int index = 0;while(rs.next()) {long t1 =System.currentTimeMillis();

org.apache.poi.ss.usermodel.Row row=sheet

.createRow(index);for (int j = 0, numberOfColumns = rsmd.getColumnCount(); j < numberOfColumns; j++) {

String key= rsmd.getColumnLabel(j + 1).toLowerCase();if(th.containsKey(key)) {

TypeHandler> type =tr.getTypeHandler(JdbcType

.forCode(rsmd.getColumnType(j+ 1)));

Object obj=type.getResult(rs, key);

row.createCell(j).setCellValue(obj== null ? "": obj.toString());

}

}

System.out.println(index+ " :"

+ (System.currentTimeMillis() -t1));

index++;

}

}//重點 Workbook

wb.write(fileOut);

}catch(IOException e) {

e.printStackTrace();throw new ServiceRunTimeException("生產xls文檔錯誤", e);

}finally{

}

}

在上面 標注了重點的兩處,分別是:

1.構建一個Excel對象

2.將該對象寫入一個OutPutStream

而在構建過程中,沒有地方寫入OutPutSteam ,也就是說必須在內存中構建整個 Excel,才能進行寫出操作,在大數據量情況下,這樣將導致所有數據載入到內存中,而不能輸出,導致最後 內存溢出。

根據運行環境不用,可能內存溢出的 情況不同

根據情況,如果數據量達到10W以上,建議使用

1、多個Excel,每個Excel一個Sheet,因為所有Sheet都是Workbook的組成部分。如果不分多個Excel,即使分Sheet也沒用,

2、每個Excel中列數適中,比如: 5W行每個Excel檔,實現分多次導出和分頁查詢原理一樣

3、對多個Excel導出到一個臨時目錄,並通過程序壓縮,然後提供給客戶下載

2003版通過資料庫結果存到List中,然後進行生產:Table 就是List Row 是Map

/*** 生產xls,2003版本的excel,每個sheet有6.5W的行數限制

*

*@paramfileOut

* 輸出流,未關閉

*@paramsheetMap

* 要導出的數據信息*/

public static void createXSLByMap(OutputStream fileOut, Map>>sheetMap) {try{

HSSFWorkbook wb= newHSSFWorkbook();

Set keys =sheetMap.keySet();for (Iterator iterator =keys.iterator(); iterator

.hasNext();) {

String SheetKey=iterator.next();

Sheet sheet=wb.createSheet(SheetKey);

List> sheetRows =sheetMap.get(SheetKey);for (int i = 0, len = sheetRows.size(); i < len; i++) {

Map cellMap =sheetRows.get(i);

Set cellSet =cellMap.keySet();

org.apache.poi.ss.usermodel.Row row=sheet.createRow(i);int j = 0;for (Iterator iterCell =cellSet.iterator(); iterCell

.hasNext(); j++) {

String cellKey=iterCell.next();

Object obj=cellMap.get(cellKey);

row.createCell(j).setCellValue(obj== null ? "": obj.toString());

}

}

}

wb.write(fileOut);

}catch(IOException e) {

e.printStackTrace();throw new ServiceRunTimeException("生產xls文檔錯誤", e);

}finally{

}

}

新版本 POI+office 2007版本excel可以導出幾十萬條而不內存溢出,詳細見:

導出大量數據到 excel 的 xlsx文件

static String src="SFGHJKJGHFERTUIO";

public static void main(String[] args) throwsThrowable {

SXSSFWorkbook wb = new SXSSFWorkbook(100); //這里100是在內存中的數量,如果大於此數量時,會寫到硬碟,以避免在內存導致內存溢出

Sheet sh =wb.createSheet();

for (int rownum = 0; rownum < 1000000; rownum++) {

Row row =sh.createRow(rownum);

for (int cellnum = 0; cellnum < 10; cellnum++) {

Cell cell =row.createCell(cellnum);

String address = newCellReference(cell).formatAsString();

cell.setCellValue(address+src.substring(rownum%10*10+1, (rownum%10+1)*10));

}

}

File file = new File("F:/aa.xlsx");

file.createNewFile();

FileOutputStream out = newFileOutputStream(file);

wb.write(out);

out.close();

}

內存使用情況:

根據以上前輩經驗,自己在結果自身需求考慮,整合出一個工具。解決了excle表.xls格式行數65535行的限制。我實現的形式是導出一張表,裡面有多頁

(我是已65000為一頁)

這里是用反射來使用所有傳入進行的實體的屬性的值。這里只針對String和基本數據類型。如有自己定義的類型需要自己加上。

packagecom.tommy.fundation.util;importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;public classRelectUtil {public static List reflectEntity(T model,Class> cals) throwsNoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchFieldException{

List list = new ArrayList();

Field[] field= model.getClass().getDeclaredFields(); //獲取實體類的所有屬性,返回Field數組

for(int j=0 ; j

String nam = field[j].getName(); //獲取屬性的名字

String name =nam;

name= name.substring(0,1).toUpperCase()+name.substring(1);

String type= field[j].getGenericType().toString(); //獲取屬性的類型

if(type.equals("class java.lang.String")){ //如果type是類類型,則前麵包含"class ",後面跟類名

Method m = model.getClass().getMethod("get"+name);

String value= (String) m.invoke(model); //調用getter方法獲取屬性值

if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Integer")){

Method m= model.getClass().getMethod("get"+name);

Integer value=(Integer) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Short")){

Method m= model.getClass().getMethod("get"+name);

Short value=(Short) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Double")){

Method m= model.getClass().getMethod("get"+name);

Double value=(Double) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Boolean")){

Method m= model.getClass().getMethod("get"+name);

Boolean value=(Boolean) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.util.Date")){

Method m= model.getClass().getMethod("get"+name);

Date value=(Date) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}

}returnlist;

}

}

下面將是重點實現導出excel表

packagecom.tommy.fundation.util;importjava.io.OutputStream;importjava.util.ArrayList;importjava.util.Date;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;importjavax.servlet.http.HttpServletResponse;importorg.apache.poi.hssf.record.formula.functions.T;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;

@SuppressWarnings("hiding")public class ExportExcel{/*** 導出多張excel表,解決xls格式行數65535的限制

*@authorOnlyOne

*@paramresponse

*@paramlist 需要處理的list數據集合

*@throwsException*/@SuppressWarnings("deprecation")public void doExcel(HttpServletResponse response,List list,String fileName) throwsException {

OutputStream os= response.getOutputStream();//獲取輸出流

response.reset();//設置下載頭部信息。Content-disposition為屬性名。attachment表示以附件方式下載,如果要在頁面中打開,則改為inline。filename為文件名

response.setHeader("Content-disposition", "attachment; filename=excell.xls");

response.setContentType("application/msexcel");

Map> sheetMap =daData(list);

HSSFWorkbook wb= newHSSFWorkbook();

Set keys =sheetMap.keySet();for (Iterator iterator =keys.iterator(); iterator.hasNext();) {

Integer SheetKey=iterator.next();

HSSFSheet sheet= wb.createSheet((fileName+SheetKey).toString());

List sheetRows =sheetMap.get(SheetKey);for (int i = 0, len = sheetRows.size(); i < len; i++) {

T en=(T) sheetRows.get(i);

List dataList = RelectUtil.reflectEntity(en, en.getClass());

HSSFRow row=sheet.createRow(i);

row.createCell(0).setCellValue(String.valueOf(i));for(int m=0; m

row.createCell(m+1).setCellValue(dataList.get(m).toString());

}

}

}

wb.write(os);

}/*** 此方法將數據集合按65000個進行分割成多個子集合

*@authorOnlyOne

*@paramlist 需要處理的list數據集合

*@return

*/

public Map> daData(Listlist){int count = list.size()/65000;int yu = list.size() % 65000;

Map> map = new HashMap>();for (int i = 0; i <= count; i++) {

List subList = new ArrayList();if (i ==count) {

subList= list.subList(i * 65000, 65000 * i +yu);

}else{

subList= list.subList(i * 65000, 65000 * (i + 1)-1);

}

map.put(i, subList);

}returnmap;

}

}

在Java中調用的方式

@RequestMapping(value = "/doExcel", method =RequestMethod.GET)public void doExcel(HttpServletResponse response,HttpServletRequest request) throwsException {

List list =enrolltgService.findAll();new ExportExcel().doExcel(response, list, "黑白淡奶");

}

大功搞成,以後再也不會為了數據量太大而導不出來煩惱了!!!

需要的包 poi-3.2-FINAL-20081019.jar

相關資源:poi讀取大文件Excel,使用xml格式解析,速度實測50mb文件13s,可指定...
打開CSDN,閱讀體驗更佳

POI多線程分表導出百萬級大數據量EXCEL導出_Zhuo_chao的博客-CSDN博 ...
由上面可知 Excel 2003及以下是無法實現單sheet百萬級的數據。 ApachePOI 簡介 Apache POI 是用Java編寫的免費開源的跨平台的 JavaAPI,Apache POI提供API給Java程式對Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式檔案讀和寫的功...
Java 使用POI導出數據到 excel,單 sheet 和多 sheet__修鐵路的的博客...
單sheet 和多 sheet,用到的jar都是一樣的,無非就是多創建一個 sheet的問題,以下是需要用到的jar包,在對應模塊的pom.xml 中引入即可 <dependency> <groupId>org.apache.poi</groupId> ...
java導出excel超出65533行
業務背景: 列表導出,數據導出超過65533行 解決方案: 1、超出65533行,直接系統提示:本系統支持導出的最大條數為65533行 2、導出模版改為.xlsx,POI導出時用XSSFWorkbook,把所有數據都拿到內存里,可以導出超過65533行,但是上線之後,發現會內存溢出 3、導出模版改為.xlsx,POI導出時用SXSSFWorkbook,每次往內存里放一定的數據,導完之後,刷新,再次...
繼續訪問
Java的poi導出的excel不能超過256列的解決辦法
Java的poi導出的excel不能超過256列的解決辦法背景1、現在的情況2、解決辦法 背景 1、現在的情況 excel文件名以.xls結尾 這個構造函數中默認採取這個類型 this.type = ExcelType.HSSF; public ExportParams(String title, String sheetName) { this.color = HSSFColorPredefined.WHITE.getIndex(); this.headerColor = HSSFC
繼續訪問
使用ApachePOI導出excel(多個sheet頁)_我是橘子京的博客
2、設置導出excel路徑 //導出的文件路徑 String filePath="D:\\excel.xls"; 1 2 3、創建excel文件 //創建Excel文件(Workbook) HSSFWorkbook workbook = new HSSFWorkbook(); 1 2 4、設置單元格樣式 //設置單元格樣式 HSSFCel...
POI3.8 導出大數據excel(50萬左右)_咖啡加糖_的博客_poi支持最...
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.streaming.SXSSFWorkbook; ...
最新發布 【JAVA問題解決方案】01.EasyExcel導出數據超過Excel單表上限解決方案
1.了解一下Excel單表最多存儲多少行數據(可以存儲1048576條數據,1024的平方,2的20次方)。本文是介紹EasyExcel導出數據超過Excel單表上限解決方案。2.知道最多多少行就能以這個數為條件,如果超過則進行分表。3.分表的同時需要對數據進行分割,才能不超過最大限度。實體類(非常簡單,為了導出表更快)
繼續訪問

java實現流輸出形式導出數據(使用EasyExcel)並打包為zip包
java實現流輸出形式文件下載並打包為zip包 pom.xml文件導入easyexcel <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.0.5</version> </d...
繼續訪問
...到excel文件(xls格式),附實驗結果(單張sheet最多可有65536行)& Fi...
使用POI導出MySQL資料庫數據到excel文件(xls格式) 注意事項:單張sheet最多存儲65536行!否則報錯! Caused by: java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535) !
使用Apache POI導出百萬條EXCEL數據_橙樂果果的博客
工作中,有這么一個需求:每天凌晨00:05分定時從資料庫導出大於三個月的訂單流水信息,保存為excel文件。 Just do it. 1.引入POM依賴 <!-- excel --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> ...
Linux下讀寫文件操作
Linux下讀寫文件操作 #include<stdio.h> typedef struct Student { int no; char name[10]; int score; }Student; int main(int args,char *argv[]) { //打開文件 FILE *fp=fopen("test.txt","w"); if(fp=NULL) { perror("fopen"); ...
繼續訪問
Java導出超大Excel文件,防止內存溢出
Java導出超大Excel文件,防止內存溢出1.採用Poi中的SXSSFWorkbook2.maven中引入Poi3.測試過程4.單元測試Java代碼5.結論 將業務數據導出到Excel表中,導出任務數據量較大時,導出的項目就會內存溢出,本文通過Java操作Poi的SXSSFWorkbook類進行導出,解決內存溢出問題。 1.採用Poi中的SXSSFWorkbook 在實現excel導出時,在數據量過大的情況下,總是容易發生內存溢出的情況。可以使用POI提供的 SXSSFWorkbook 類來避免內存溢
繼續訪問

Apache Poi導出Excel多Sheet頁詳解!_奧鵬馬的博客
apache poi是目前比較常用導出excel的方式。最近想要實現一個導出excel多sheet頁的功能。 網上查了一下大多都是針對某個具體對象的導出,不能實現任意對象的導出。現在將自己研究出的代碼貼出來,供大家參考。 //注意:此處實現的關鍵是將...
Apache poi 導出多sheet的excel表格_朋態圈的博客
導出多sheet的excel */public class ApachePoi { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub exportExcel();} @SuppressWarnings("resource") public static String exportExcel...
java導出excel限制大小_解決java poi導出excel2003不能超過65536行的問題
/*** 如果達到50000條數據則重新創建工作表的邏輯*/@Overridepublic void exportExcel(ListformList, ServletOutputStream outputStream){try{//工作表名後面的數字,如表1,表2int i = 0;//記錄總行數int rownum = 0;//記錄每個sheet的行數int tempnum = 0;//分頁條...
繼續訪問
熱門推薦 java poi 導出Excel 超大數據量解決方案
http://blog.csdn.net/qiaoshuai0920/article/details/51800991
繼續訪問
poi導出excel,實現一個excel中多個sheet(可解決poi導出限制65536的問題...
本文章的excel實現導出多個sheet是在上一篇poi導出的基礎上實現的,這么久了,對於上一篇文章的poi也作出過一些優化。 這里我只貼修改了的方法的代碼,其餘的和上一篇文章的一樣。 /** * 導出excel.在一個頁面中單獨導出Excel ...
基於Apache POI導出(百萬級)大數據量Excel的實現_一朵風中搖曳的水仙...
支持單個 excel 的 sheet 導出100w 的數據 ApachePOI操作Excel對象 1.HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不經過壓縮直接導出 2.XSSF:操作Excel 2007及之後版本(.xlsx)格式,內存佔用高於HSSF ...
解決POI的XSSFWorkbook導入大excel的內存消耗過大問題
方式1:使用SXSSFWorkbook ,經過測試,這個情況無效,因為本質上SXSSFWorkbook 也是通過XSSFWorkbook來的,他可以解決寫出excel的場景,但是解決不了我們這種用戶上傳且讀取excel中的內容的場景 XSSFWorkbook XSSFWorkbook = new XSSFWorkbook(fileInputStream); System.gc(); SXSSFWorkbook SXSSFWorkbook = new SXSS
繼續訪問
導入導出
原文地址:https://blog.csdn.net/qq_29631809/article/details/72785338 創建流程:(上級為 下級的載體) 1:.創建 工作簿 2.創建 sheet(可以創建多個) 3.創建行 4.創建單元格 接下來 分別說下 工作簿的常用三種形式的區別,他們分別是 1.HSSFWorkbook 2.XSSFWorkbook 3.SXSSFWork...
繼續訪問
NPOI導出Excel 65536限制
1 #region NPOI 導出excel數據超65535自動分表 2 /// <summary> 3 /// DataTable轉換成Excel文檔流,並輸出到客戶端 4 /// </summary> 5 /// <param name="table">...
繼續訪問
java導出csv文件 為解決導出excel時每個單元格的限制(32767)
此實現方法僅供參考 因為本人導出數據量不大所採取的方法 如數據量大,會到至內存溢出請知曉 在這還提下:導出時內容自己換行 只需在內容前尾各加雙引號就行。 如圖 1、准備導出工具類 // An highlighted block package com.test; import java.io.BufferedWriter; import java.io.File; import java.io...
繼續訪問
Excel單元格數據超過32767報錯問題處理
java poi 32767
繼續訪問
SXSSFWorkbook Excel 大量數據導出
注意 SXSSFWorkbook 用於大量數據的導出 SXSSFWorkbook是用來生成海量excel數據文件,主要原理是藉助臨時存儲空間生成excel, SXSSFWorkbook專門處理大數據,對於大型excel的創建且不會內存溢出的,就只SXSSFWorkbook了。 它的原理很簡單,用硬碟空間換內存(就像hashmap用空間換時間一樣)。 SXSSFWorkbook是streami...
繼續訪問
EXCEL大數據量導出的解決方案
將web頁面上顯示的報表導出到excel文件里是一種很常見的需求。然而,當數據量較大的情況下,excel本身的支持最多65535行數據的問題便凸顯出來。下面就給出大數據量導出到excel的解決方 案。 首先,對於數據超過了65535行的問題,很自然的就會想到將整個數據分塊,利用excel的多sheet頁的功能,將超出65535行後的數據寫入到下一個sheet頁中,即通過多sheet頁的方式,突破了...
繼續訪問
幾行代碼,復雜Excel 導入導出,真心強大!
點擊上方藍色字體,選擇「標星公眾號」優質文章,第一時間送達項目中使用:功能介紹IMPORT1、 ExcelHandle核心處理器;2、 ExcelWorkbookManageexcel所有工作表管理;3、 ExcelInitConfig配置文件初始化;4、 AbstractFileParser文件轉換類;alanpoi import有何優勢?1、 用戶不需要額外引入poi...
繼續訪問

java中poi導出excel問題總結
java中poi導出excel問題總結
繼續訪問
java POI導出excel,列數限制在256列
有兩篇文章寫得比較好的 https://www.oschina.net/code/snippet_1052786_47435 https://www.jianshu.com/p/4c6eec65fdc3
繼續訪問
apache poi導出excel最大多少個sheet
大數據導出excel大小限制
寫評論

評論

收藏

點贊



分享

⑶ java中怎麼把報表導出到excel

導入資料庫

	@RequestMapping("/uploadOrderFile")
@ResponseBody
publicObjectuploadOrderFile(HttpServletRequestrequest,HttpServletResponseresponse,@RequestParam(value="file")MultipartFile[]files)throwsServletException,IOException,ParseException{
Workbookrwb=null;
if(files!=null&&files.length>0){
try{
//StringfilePath=request.getSession().getServletContext().getRealPath("/")+"\uploadOrderFile\"+files.getOriginalFilename();
//System.out.println("----------"+filePath);
rwb=Workbook.getWorkbook(files[0].getInputStream());
Sheetrs=rwb.getSheet(0);//默認0是第一張表,或者rwb.getSheet(Sheet1)Excel要導入的表名
intclos=rs.getColumns();//得到所有的列
introws=rs.getRows();//得到所有的行
//存放Excel表抬頭名稱以及對應的列
Map<Integer,Object>map=newHashMap<Integer,Object>();
//實體類集合存放每次循環獲得的值
List<Medicine>medicineList=newArrayList<Medicine>();
for(inti=0;i<rows;i++){
//創建實體類
Medicinemedicine=newMedicine();
if(i==0){//遍歷第一行獲取抬頭跟對應的列
for(intj=0;j<clos;j++){//取得每個抬頭名稱對應的列
if(rs.getCell(j,i).getContents().equals("品名")){
map.put(j,"品名");
}elseif(rs.getCell(j,i).getContents().equals("商品編號")){
map.put(j,"商品編號");
}elseif(rs.getCell(j,i).getContents().equals("生產日期")){
map.put(j,"生產日期");
}elseif(rs.getCell(j,i).getContents().equals("產地")){
map.put(j,"產地");
}elseif(rs.getCell(j,i).getContents().equals("生產廠家")){
map.put(j,"生產廠家");
}elseif(rs.getCell(j,i).getContents().equals("批號")){
map.put(j,"批號");
}
}
}else{
//循環遍歷map》》》存的Excel表的抬頭名稱以及對應的列
for(intj=0;j<clos;j++){
if(map.get(j)==null){//如果=null進入下一個循環
continue;
}
if(map.get(j).equals("品名")){
//如果為空結束當前循環,進入下一個循環
if(rs.getCell(j,i).getContents()==null||rs.getCell(j,i).getContents().equals("")){
continue;
}
medicine.setMedicineName(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("商品編號")&&map.get(j)!=null){
//如果為空結束當前循環,進入下一個循環
if(rs.getCell(j,i).getContents()==null||rs.getCell(j,i).getContents().equals("")){
continue;
}
medicine.setMedicineCode(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("生產日期")&&map.get(j)!=null){
medicine.setCreateTime(rs.getCell(j,i).getContents());
if(rs.getCell(j,i).getContents()!=null&&!rs.getCell(j,i).getContents().equals("")){
//如果生產日期存在則+三年給到期日期賦值
//CommonUtil.getMedicineEffectiveTime為封裝好的類
medicine.setEffectTime(CommonUtil.getMedicineEffectiveTime(rs.getCell(j,i).getContents(),3));
}
}elseif(map.get(j).equals("產地")&&map.get(j)!=null){
medicine.setAddress(rs.getCell(j,i).getContents());

}elseif(map.get(j).equals("生產廠家")&&map.get(j)!=null){
medicine.setProcingArea(rs.getCell(j,i).getContents());

}elseif(map.get(j).equals("批號")&&map.get(j)!=null){
medicine.setBatchNumber(rs.getCell(j,i).getContents());
}
}
medicineList.add(medicine);//獲得的值放入集合中
}
}
//新增用到的list
List<Medicine>addList=newArrayList<Medicine>();
//修改用到的list
List<Medicine>updateList=newArrayList<Medicine>();
//導入數據
for(inti=0;i<medicineList.size();i++){
//判斷商品編號是否存在
if(medicineService.selectMedicineCode(medicineList.get(i).getMedicineCode()).size()>0){
//如果存在則修改
updateList.add(medicineList.get(i));
}else{
addList.add(medicineList.get(i));
}
}
intupdate=0;
intadd=0;
if(updateList!=null&&updateList.size()>0){
update=medicineService.updateMedicine(updateList);
}
if(addList!=null&&addList.size()>0){
add=medicineService.addMedicine(addList);
}
if(update>0||add>0){
returnnewResponseModel().attr(ResponseModel.KEY_DATA,"數據導入成功!");
}else{
returnnewResponseModel().attr(ResponseModel.KEY_ERROR,"數據導入失敗!");
}
}catch(BiffExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}

}else{
returnnewResponseModel().attr(ResponseModel.KEY_ERROR,"沒有需要導入的數據!");
}
returnnull;
}

導出

packagebeans.excel;

importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Calendar;
importjava.util.Date;

importjxl.Workbook;
importjxl.format.Colour;
importjxl.format.UnderlineStyle;
importjxl.write.Boolean;
importjxl.write.DateFormats;
importjxl.write.DateTime;
importjxl.write.Label;
importjxl.write.Number;
importjxl.write.WritableCellFormat;
importjxl.write.WritableFont;
importjxl.write.WritableSheet;
importjxl.write.WritableWorkbook;
importjxl.write.WriteException;

{
publicvoidcreateExcel(OutputStreamos)throwsWriteException,IOException{
//創建工作薄
WritableWorkbookworkbook=Workbook.createWorkbook(os);
//創建新的一頁
WritableSheetsheet=workbook.createSheet("FirstSheet",0);
//構造表頭
sheet.mergeCells(0,0,4,0);//添加合並單元格,第一個參數是起始列,第二個參數是起始行,第三個參數是終止列,第四個參數是終止行
WritableFontbold=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//設置字體種類和黑體顯示,字體為Arial,字型大小大小為10,採用黑體顯示
=newWritableCellFormat(bold);//生成一個單元格樣式控制對象
titleFormate.setAlignment(jxl.format.Alignment.CENTRE);//單元格中的內容水平方向居中
titleFormate.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//單元格的內容垂直方向居中
Labeltitle=newLabel(0,0,"JExcelApi支持數據類型詳細說明",titleFormate);
sheet.setRowView(0,600,false);//設置第一行的高度
sheet.addCell(title);

//創建要顯示的具體內容
WritableFontcolor=newWritableFont(WritableFont.ARIAL);//選擇字體
color.setColour(Colour.GOLD);//設置字體顏色為金黃色
WritableCellFormatcolorFormat=newWritableCellFormat(color);
Labelformate=newLabel(0,1,"數據格式",colorFormat);
sheet.addCell(formate);
Labelfloats=newLabel(1,1,"浮點型");
sheet.addCell(floats);
Labelintegers=newLabel(2,1,"整型");
sheet.addCell(integers);
Labelbooleans=newLabel(3,1,"布爾型");
sheet.addCell(booleans);
Labeldates=newLabel(4,1,"日期格式");
sheet.addCell(dates);

Labelexample=newLabel(0,2,"數據示例",colorFormat);
sheet.addCell(example);
//浮點數據
//設置下劃線
WritableFontunderline=newWritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.NO_BOLD,false,UnderlineStyle.SINGLE);
=newWritableCellFormat(underline);
greyBackground.setBackground(Colour.GRAY_25);//設置背景顏色為灰色
Numbernumber=newNumber(1,2,3.1415926535,greyBackground);
sheet.addCell(number);
//整形數據
WritableFontboldNumber=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//黑體
=newWritableCellFormat(boldNumber);
Numberints=newNumber(2,2,15042699,boldNumberFormate);
sheet.addCell(ints);
//布爾型數據
Booleanbools=newBoolean(3,2,true);
sheet.addCell(bools);
//日期型數據
//設置黑體和下劃線
WritableFontboldDate=newWritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD,false,UnderlineStyle.SINGLE);
=newWritableCellFormat(boldDate,DateFormats.FORMAT1);
Calendarc=Calendar.getInstance();
Datedate=c.getTime();
DateTimedt=newDateTime(4,2,date,boldDateFormate);
sheet.addCell(dt);
//把創建的內容寫入到輸出流中,並關閉輸出流
workbook.write();
workbook.close();
os.close();

}
}

⑷ java怎麼實現導出excel

偶將最近寫了兩個導出excel的方法,第一個是面向過程的思路,就是在指定的單元格寫入指定的值,如下:
/**
*負責數據導入到EXCEL
*
* @param realPath
* EXCEL表格存放的絕對路徑
* @param sheetname
*
* @param xLocation
* EXCEL表格的行索引,從1開始
* @param yLocation
* EXCEL表格的列索引,從1開始
* @param value
* 需要導入的數據
*
*/
public void modifyExcel(String realPath,String sheetname,int xLocaion,int yLocation,String value){
POIFSFileSystem fs=null;
HSSFWorkbook wb=null;
try {
File file=new File(realPath);
if(file.exists()){
fs = new POIFSFileSystem(new FileInputStream(realPath));
wb=new HSSFWorkbook(fs);
HSSFSheet s=wb.getSheetAt(0);
//函數處理時橫縱坐標從索引0開始
HSSFRow row=s.getRow(xLocaion-1);
HSSFCell cell=null;
if(row!=null){
cell=row.getCell(yLocation-1);
if(cell==null){
cell=row.createCell(yLocation-1);
}
}else{
row=s.createRow(xLocaion-1);
cell=row.createCell(yLocation-1);
}

cell.setCellValue(value);

}else{
wb=new HSSFWorkbook();
HSSFSheet s=wb.createSheet();
wb.setSheetName(0, sheetname);
HSSFRow row=s.createRow(xLocaion-1);
HSSFCell cell=row.createCell(yLocation-1);
cell.setCellValue(value);
}
FileOutputStream fos=new FileOutputStream(realPath);
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

第二種就是運用了對象,以對象為單位寫入數據,即一個對象的所有屬性在一行列出,有多少個對象就有多少行,此方法比較適用於個人信息導出之類的應用,至於導出屬性的順序問題在導出對象的實體類內部改動下即可:
/**
*負責數據導入到EXCEL
*
* @param realPath
* EXCEL表格存放的絕對路徑
* @param sheetname
*
* @param users
* 需要導出到excel表的對象數組
*/
public void outputExcel(String realPath,String sheetname,UserModel[] users){
FileOutputStream fos;
try {
File file=new File(realPath);

fos = new FileOutputStream(file, true);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s=wb.createSheet();
wb.setSheetName(0, sheetname);
HSSFRow[] rows=new HSSFRow[users.length];
HSSFCell[][] cells=new HSSFCell[20][20];
for (int i=0; i<users.length;i++) { // 相當於excel表格中的總行數
PropertyDescriptor[] descriptors=(users[i]);
rows[i]=s.createRow(i);
for (int j=0; descriptors!=null&&j<descriptors.length;j++) {
java.lang.reflect.Method readMethod = descriptors[j]
.getReadMethod();
cells[i][j]=rows[i].createCell(j);
Object value=readMethod.invoke(users[i], null);
cells[i][j].setCellValue(value.toString());

}

}
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

}

⑸ java導出excel圖表

通過Java程序導出帶圖表的excel嗎?參考下面用spire.xls.jar來創建Excel圖表的方法,這里以創建餅圖為例,當然你也可以指定創建其他圖表類型,如柱狀圖、折線圖、雷達圖、散點圖等等:

import com.spire.xls.*;

import com.spire.xls.charts.ChartSerie;

import java.awt.*;

public class CreatePieChart {

public static void main(String[] args) {

//創建Workbook對象

Workbook workbook = new Workbook();

//獲取第一個工作表

Worksheet sheet = workbook.getWorksheets().get(0);

//將圖表數據寫入工作表

sheet.getCellRange("A1").setValue("年份");

sheet.getCellRange("A2").setValue("2002");

sheet.getCellRange("A3").setValue("2003");

sheet.getCellRange("A4").setValue("2004");

sheet.getCellRange("A5").setValue("2005");

sheet.getCellRange("B1").setValue("銷售額");

sheet.getCellRange("B2").setNumberValue(4000);

sheet.getCellRange("B3").setNumberValue(6000);

sheet.getCellRange("B4").setNumberValue(7000);

sheet.getCellRange("B5").setNumberValue(8500);

//設置單元格樣式

sheet.getCellRange("A1:B1").setRowHeight(15);

sheet.getCellRange("A1:B1").getCellStyle().setColor(Color.darkGray);

sheet.getCellRange("A1:B1").getCellStyle().getExcelFont().setColor(Color.white);

sheet.getCellRange("A1:B1").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);

sheet.getCellRange("A1:B1").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);

sheet.getCellRange("B2:C5").getCellStyle().setNumberFormat(""¥"#,##0");

//添加餅圖

Chart chart = sheet.getCharts().add(ExcelChartType.Pie);

//設置圖表數據區域

chart.setDataRange(sheet.getCellRange("B2:B5"));

chart.setSeriesDataFromRange(false);

//設置圖表位置

chart.setLeftColumn(3);

chart.setTopRow(1);

chart.setRightColumn(11);

chart.setBottomRow(20);

//設置圖表標題

chart.setChartTitle("年銷售額");

chart.getChartTitleArea().isBold(true);

chart.getChartTitleArea().setSize(12);

//設置系列標簽

ChartSerie cs = chart.getSeries().get(0);

cs.setCategoryLabels(sheet.getCellRange("A2:A5"));

cs.setValues(sheet.getCellRange("B2:B5"));

cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);

chart.getPlotArea().getFill().setVisible(false);

//保存文檔

workbook.saveToFile("output/PieChart.xlsx", ExcelVersion.Version2016);

}

}

餅圖創建效果:

excel餅狀圖效果

⑹ 怎麼用java實現導出excel

/**
*@authorliuwu
* Excel的導入與導出
*/
@SuppressWarnings({"unchecked"})
publicclassExcelOperate{
/**
*@authorliuwu
*這是一個通用的方法,利用了JAVA的反射機制,
*可以將放置在JAVA集合中並且符合一定條件的數據以EXCEL的形式輸出到指定IO設備上
*@paramtitle表格標題名
*@paramheaders表格屬性列名數組
*@paramdataset需要顯示的數據集合,集合中一定要放置符合javabean風格的類的對象。
* 此方法支持的javabean屬性【數據類型有java基本數據類型及String,Date,byte[](圖片轉成位元組碼)】
*@paramout與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網路中
*@parampattern如果有時間數據,設定輸出格式。默認為"yyy-MM-dd"
*@throwsIOException
*/
publicstaticvoidexportExcel(Stringtitle,String[]headers,Collection<?>dataset,OutputStreamout,Stringpattern)throwsIOException{
//聲明一個工作薄
HSSFWorkbookworkbook=newHSSFWorkbook();
//生成一個表格
HSSFSheetsheet=workbook.createSheet(title);
//設置表格默認列寬度為15個位元組
sheet.setDefaultColumnWidth((short)20);
//生成一個樣式
HSSFCellStylestyle=workbook.createCellStyle();
//設置這些樣式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成一個字體
HSSFFontfont=workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short)12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//把字體應用到當前的樣式
style.setFont(font);
//生成並設置另一個樣式
HSSFCellStylestyle2=workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//生成另一個字體
HSSFFontfont2=workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//把字體應用到當前的樣式
style2.setFont(font2);
//產生表格標題行
HSSFRowrow=sheet.createRow(0);
for(shorti=0;i<headers.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextStringtext=newHSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍歷集合數據,產生數據行
Iterator<?>it=dataset.iterator();
intindex=0;
while(it.hasNext()){
index++;
row=sheet.createRow(index);
Objectt=it.next();
//利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
Field[]fields=t.getClass().getDeclaredFields();
for(shorti=0;i<fields.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style2);
Fieldfield=fields[i];
StringfieldName=field.getName();
StringgetMethodName="get"
+fieldName.substring(0,1).toUpperCase()
+fieldName.substring(1);//注意實體getSet不要自己改名字不然反射會有問題
try{
ClasstCls=t.getClass();
MethodgetMethod=tCls.getMethod(getMethodName,newClass[]{});
Objectvalue=getMethod.invoke(t,newObject[]{});
HSSFRichTextStringrichString=newHSSFRichTextString(value.toString());
HSSFFontfont3=workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}catch(SecurityExceptione){
e.printStackTrace();
e=null;
}catch(NoSuchMethodExceptione){
e.printStackTrace();
e=null;
}catch(IllegalArgumentExceptione){
e.printStackTrace();
e=null;
}catch(IllegalAccessExceptione){
e.printStackTrace();
e=null;
}catch(InvocationTargetExceptione){
e.printStackTrace();
e=null;
}finally{
//清理資源
}
}
}
try{
workbook.write(out);
}catch(IOExceptione){
e.printStackTrace();
e=null;
}
}
}

⑺ java怎麼導出excel表格

可以使用POI開源的api:
1.首先下載poi-3.6-20091214.jar,下載地址如下:
http://download.csdn.net/detail/evangel_z/3895051

2.Student.java

import java.util.Date;

public class Student
{
private int id;
private String name;
private int age;
private Date birth;

public Student()
{
}

public Student(int id, String name, int age, Date birth)
{
this.id = id;
this.name = name;
this.age = age;
this.birth = birth;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

public Date getBirth()
{
return birth;
}

public void setBirth(Date birth)
{
this.birth = birth;
}

}
3.CreateSimpleExcelToDisk.java

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

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

public class CreateSimpleExcelToDisk
{
/**
* @功能:手工構建一個簡單格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "張三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);

return list;
}

public static void main(String[] args) throws Exception
{
// 第一步,創建一個webbook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("學生表一");
// 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,創建單元格,並設置值表頭 設置表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式

HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("學號");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("年齡");
cell.setCellStyle(style);
cell = row.createCell((short) 3);
cell.setCellValue("生日");
cell.setCellStyle(style);

// 第五步,寫入實體數據 實際應用中這些數據從資料庫得到,
List list = CreateSimpleExcelToDisk.getStudent();

for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,創建單元格,並設置值
row.createCell((short) 0).setCellValue((double) stu.getId());
row.createCell((short) 1).setCellValue(stu.getName());
row.createCell((short) 2).setCellValue((double) stu.getAge());
cell = row.createCell((short) 3);
cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
.getBirth()));
}
// 第六步,將文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/students.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

⑻ java導出excel

java導出Excel

java 代碼 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.serv ...

java導出Excel例舉方式
方法一:導出Excel數據的插件jexcelapi

程序實例如下:
public void exportClassroom(OutputStream os) throws PaikeException {

try {
WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件
WritableSheet wsheet = wbook.createSheet("教室信息表", 0); //工作表名稱
//設置Excel字體
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,
WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
WritableCellFormat titleFormat = new WritableCellFormat(wfont);
String[] title = { "教室名", "容 量", "類 型", "其他說明" };
//設置Excel表頭
for (int i = 0; i < title.length; i++) {
Label excelTitle = new Label(i, 0, title[i], titleFormat);
wsheet.addCell(excelTitle);
}
int c = 1; //用於循環時Excel的行號
ClassroomService cs = new ClassroomService();
List list = cs.findAllClassroom(); //這個是從資料庫中取得要導出的數據
Iterator it = list.iterator();
while (it.hasNext()) {
ClassroomDTO crdto = (ClassroomDTO) it.next();
Label content1 = new Label(0, c, crdto.getRoomname());
Label content2 = new Label(1, c, crdto.getCapicity().toString());
Label content3 = new Label(2, c, crdto.getRoomTypeId()
.toString());
Label content4 = new Label(3, c, crdto.getRemark());
wsheet.addCell(content1);
wsheet.addCell(content2);
wsheet.addCell(content3);
wsheet.addCell(content4);
c++;
}

wbook.write(); //寫入文件
wbook.close();
os.close();
} catch (Exception e) {

throw new PaikeException("導出文件出錯");

}

}

方法二:直接用Java代碼實現導出Excel報表

/*

* Generated by MyEclipse Struts

* Template path: templates/java/JavaClass.vtl

*/

package com.axon.fable.sams.view.action;

import java.io.IOException;

import java.io.OutputStream;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

import com.axon.fable.empolderpackage.out.OutJavaScript;

import com.axon.fable.empolderpackage.page.Pager;

import com.axon.fable.empolderpackage.string.MyPublic;

import com.axon.fable.sams.common.BaseAction;

import com.axon.fable.sams.exception.AppBusinessException;

import com.axon.fable.sams.exception.AppSystemException;

/**

* MyEclipse Struts

* Creation date: 06-28-2007

*

* XDoclet definition:

* @struts.action path="/axon" name="axonForm" input="/samspage/zm/axon.jsp" parameter="method" scope="request" validate="true"

* @struts.action-forward name="success" path="/samspage/zm/content.jsp"

*/

public class StshipoperationAction extends BaseAction {

/*

* Generated Methods

*/

private static Session session=null;

private static Transaction ts=null;

private static Query queryC=null;

private static Query queryR=null;

private static Query query=null;

private static List list=null;

private static Integer startRow;

private static Integer ncurrentPage;

private static Integer cell;

private static String property;

private static String sql;

private static String type;

private static String condition ;//是否導出當前頁

private static String currentPage;

private static String from ;

private static String pactdata;

private static String voyagename;

private static String voyageno;

private static String dwt ;

private static String hirefrom ;

private static String deliveryposion ;

private static String redeliveryposion ;

private static String sheepowner ;

private static String addr;

private static String addcomm;

private static String rent;

private static String fileName ;

private static OutputStream os;

@Override

public ActionForward findAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

@Override

public ActionForward findById(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

@Override

public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

public static String strNull(Object nullStr,String newStr,Integer cell){

if(nullStr==null||nullStr.equals("")){return newStr;}else{cell+=1;return nullStr+"";}

}

public static String getStr(String str,Integer cell){

if(str==null||str.trim().equals("")){return "";}else{cell+=1;return ","+str;}

}

public static String getExcelTile(String title){

if(title==null)

return "";

if(title.equals("modela.stsid"))

return "編號";

if(title.equals("modelc.pactdata"))

return "合同日期";

if(title.equals("modela.voyagename"))

return "航名";

if(title.equals("modela.voyageno"))

return "航次";

if(title.equals("modelc.dwt"))

return "DWT";

if(title.equals("modelc.hirefrom"))

return "受載期";

if(title.equals("modela.deliveryposion"))

return "交船地點";

if(title.equals("modela.redeliveryposion"))

return "還船地點";

if(title.equals("modelc.sheepowner"))

return "聯系人";

if(title.equals("modelc.addr"))

return "經紀人擁金";

if(title.equals("modelc.addcomm"))

return "ADD COMM";

if(title.equals("modelc.rent"))

return "租金";

return "";

}

public ActionForward exporVoyagesInfoToExcel(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

list=null;

startRow=0;

ncurrentPage=1;

cell=0;

type =request.getParameter("type");

condition =request.getParameter("condition");//是否導出當前頁

currentPage =request.getParameter("currentPage");

from =request.getParameter("from");

pactdata = request.getParameter("modelc.pactdata");

voyagename = request.getParameter("modela.voyagename");

voyageno = request.getParameter("modela.voyageno");

dwt = request.getParameter("modelc.dwt");

hirefrom = request.getParameter("modelc.hirefrom");

deliveryposion = request.getParameter("modela.deliveryposion");

redeliveryposion = request.getParameter("modela.redeliveryposion");

sheepowner = request.getParameter("modelc.sheepowner");

addr = request.getParameter("modelc.addr");

addcomm = request.getParameter("modelc.addcomm");

rent = request.getParameter("modelc.rent");

if(type!=null&&type.trim().equals("1")){

type ="已還船舶--費用未結清";

}else{

type ="已還船舶--費用已結清";

}

property =getStr(pactdata,cell)+getStr(voyagename,cell)+getStr(voyageno,cell)+getStr(dwt,cell)+getStr(hirefrom,cell)

+getStr(deliveryposion,cell)+getStr(redeliveryposion,cell)+getStr(sheepowner,cell)+getStr(addr,cell)+getStr(addcomm,cell)

+getStr(rent,cell);

property = property.substring(1);

String split[] = property.split(",");

// System.out.println("-----------------------------property:"+property);

if(currentPage!=null&&!currentPage.trim().equals("")){

ncurrentPage =Integer.parseInt(currentPage);

}else{

OutJavaScript.outString(response, "Sorry! Failed to get information of pager.");

return null;

}

try {

session =getServiceLocator().getBaseHibernateDAO().getSession();

sql ="select count(*) "+from;

query =session.createQuery(sql);

list = query.list();

for (int i = 0; i < list.size(); i++) {

totalSize =(Integer)list.get(i);

if(totalSize!=0){

pager =new Pager(ncurrentPage,totalSize);

}

}

query =getServiceLocator().getBaseHibernateDAO().getSession().createQuery("select " +property+from);

if(condition!=null&&condition.trim().equals("1")){//分頁數據

startRow = (ncurrentPage - 1)*pager.getPageSize();

query.setFirstResult(startRow);

query.setMaxResults(pager.getPageSize());

// System.out.println("---------------------------------------------------query:"+query);

}

list = query.list();

fileName = "shipInfo";

os = response.getOutputStream();

response.reset();

response.setHeader("Content-disposition",

"attachment; filename=" +fileName + ".xls");

response.setContentType("application/msexcel");

jxl.write.WritableWorkbook wbook = Workbook.createWorkbook(os);

jxl.write.WritableSheet wsheet = wbook.createSheet("the first sheet", 0);

for (int i = 0; i < split.length; i++) {

jxl.write.Label wlabel0;

wlabel0 = new jxl.write.Label(i, 0, getExcelTile(split[i]));

wsheet.addCell(wlabel0);

}

jxl.write.Label wlabel1;

for(int i=0;i<list.size();i++) {

if(split.length==1){

Object strval = (Object) list.get(i);

String javaScript=""+MyPublic.toHtmlStr(strval==null?"":strval.toString().trim())+"";

wlabel1 = new jxl.write.Label(0, i+1,strval==null?"":strval.toString().trim() );

wsheet.addCell(wlabel1);

}else{

Object[] strval = (Object[]) list.get(i);

for(int j=0;j<strval.length;j++) {

String javaScript=""+MyPublic.toHtmlStr(strval[j]==null?"":strval[j].toString().trim())+"";

//System.out.println("===================script:"+javaScript);

wlabel1 = new jxl.write.Label(j, i+1,strval[j]==null?"":strval[j].toString().trim() );

wsheet.addCell(wlabel1);

}

}

}

wbook.write();

response.flushBuffer();

wbook.close();

os.close();

} catch (IOException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

} catch (HibernateException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Database exception.");

e1.printStackTrace();

} catch (AppSystemException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! System exception.");

e1.printStackTrace();

} catch (AppBusinessException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Database exception.");

e1.printStackTrace();

} catch (RowsExceededException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

} catch (WriteException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

}

return null;

}

@Override

public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

}

還有其他很多種 字數限制 無法一一舉例方式

閱讀全文

與java導出excel報表相關的資料

熱點內容
安卓怎麼下載正版刺激戰場 瀏覽:235
xrv本田壓縮比 瀏覽:63
空調耗電量手機app怎麼看 瀏覽:723
伺服器怎麼登錄u8 瀏覽:909
明星pdf 瀏覽:270
判斷手機訪問php 瀏覽:119
appstory怎麼設密碼 瀏覽:798
程序員月薪3萬 瀏覽:261
flash反編譯覆蓋碼怎麼找 瀏覽:196
女大男小忘年戀題材電影 瀏覽:83
築業軟體如何查找加密鎖 瀏覽:114
電信盒子系統升級伺服器地址 瀏覽:584
海康威視伺服器如何設置dns 瀏覽:911
空調壓縮機檢測方法 瀏覽:529
程序員的工資多少錢啊 瀏覽:966
faka.369kuai。com/details/022D34D2 瀏覽:626
主角一開始是個小孩子的小說 瀏覽:568
為什麼安卓手機拍抖音沒有蘋果好 瀏覽:367
關鍵點pdf 瀏覽:535
linuxpython版本查看 瀏覽:242