`
tanglei198577
  • 浏览: 60240 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

Export the excel/txt file of report list by java

    博客分类:
  • java
阅读更多

First of all, we should click a button or some pic to trigger the action of exporting,here I used a button:

<input type="button" value="Export" onclick="export()" class="buttoncss"/>

Then the export function should like:

window.location.href="*.do?method=exportList"

 whick the method used for achieve the data that need exported.

List excelList = getPrintService().queryTask(ref, type, taskName,level);//data content
List<String> listHeader = new ArrayList<String>();//head of the data
listHeader.add("Reference");
listHeader.add("TaskName");
request.setAttribute("listHeader", listHeader);
request.setAttribute("excelList", excelList);

 then mapping this action to this jsp:

<%@page language="java" import="java.util.List, com.alba.util.ExcelBean, com.alba.util.DateUtil" pageEncoding="UTF-8" %> 
<% 
	response.setContentType("text/plain");//set as a txt document
	response.setHeader("Content-Disposition", "attachment;filename=" + 
		new String(("PrintTask_" + 
				DateUtil.formatFullDate(new java.util.Date().getTime()) + ".txt").getBytes(), "iso-8859-1"));//save as a attachment 
	ExcelBean eb = new ExcelBean();
	List<String> listHeader= (List<String>)request.getAttribute("listHeader");
	List excelList= (List)request.getAttribute("excelList");
	try{
		eb.exportTask(response.getOutputStream(),excelList,listHeader);//exporting method
	}catch(Exception e){
		e.printStackTrace();
	}
	
	out.clear();
	out = pageContext.pushBody();//save the object 'Out' and refresh
%>

 then the exportTask method is:

public void exportTask(OutputStream os,List excelList,List<String> listHeader){
		OutputStreamWriter fw = new OutputStreamWriter(os);
		StringBuffer row = null;
		if(fw != null){
			row = new StringBuffer();
			for(int i=0;i<listHeader.size();i++){
				if(i!=listHeader.size()-1){
					row.append(listHeader.get(i)+"\t");
				}else{
					row.append(listHeader.get(i)+"\n");
				}
			}
            try {
				fw.write(row.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			//add the contend
			if(excelList!=null&&excelList.size()>0){
				for(int i=0;i<excelList.size();i++){
						row = new StringBuffer();
						PrintTask task = (PrintTask) excelList.get(i);
							String reference = task.getProjectprint().getProject().getReference()!=null?task.getProjectprint().getProject().getReference()+"\t":"\t";
							String level = getLevelValue(task.getLevel()!=null?task.getLevel():0);
							String status = getStatusValue(task.getProjectprint().getStatus()!=null?task.getProjectprint().getStatus():10);
							
							row.append(reference)
							   .append(task.getTaskname()!=null?task.getTaskname()+"\t":"\t")
							   .append(task.getProjectprint().getType()!=null?task.getProjectprint().getType()+"\t":"\t")
							   .append(task.getProjectprint().getDestination()!=null?task.getProjectprint().getDestination()+"\t":"\t")
							   .append(task.getProjectprint().getProject().getDescription()!=null?task.getProjectprint().getProject().getDescription()+"\t":"\t")
							   .append(task.getProjectprint().getProject().getPlanWeekToShow()!=null?task.getProjectprint().getProject().getPlanWeekToShow()+"\t":"\t")
							   .append(level+"\t")
							   .append(task.getNeededtime()!=null?task.getNeededtime()+"\t":"\t")
							   .append(status+"\n");
							 try {
									fw.write(row.toString());
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
							}
					}
		  }
		try {
			fw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   }
	}

 when we want  to export as a excel file,we can use this method and do some changes like export txt file is ok:

public void exportExcelByJxl(List excelList,List<String> listHeader){
		WritableWorkbook wwb = null;
		try {
			File fileName = new File("d:/PrintList/");
			if(!fileName.exists()){
				fileName.mkdirs();
			}
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
			wwb = Workbook.createWorkbook(new File("d:/PrintList/PrintList"+sdf.format(date)+".xls"));		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		//add the header
		if(wwb != null){
			WritableSheet ws = wwb.createSheet("test", 0);
			for(int i=0;i<listHeader.size();i++){
				Label labelC = new Label(i, 0, listHeader.get(i));
				try {
					ws.addCell(labelC);
				} catch (RowsExceededException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (WriteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		
			//add the contend
			if(excelList!=null&&excelList.size()>0){
				for(int i=0;i<excelList.size();i++){
					for(int j=0;j<listHeader.size();j++){
						ProjectPrint print = (ProjectPrint) excelList.get(i);	
						Label labelC = null;
						
						if(print == null){
							labelC = new Label(j,i+1,"");
						}else{
							String reference = "";
							String cusName = "";
							String mark = getMarkValue(print.getMarked());
							String revise = getReviseValue(print.getRevised());
							String status = getStatusValue(print.getStatus());
							if(print.getMarked()!=2){
								reference = print.getProject().getReference()!=null?print.getProject().getReference():"";
								cusName = print.getProject().getCustomerName()!=null?print.getProject().getCustomerName():"";
							}
							switch(j){
							  case 0 : labelC = new Label(j,i+1,print.getId()!=null? print.getId()+"" :"");break;
							  case 1 : labelC = new Label(j,i+1,reference);break;
							  case 2 : labelC = new Label(j,i+1,print.getType()!=null?print.getType():"");break;
							  case 3 : labelC = new Label(j,i+1,print.getInkMaterial1()!=null?print.getInkMaterial1():"");break;
							  case 4 : labelC = new Label(j,i+1,print.getSurfaceMaterial()!=null?print.getSurfaceMaterial():"");break;
							  case 5 : labelC = new Label(j,i+1,print.getProject().getPlanWeekToShow()!=null?print.getProject().getPlanWeekToShow():"");break;
							  case 6 : labelC = new Label(j,i+1,cusName);break;
							  case 7 : labelC = new Label(j,i+1,print.getProject().getDescription()!=null?print.getProject().getDescription():"");break;
							  case 8 : labelC = new Label(j,i+1,print.getNumberofPage()!=null?print.getNumberofPage()+"":"");break;
							  case 9 : labelC = new Label(j,i+1,mark);break;
							  case 10 : labelC = new Label(j,i+1,revise);break;
							  case 11 : labelC = new Label(j,i+1,status);break;
							  default : break;
							}
						}
						
						try {
							ws.addCell(labelC);
						} catch (RowsExceededException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (WriteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			try {
				wwb.write();
				wwb.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WriteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   }
	}

 

0
0
分享到:
评论
2 楼 tanglei198577 2011-01-10  
楚天阔 写道
Tom。。。。

1 楼 楚天阔 2011-01-10  
Tom。。。。

相关推荐

    ExcelUtils-2.00.zip

    ExcelUtils is a helper to export excel report in java web project. It's like velocity, has own tags, but these tags is written in excel file. By these tags, you can custom your excel report format ...

    plsqldev14.0.0.1961x32多语言版+sn.rar

    You also can enter the filter expression directly at the top of the File Browser All windows shell functions are now available from the popup menu. You can now create a specific PL/SQL Developer file ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    + added export of Excel formulas in the BIFF export + added export of external URLs in the PDF export + added converter from Rave Reports ConverterRR2FR.pas + added Cross.KeepRowsTogether property + ...

    plsqldev14.0.0.1961x64多语言版+sn.rar

    You also can enter the filter expression directly at the top of the File Browser All windows shell functions are now available from the popup menu. You can now create a specific PL/SQL Developer file ...

    FastReport 4.9

    - fixed bug with setting up of the Protection Flags in the PDF export dialog window - fixed bug in PDF export (file structure) - fixed bug with pictures in Open Office Writer (odt) export - ...

    2009 达内Unix学习笔记

    ls -l (list)列表显示文件(默认按文件名排序), 显示文件的权限、硬链接数(即包含文件数,普通文件是1,目录1+)、用户、组名、大小、修改日期、文件名。 ls -t (time)按修改时间排序,显示目录和文件。 ls -lt 是...

    Fast Report Enterprise v4.9.32 Full Source

    - fixed bug with setting up of the Protection Flags in the PDF export dialog window - fixed bug in PDF export (file structure) - fixed bug with pictures in Open Office Writer (odt) export - ...

    PLSQL.Developer v11.0.0.1762 主程序+ v10中文包+keygen

    When the read-only status of a file changes this will be propagated to a window associated with that file The logon form now has shortcuts for all fields, is sizeable to show long database names in ...

    ireport导出excel 部分源码

    exporter.exportReport(); ``` ### 总结 通过上述分析可以看出,iReport及其Java API提供了丰富的功能来支持报表的设计和导出工作。无论是简单的文本报表还是复杂的包含图表和图像的报表,都可以通过适当的方法来...

    myBase Desktop 6.3.3 12/1/2013 绿色 完美破解版

    Added: a progress indicator to report import/export specific operations during dragging-and-dropping a large number of info items across different databases. Added: The viewer program is now shiped ...

    CE中文版-启点CE过NP中文.exe

    If you encounter bugs or have suggestions, please do not hesitate to report them in the forum, bugtracker or by e-mail. And if you have questions, don't hesitate to ask them in the forum Fixes: Fixed...

    PLSQL.Developer v11.0.4.1774 主程序+ v11中文包+keygen

    The file format encoding preference "Always as UTF8" did not work for the Program Window Crash recovery saved per InstanceName parameter value Shortcut key assigned to object functions could insert a ...

    acpi控制笔记本风扇转速

    Enhanced the implementation of the "serialized mode" of the interpreter (enabled via the AcpiGbl_AllMethodsSerialized flag.) When this mode is specified, instead of creating a serialization semaphore ...

    ora分析脚本

    'ash 30 10 -f foo.txt' to display a 10 minutes period from [now - 30min] and store the result in file foo.txt - ash_wait_graph [duration] [-f &lt;file_name&gt;] PQ event wait graph using ASH data ...

    DevExpress VCL v2012 vol 1.6源码、例子、帮助-part2

    Q440760 - Export to PDF - The File Save dialog is not shown if the default file name for a report is too long B218629 - In the Page Number Format dialog, the "Start At" field value is incorrectly ...

    allegro skill functions prefixed axl

    The topic "Allegro Skill Functions Prefixed AXL" refers to a specific subset of functions within the SKILL programming language that are used extensively in the Allegro PCB Editor software suite by ...

    FastReport.v4.9.81 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版

    You can open the report file only if you know the password. Print copy name on each printed copy (for example, "First copy", "Second copy"). You can set up copy names easily. What you get with ...

    eac3to V3.17

    * you can disable removal of the "full range" flag by doing "-keepFullRange" * added reader for external DVD, HD DVD and Blu-Ray SUP files * external SUP files can be delayed now * number of HD DVD ...

    java+ireport应用.docx

    exporter.exportReport(); } catch (Exception e) { // 处理异常 } } } ``` 在实际应用中,你可以根据业务需求调整`map`参数以传递动态参数,以及通过`list`参数传递数据。同时,还可以扩展`Reports`类以支持...

    DevExpress VCL v2012 vol 1.6源码、例子、帮助

    Q440760 - Export to PDF - The File Save dialog is not shown if the default file name for a report is too long B218629 - In the Page Number Format dialog, the "Start At" field value is incorrectly ...

Global site tag (gtag.js) - Google Analytics