`
galo
  • 浏览: 36651 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

利用poi,iText导出excel,pdf

阅读更多
  先声明下,本人对poi,iText没有深入研究,只因网上实例很多,所以照葫芦画瓢,再加上自己进一步的重构,才有了下面的模型.只希望能帮助到大家。
//创建ExcelEntity
import java.io.OutputStream;
import java.util.List;

public class ExcelEntity<T> {
	
	private String title = "报表标题";
	private String[] headers;
	private List<T> dataset;
	private OutputStream os;
	private boolean hasComment = false;
	private String commentContent = "report";
	private String commentAuthor = "Galo";
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String[] getHeaders() {
		return headers;
	}
	public void setHeaders(String[] headers) {
		this.headers = headers;
	}
	public List<T> getDataset() {
		return dataset;
	}
	public void setDataset(List<T> dataset) {
		this.dataset = dataset;
	}
	public OutputStream getOs() {
		return os;
	}
	public void setOs(OutputStream os) {
		this.os = os;
	}
	public boolean isHasComment() {
		return hasComment;
	}
	public void setHasComment(boolean hasComment) {
		this.hasComment = hasComment;
	}
	public String getCommentContent() {
		return commentContent;
	}
	public void setCommentContent(String commentContent) {
		this.commentContent = commentContent;
	}
	public String getCommentAuthor() {
		return commentAuthor;
	}
	public void setCommentAuthor(String commentAuthor) {
		this.commentAuthor = commentAuthor;
	}
}

//创建PdfEntity
import java.io.OutputStream;
import java.util.List;

public class PdfEntity<T> {
	
	private String title; //标题
	private float margin_bottom = 50; //下边距
	private float margin_left = 50;
	private float margin_top = 50;
	private float margin_right = 50;
	private String pageSize = "A4";	//纸张大小
	private String fileName = "E://report.pdf"; //文件名称
	private String author = "Galo"; //作者
	private String subject = "Zhang";	//子项
	private boolean creationDate = true;	//创建时间
	private String creator = "Galo"; //创建者
	private String keywords = "报表"; //关键字
	private String pageHeader; //页眉
	private String pageFooter; //页脚
	
	private String[] headers;	//表头
	private List<T> dataset;	//数据集
	private OutputStream os;	//文件输出流
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public float getMargin_bottom() {
		return margin_bottom;
	}
	public void setMargin_bottom(float margin_bottom) {
		this.margin_bottom = margin_bottom;
	}
	public float getMargin_left() {
		return margin_left;
	}
	public void setMargin_left(float margin_left) {
		this.margin_left = margin_left;
	}
	public float getMargin_top() {
		return margin_top;
	}
	public void setMargin_top(float margin_top) {
		this.margin_top = margin_top;
	}
	public float getMargin_right() {
		return margin_right;
	}
	public void setMargin_right(float margin_right) {
		this.margin_right = margin_right;
	}
	public String getPageSize() {
		return pageSize;
	}
	public void setPageSize(String pageSize) {
		this.pageSize = pageSize;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public boolean isCreationDate() {
		return creationDate;
	}
	public void setCreationDate(boolean creationDate) {
		this.creationDate = creationDate;
	}
	public String getCreator() {
		return creator;
	}
	public void setCreator(String creator) {
		this.creator = creator;
	}
	public String getKeywords() {
		return keywords;
	}
	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}
	public String getPageHeader() {
		return pageHeader;
	}
	public void setPageHeader(String pageHeader) {
		this.pageHeader = pageHeader;
	}
	public String getPageFooter() {
		return pageFooter;
	}
	public void setPageFooter(String pageFooter) {
		this.pageFooter = pageFooter;
	}
	public String[] getHeaders() {
		return headers;
	}
	public void setHeaders(String[] headers) {
		this.headers = headers;
	}
	public List<T> getDataset() {
		return dataset;
	}
	public void setDataset(List<T> dataset) {
		this.dataset = dataset;
	}
	public OutputStream getOs() {
		return os;
	}
	public void setOs(OutputStream os) {
		this.os = os;
	}
}

//下面是具体导出方法
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.jd.report.entity.ExcelEntity;
import com.jd.report.entity.PdfEntity;
import com.jd.report.util.PdfParagraph;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class ExportUtils<T> {
	
	@SuppressWarnings("unchecked")
	public void exportPdf(PdfEntity<T> pdfEntity){
		
		String pageSize = pdfEntity.getPageSize();
		
		Rectangle rectangle = new Rectangle(getPdfPageSize(pageSize));
		Document document = new Document(rectangle,pdfEntity.getMargin_bottom(),pdfEntity.getMargin_left(),pdfEntity.getMargin_right(),pdfEntity.getMargin_top());
		
		try {
			PdfWriter.getInstance(document, pdfEntity.getOs());
			//基本配置信息
			document.addTitle(pdfEntity.getTitle());
			document.addAuthor(pdfEntity.getAuthor());
			if(pdfEntity.isCreationDate()){
				
				document.addCreationDate();
			}
			document.addCreator(pdfEntity.getCreator());
			document.addKeywords(pdfEntity.getKeywords());
			document.addSubject(pdfEntity.getSubject());
			
			//定义页眉和页脚
			String pageHeader = pdfEntity.getPageHeader();
			String pageFooter = pdfEntity.getPageFooter();
			HeaderFooter header = null;
			HeaderFooter footer = null;
			if(pageHeader != null){
				
				header = new HeaderFooter(new PdfParagraph(pageHeader,14,true),false);
				header.setBorderWidth(0);
				header.setAlignment(Element.ALIGN_CENTER);
			}
			if(pageFooter != null){
				
				footer = new HeaderFooter(new PdfParagraph(pageFooter,14,true),false);
				footer.setBorderWidth(0);
				footer.setAlignment(Element.ALIGN_CENTER);
			}
			document.setHeader(header);
			document.setFooter(footer);
			//打开pdf文档
			document.open();
			
			String[] headers = pdfEntity.getHeaders();
			//创建多少列的表格
			PdfPTable table = new PdfPTable(headers.length);
			table.setHorizontalAlignment(Element.ALIGN_CENTER);
	        table.setWidthPercentage(16 * headers.length);
	        
	        //产生表格栏
	        PdfPCell cell = null;
	        for (int i = 0; i < headers.length; i++) {

	            cell = new PdfPCell(new PdfParagraph(headers[i], 14,true));
	            cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
	            cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
	            cell.setBackgroundColor(Color.cyan);
	            cell.setBorderColor(Color.green);
	            table.addCell(cell);
	         }
	        //装载数据行
	        Collection<T> dataset = pdfEntity.getDataset();
	        Iterator<T> it = dataset.iterator();
	        while(it.hasNext()){
	        	
	        	T t = it.next();
	        	Class tClass = t.getClass();
	        	Field[] fields = tClass.getDeclaredFields();
	        	for (int i = 0; i < fields.length; i++) {
					
	        		String fieldName = fields[i].getName();
	        		String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
	        		Method getMethod = tClass.getMethod(getMethodName, new Class[]{});
	        		Object value = getMethod.invoke(t, new Object[]{});
	        		value = value == null ? "" : value;
	        		if(value != null){
	        			
	        			cell = new PdfPCell(new PdfParagraph(value.toString(),12,false));
	        			cell.setHorizontalAlignment(Cell.ALIGN_CENTER);
	                    cell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
	                    cell.setBorderColor(Color.green);
	                    table.addCell(cell);
	        		}
				}
	        }
	        document.add(table);
	        document.close();
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	public void exportExcel(ExcelEntity excelEntity){
		
		String title = excelEntity.getTitle();
		HSSFWorkbook workbook = new HSSFWorkbook();
		//生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		//设置默认列宽度为15个字节
		sheet.setDefaultColumnWidth(15);
		//生成一个标题样式
		HSSFCellStyle style = workbook.createCellStyle();
		//设置居中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		//设置填充前景色和背景色
		style.setFillForegroundColor(HSSFColor.YELLOW.index);
		style.setFillBackgroundColor(HSSFColor.WHITE.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);
		//生成一个字体
		HSSFFont font = workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setColor(HSSFColor.VIOLET.index);
		font.setFontHeightInPoints((short)12);
		//字体应用到样式
		style.setFont(font);
		
		//生成主体样式
		HSSFCellStyle bodyStyle = workbook.createCellStyle();
		//设置居中
		bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		//设置填充前景色和背景色
		bodyStyle.setFillForegroundColor(HSSFColor.WHITE.index);
		bodyStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
		bodyStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		//设置线条宽度
		bodyStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		//生成一个字体
		HSSFFont bodyFont = workbook.createFont();
		bodyFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		bodyFont.setColor(HSSFColor.VIOLET.index);
		bodyFont.setFontHeightInPoints((short)12);
		//字体应用到样式
		bodyStyle.setFont(bodyFont);
		
		HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
		HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,0,0,0,(short)4,2,(short)6,5));
		comment.setString(new HSSFRichTextString(excelEntity.getCommentContent()));
		comment.setAuthor(excelEntity.getCommentAuthor());
		
		//产生标题行
		String[] headers = excelEntity.getHeaders();
		int index = 0;
		HSSFRow row = sheet.createRow(index);
		HSSFCell cell = null;
	    for (short i = 0; i < headers.length; i++) {

	      cell = row.createCell(i);
	      cell.setCellStyle(style);
	      HSSFRichTextString text = new HSSFRichTextString(headers[i]);
	      cell.setCellValue(text);
	    }
	    //遍历集合,产生数据行
	    Collection<T> dataset = excelEntity.getDataset();
	    Iterator<T> it = dataset.iterator();
	    while(it.hasNext()){
	    	
	    	index++;
	    	row = sheet.createRow(index);
	    	T t = it.next();
	    	Class tClass = t.getClass();
	    	Field[] fields = tClass.getDeclaredFields();
	    	for (int i = 0; i < fields.length; i++) {
				
	    		cell = row.createCell(i);
	    		cell.setCellStyle(style);
	    		String fieldName = fields[i].getName();
	    		String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
	    		try {
					Method getMethod = tClass.getMethod(getMethodName, new Class[]{});
					Object value = getMethod.invoke(t, new Object[]{});
					value = value == null ? "" : value;
					if(value != null){
						
						HSSFRichTextString textString = new HSSFRichTextString(value.toString());
						cell.setCellValue(textString);
						cell.setCellStyle(bodyStyle);
					}
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	    }
	    try {
	    	//写出excel
			workbook.write(excelEntity.getOs());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void exportWord(){
		
		
	}
	public Rectangle getPdfPageSize(String pageSize){
		
		Rectangle pSize = null;
		if("A4".equals(pageSize)){
			
			pSize = PageSize.A4;
		}else if("A3".equals(pageSize)){
			
			pSize = PageSize.A3;
		}else if("A2".equals(pageSize)){
			
			pSize = PageSize.A2;
		}else if("A1".equals(pageSize)){
			
			pSize = PageSize.A1;
		}else{
			
			pSize = PageSize.A4;
		}
		
		return pSize;
	}
}

//对于pdf中文乱码,有如下辅助类
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;

public class PdfParagraph extends Paragraph {

   private static final long serialVersionUID = -244970043180837974L;
   private static Properties pro ;
   private static InputStream is ;
   static{
		try {
           is =  PdfParagraph.class.getClassLoader().getResourceAsStream("fontSrc.properties");
			pro = new Properties();
			pro.load(is);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	} 
   public static String getPlan(String source){
	   
	   return pro.getProperty(source);
   }
   
   public PdfParagraph(String content) {

      super(content, getChineseFont(12, false));
   }

   public PdfParagraph(String content, int fontSize, boolean isBold) {

      super(content, getChineseFont(fontSize, isBold));
   }

   // 设置字体-返回中文字体
   protected static Font getChineseFont(int nfontsize, boolean isBold) {

      BaseFont bfChinese;
      Font fontChinese = null;

      try {
    	  
         bfChinese = BaseFont.createFont(getPlan("fontSrc") + ":\\windows\\fonts\\simsun.ttc,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
         if (isBold) {

            fontChinese = new Font(bfChinese, nfontsize, Font.BOLD);
         } else {

            fontChinese = new Font(bfChinese, nfontsize, Font.NORMAL);
         }

      } catch (DocumentException e) {

         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IOException e) {

         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return fontChinese;
   }

   // 转化中文
   protected Cell ChangeCell(String str, int nfontsize, boolean isBold) throws IOException, BadElementException, DocumentException {

      Phrase ph = ChangeChinese(str, nfontsize, isBold);
      Cell cell = new Cell(ph);
      // cell.setBorderWidth(3);
      return cell;
   }

   // 转化中文
   protected Chunk ChangeChunk(String str, int nfontsize, boolean isBold) throws IOException, BadElementException, DocumentException {

      Font FontChinese = getChineseFont(nfontsize, isBold);
      Chunk chunk = new Chunk(str, FontChinese);
      return chunk;
   }

   // 转化中文
   protected Phrase ChangeChinese(String str, int nfontsize, boolean isBold) throws IOException, BadElementException, DocumentException {

      Font FontChinese = getChineseFont(nfontsize, isBold);
      Phrase ph = new Phrase(str, FontChinese);
      return ph;
   }
   
   }
}



  代码写了很长时间了,现在也忘记结构了,大概应该能够帮助到需要的朋友.
6
1
分享到:
评论
3 楼 zhunengfei 2015-04-11  
唉, 没有源码,不知道 有没有用
2 楼 xinxi_falcons 2014-02-26  
你好,你这边有一个
fontSrc.properties

这个配置文件的里面的内容是什么 ?

这个配置文件 配置 是为了读系统widows 下的字体 吗 ?

能否回答下,谢谢!
1 楼 xinxi_falcons 2014-02-26  
你好,你这边有一个

相关推荐

Global site tag (gtag.js) - Google Analytics