`
redheart_2006
  • 浏览: 21730 次
  • 性别: 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 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics