`
redheart_2006
  • 浏览: 22482 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类

用java的第三方类库生成一个pdf和excel报表对象

    博客分类:
  • java
阅读更多
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.ztesoft.zsmart.core.service.DynamicDict;

public class PDFViewer {
	
	Font fontheader = FontFactory.getFont("Helvetica", 10, Font.BOLD, Color.BLACK);
	Font fontitle = FontFactory.getFont("Helvetica", 22, Font.ITALIC, Color.darkGray);
	Font font = FontFactory.getFont("Helvetica", 8, Font.NORMAL, Color.BLACK);
	Font fontsummary = FontFactory.getFont("Helvetica", 10, Font.TIMES_ROMAN, Color.BLACK);
	private Document document;
	private PdfWriter writer;
	private PdfPTable table;
	
	private float interval = 35;
	private String title = "";
	private String filepath = "F:\\";
	private List tableHeader;
	private List tableData;
	private Map headerPropery = new HashMap();
	private float[] widths;
	
	public void setWidths(float[] widths) {
		this.widths = widths;
	}
	private Map summarys ;
	

	public static void main(String[] args) {
		PDFViewer viewer = new PDFViewer("kkkkkkkkkiiiiiiiik");
		String[] headers_ = {"header11,HEAD1","header22,HEAD2","header33,HEAD3"};
		List headers = Arrays.asList(headers_);
		viewer.setTableHeader(headers);

		List bodys = new ArrayList();
		for (int i = 0; i < 200; i++) {
			Map map = new HashMap();
			map.put("HEAD1", "bluesky1");
			map.put("HEAD2", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
			map.put("HEAD3", "3");
			bodys.add(map);
		}
		viewer.setTableData(bodys);
		
		Map summarys = new HashMap();
		summarys.put("HEAD3","0");
		summarys.put("HEAD2","0");
		viewer.setSummarys(summarys);
		try {
			viewer.generatePDF();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public PDFViewer(String title) {
		super();
		this.title = title;
	}
	public void generateTitle() throws DocumentException {
		   Paragraph title_ =new Paragraph(title,fontitle);
		   title_.setAlignment(Element.ALIGN_CENTER);
		   title_.setSpacingAfter(10);
           document.add(title_); 
		   float currentY = document.top();
         PdfContentByte cb = writer.getDirectContent(); 
         cb.moveTo(document.left()+100, currentY-interval);
         cb.lineTo(document.right()-100, currentY-interval);
         cb.stroke();
	}
	private void generateFoot() {
		HeaderFooter footer = new HeaderFooter(new Phrase("", font),
				true);
		footer.setBorder(Rectangle.NO_BORDER);
		footer.setAlignment(Element.ALIGN_RIGHT);
		document.setFooter(footer);
	}
	private void generateHeader() {
		 int size = tableHeader.size();
		 if(widths==null){
		 widths = new float[size];
		 for (int i = 0; i < size; i++)
			 widths[i]=1;}
         table = new PdfPTable(widths);
         table.setWidthPercentage(100);
         table.getDefaultCell().setBorderWidth(3);
         table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        
		for (int i = 0; i < size; i++) {
        	String headername = (String) tableHeader.get(i);
        	String[] headernames = headername.split(",");
        	if(headernames.length==2)headerPropery.put(String.valueOf(i), headernames[1]);
        	else headerPropery.put(String.valueOf(i), headernames[0]);
        	 PdfPCell ph = getCell(headernames[0], fontheader);
        	 ph.setBackgroundColor(Color.LIGHT_GRAY);
        	 table.addCell(ph);
		 }
         table.setHeaderRows(1);
	}
	public void generatePDF(OutputStream out) throws DocumentException, FileNotFoundException {
        document = new Document(PageSize.LETTER);
       // OutputStream out = new FileOutputStream(filepath+filename+".pdf");
        writer =  PdfWriter.getInstance(document, out);
      //generate report's foot
        generateFoot();
       //open the document
        document.open();
      //generate report's title
        generateTitle();
     //generate report's header
        generateHeader();
      //generate report's body 
        generateBody();
      //generate end summary
        generatEnd();
        
        document.add(table);
        document.close();
}
	public void generatePDF() throws DocumentException, FileNotFoundException {
	            document = new Document(PageSize.LETTER);
	            String filename = title;
	            if(title.length()>8)filename = title.substring(0, 8);
	            OutputStream out = new FileOutputStream(filepath+filename+".pdf");
	            writer =  PdfWriter.getInstance(document, out);
	          //generate report's foot
	            generateFoot();
	            document.open();
	          //generate report's title
	            generateTitle();
	         //generate report's header
	            generateHeader();
	          //generate report's body 
	            generateBody();
	          //generate end summary
	            generatEnd();
	            
	            document.add(table);
	            document.close();
	}
	public void generatEnd(){
		int total = 0;
		 PdfPCell cell = getCell("Summary", fontsummary);
		 cell.setBackgroundColor(Color.LIGHT_GRAY);
         table.addCell(cell);
         Map map = new HashMap();
         Iterator iter = summarys.keySet().iterator();
			while (iter.hasNext()) {
			 String propery =(String)iter.next();
			 for (int i = 0; i < headerPropery.size(); i++) {
				if(propery.equals(headerPropery.get(String.valueOf(i)))){
					String summary = (String)summarys.get(propery);
					map.put(String.valueOf(i), getCell(summary, font));	
					total+=Integer.parseInt(summary);
					}
			 }
			}
	//summary	
		for (int i = 1; i < headerPropery.size(); i++) {
			 Object obj = map.get(String.valueOf(i));
			 if(obj==null){
				 cell =getCell("", font);
				 cell.setBackgroundColor(Color.LIGHT_GRAY);
				 table.addCell(cell);
				 continue;}
			 cell =(PdfPCell)obj;
			 cell.setBackgroundColor(Color.LIGHT_GRAY);
			 cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
	         table.addCell(cell);
		}
	//total	
		 cell = getCell("Total", fontsummary);
		 cell.setBackgroundColor(Color.LIGHT_GRAY);
         table.addCell(cell);
         cell = getCell(String.valueOf(total), fontsummary);
         cell.setColspan(headerPropery.size()-1);
         cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		 cell.setBackgroundColor(Color.LIGHT_GRAY);
         table.addCell(cell);
	}
	
	
	
	
	private void generateBody()  {
		table.getDefaultCell().setBorderWidth(1);
		for (int i = 0; i < tableData.size(); i++) {
			   Object item =   tableData.get(i);
			   String[] contents = null;
			   if(item instanceof Map){
				  Map map =  (Map)item; 
				  contents = new String[headerPropery.size()];
				for (int k = 0; k < contents.length; k++) {
					contents[k] = (String) map.get(headerPropery.get(String.valueOf(k)));
					if(contents[k]==null)contents[k]="";
				}
				 createNewRow(contents);
				 //process summary 
				 if(summarys!=null){
						Iterator iter = summarys.keySet().iterator();
						while (iter.hasNext()) {
						 String propery =(String)iter.next();
						 String addvalue =(String)map.get(propery);
					    if(addvalue==null||addvalue.equals(""))addvalue="0";
					    int addvalue_ = 0;
					    try {
					    	  addvalue_  =  Integer.parseInt(addvalue);
						} catch (Exception e) {
						}
					     String oldvalue =(String)summarys.get(propery);
					     int newvalue = Integer.parseInt(oldvalue)+addvalue_;
					    // System.out.println("newvalue========>"+newvalue);
					     summarys.put(propery, String.valueOf(newvalue));
						}
				 }
			   }
			   else if(item instanceof DynamicDict){
				//   DynamicDict dict =  (DynamicDict)item; 
			   }
		}
	}

	private  void createNewRow(String[] contents) {
        PdfPCell cell;
        for (int i = 0; i < contents.length; i++) {
        	 cell = getCell(contents[i], font);
             table.addCell(cell);	
		}
    }

	private  PdfPCell getCell(String content,  Font font) {
    	PdfPCell cell = new PdfPCell(new Paragraph(content, font));
        return cell;
    }

	public String getTitle() {
		return title;
	}

	public void setTitle(String title_) throws DocumentException {
		  this.title = title_;
	}
	public List getTableHeader() {
		return tableHeader;
	}
	public void setTableHeader(List tableHeader) {
		this.tableHeader = tableHeader;
	}
	public List getTableData() {
		return tableData;
	}
	public void setTableData(List tableData) {
		this.tableData = tableData;
	}
	public void setHeaderPropery(Map headerPropery) {
		this.headerPropery = headerPropery;
	}
	public Map getHeaderPropery() {
		return headerPropery;
	}

	public Map getSummarys() {
		return summarys;
	}
	public void setSummarys(Map summarys) {
		this.summarys = summarys;
	}
}

以上主要用的第三方jar包为itext.jar

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


//import org.displaytag.model.TableModel;

/**
 * Export view for excel exporting.
 * 
 */
public class ExcelViewer {
	private List tableHeader;
	private List tableData;
	ByteArrayOutputStream os = null;
	WritableWorkbook wwb = null;
	WritableSheet wsheet = null;
    int row = 0;//excel's row
    
	private Map headerPropery = new HashMap();
	private Map summarys;
	private String title = "";
	private String[] widths;
	
	public static void main(String[] args) throws Exception {
		OutputStream fos = new FileOutputStream("F:\\test.xls");
		ExcelViewer viewer = new ExcelViewer("blueskey222");
		String[] headers_ = { "header11,HEAD1", "header22,HEAD2", "header33,HEAD3" };
		List headers = Arrays.asList(headers_);
		viewer.setTableHeader(headers);

		List bodys = new ArrayList();
		for (int i = 0; i < 10; i++) {
			Map map = new HashMap();
			map.put("HEAD1", "bluesky1");
			map.put("HEAD2", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
			map.put("HEAD3", "3");
			bodys.add(map);
		}
		viewer.setTableData(bodys);

		Map summarys = new HashMap();
		summarys.put("HEAD3", "0");
		summarys.put("HEAD2", "0");
		viewer.setSummarys(summarys);

		String[] widths = { "0,100", "1,100"};
		viewer.setWidths(widths);
		viewer.generateExcel(fos);

	}

	public void generateExcel(OutputStream out) throws WriteException, IOException {
		os = new ByteArrayOutputStream();
		wwb = Workbook.createWorkbook(os);
		wsheet = wwb.createSheet(title, 0);
		//set column's space 
		setColSpace();

		generateHeaders();
		generateBody();
		generatEnd();
		//System.out.println("row:"+row);
		wwb.write();
		wwb.close();
		out.write(os.toByteArray());
	}

	private void setColSpace() {
		if(widths==null)return;
		for (int i = 0; i < widths.length; i++) {
			String[] strs = widths[i].split(",");
			System.out.println(strs[0]+":"+strs[1]);
			wsheet.setColumnView(Integer.parseInt(strs[0]), Integer.parseInt(strs[1]));
		}
	}

	public void generatEnd() throws RowsExceededException, WriteException {
		WritableFont endfont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
		WritableCellFormat endheader = new WritableCellFormat(endfont);
		endheader.setBackground(Colour.GRAY_25);
		WritableCellFormat numheader = new WritableCellFormat(endfont);
		numheader.setBackground(Colour.GRAY_25);
		numheader.setAlignment(Alignment.RIGHT);
		
		int total = 0;
		Label label = new Label(0, row,"Summary",endheader);
		wsheet.addCell(label);
        Map map = new HashMap();
        Iterator iter = summarys.keySet().iterator();
			while (iter.hasNext()) {
			 String propery =(String)iter.next();
			 for (int i = 0; i < headerPropery.size(); i++) {
				if(propery.equals(headerPropery.get(String.valueOf(i)))){
					String summary = (String)summarys.get(propery);
					map.put(String.valueOf(i), new Label(i, row,summary,numheader));
					total+=Integer.parseInt(summary);
				}	
			 }
			}
	//summary
		for (int i = 1; i < headerPropery.size(); i++) {
			 Object obj = map.get(String.valueOf(i));
			 if(obj==null){
				 label =new Label(i, row,"",endheader);
				 wsheet.addCell(label);
				continue;}
			 label =(Label)obj;
			 wsheet.addCell(label);
		}
		row++;
	//total
		 label =new Label(0, row,"Total",endheader);
		 wsheet.addCell(label);
		 wsheet.mergeCells(1, row, headerPropery.size()-1, row);
		
		 label =new Label(1, row,String.valueOf(total),numheader);
		
		 wsheet.addCell(label);
       
	}

	public ExcelViewer(String title) {
		super();
		this.title = title;
	}
	
	
	
	private void generateHeaders() throws WriteException {
		int size = tableHeader.size();
		for (int i = 0, index = 0; i < size; i++, index++) {
			String headername = (String) tableHeader.get(i);
			String[] headernames = headername.split(",");
			if (headernames.length == 2)
				headerPropery.put(String.valueOf(i), headernames[1]);
			else
				headerPropery.put(String.valueOf(i), headernames[0]);
			
			WritableFont headerfont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
			WritableCellFormat fomatheader = new WritableCellFormat(headerfont);
			fomatheader.setBackground(Colour.GRAY_25);
			Label label = new Label(index, row, headernames[0],fomatheader);
			wsheet.addCell(label);
		}
		row++;
	}

	private void generateBody() throws WriteException {
		for (int i = 0; i < tableData.size(); i++) {
			Map map = (HashMap) tableData.get(i);
			String[] contents = null;
			contents = new String[headerPropery.size()];
			for (int k = 0; k < contents.length; k++) {
				contents[k] = (String) map.get(headerPropery.get(String.valueOf(k)));
				if (contents[k] == null)
					contents[k] = "";
			}

			for (int col = 0; col < contents.length; col++) {
				Label label = new Label(col, row, contents[col]);
				wsheet.addCell(label);
			}
			row++;
			 //process summary 
			 if(summarys!=null){
					Iterator iter = summarys.keySet().iterator();
					while (iter.hasNext()) {
					 String propery =(String)iter.next();
					 String addvalue =(String)map.get(propery);
				    if(addvalue==null||addvalue.equals(""))addvalue="0";
				    int addvalue_ = 0;
				    try {
				    	  addvalue_  =  Integer.parseInt(addvalue);
					} catch (Exception e) {
					}
				     String oldvalue =(String)summarys.get(propery);
				     int newvalue = Integer.parseInt(oldvalue)+addvalue_;
				    // System.out.println("newvalue========>"+newvalue);
				     summarys.put(propery, String.valueOf(newvalue));
					}
			 }
		}
	}


	public List getTableHeader() {
		return tableHeader;
	}

	public void setTableHeader(List tableHeader) {
		this.tableHeader = tableHeader;
	}

	public List getTableData() {
		return tableData;
	}

	public void setTableData(List tableData) {
		if (this.tableData != null) {
			this.tableData.clear();
			this.tableData = null;
		}
		this.tableData = tableData;
	}

	public Map getSummarys() {
		return summarys;
	}

	public void setSummarys(Map summarys) {
		this.summarys = summarys;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setWidths(String[] widths) {
		this.widths = widths;
	}

}

 以上主要用的是jxl.jar 

分享到:
评论

相关推荐

    帆软报表导出各种格式(excel/word/pdf等)

    这两个jar文件包含了帆软报表引擎的核心组件和第三方依赖,它们是实现报表格式转换的关键。在实际操作中,我们需要将这些库加入到项目的类路径中,确保系统能够正确识别并执行报表导出的指令。 datasource.xml文件...

    java报表技术实例

    8. **自定义函数和类库**:了解如何扩展JasperReports,添加自定义函数或引入第三方类库,以实现更复杂的功能。 9. **国际化支持**:学习如何使报表支持多语言,满足全球化需求。 10. **API使用**:通过实例代码,...

    C++和excel源码

    3. **第三方库**:如`libxl`、`EasyXLS`、`Apache POI`(Java库,但有C++绑定)等,提供API使得C++可以直接读写Excel文件,无需安装Excel。这种方法通常效率较高,且跨平台。 4. **MFC(Microsoft Foundation ...

    JAVA窗体的jar包

    总的来说,这个"JAVA窗体的jar包"是一个包含多种功能的资源集合,涵盖了数据库交互、用户界面定制和报表生成等方面,对于Java桌面应用的开发提供了便利和丰富的功能选择。开发者可以根据项目需求,灵活运用这些组件...

    人事考勤签到管理系统 JAVA

    JAVA可以借助第三方库,如Apache POI或iText,生成Excel或PDF格式的考勤报表,这些报表可以包含员工的出勤天数、迟到次数、请假情况等详细信息,便于分析和决策。 在实际开发过程中,为了提高代码质量和可维护性,...

    checking-in-analysis_Java.zip_run

    - 报告生成可能使用了Java的打印服务或者第三方库,如Apache POI来处理Excel,iText或PDFBox用于PDF报告。 3. **运行流程**: - 用户安装并配置好JDK 6后,找到项目解压的目录,进入"checking-in"子目录。 - ...

    ireport 使用的 jar .zip

    这些jar文件可能包含了iReport本身的功能实现、JasperReports库、数据库连接驱动和其他依赖的第三方库。例如: 1. **jasperreports.jar** - JasperReports库的核心文件,提供了报表生成的API和各种报表元素。 2. **...

    JasperReport+iReport 报表工具详细开发手册

    - **JasperReport依赖的第三方组件包**:位于\jasperreports-3.5.2\lib\目录下。其中,“commons-”开头的jar包为必须的,例如`commons-logging-api-1.0.2.jar`、`commons-logging-1.0.2.jar`、`commons-pool-1.3....

    JasperReports 报表类库v3.5.zip

    1. **模板设计**:用户可以使用内置的报表设计工具JasperDesign或第三方工具(如iReport)创建XML格式的报表模板。这些模板可以包含文本、图像、表格、图表等各种元素,允许开发者通过简单的拖放操作进行布局设计。 ...

    学生信息管理系统

    这里可能用到Apache POI或iText等第三方库。 三、数据库设计 数据库是系统的核心,用于持久化存储数据。学生信息表可能包含以下字段:学号(主键)、姓名、性别、出生日期、班级等。成绩表则包括学号、科目、分数...

    JasperReports_UltimateGuide.1.2.5.pdf

    - 包括使用内置查看器或第三方工具。 - **打印报告**: - 说明了如何将报告发送到打印机。 - 包括设置打印选项的方法。 - **导出报告**: - 探讨了将报告导出为多种格式的可能性。 - 如PDF、Excel、HTML等格式...

    jasperreports实例+中文文档+资料

    5. **自定义函数与组件**: 如何编写和使用自定义函数,以及添加第三方组件,扩展报表功能。 **中文文档** 中文文档对于非英语背景的学习者来说非常宝贵,它能帮助理解JasperReports的各项功能和API,包括: 1. **...

    各种有关.net的dll的集合

    2. **依赖库**:许多第三方库和API以DLL的形式提供,如ASP.NET MVC、Entity Framework等,这些库提供了丰富的功能,如Web开发、数据访问等。 3. **运行时环境**:.NET Framework本身包含大量系统级的DLL,如mscorlib...

    《基于Oracle10g的数据仓库实践》

    除了Oracle10g本身之外,还有许多第三方软件和工具可以帮助更好地构建和管理数据仓库。 - **5.1 Oracle Database**:提供核心的数据存储和管理功能。 - **5.2 Oracle Companion**:一系列用于增强Oracle10g功能的...

    Pyro_Fusion-开源

    1. **Pyro_JasperReports**: 这是Pyro_Fusion库中的一个关键部分,它集成了JasperReports,一个广泛使用的Java报表工具。JasperReports允许开发者创建复杂的报表设计,并以多种格式导出,如PDF、HTML、Excel等。通过...

Global site tag (gtag.js) - Google Analytics