- 浏览: 36651 次
- 性别:
- 来自: 杭州
最新评论
-
zhunengfei:
唉, 没有源码,不知道 有没有用
利用poi,iText导出excel,pdf -
xinxi_falcons:
你好,你这边有一个 fontSrc.properties这个配 ...
利用poi,iText导出excel,pdf -
xinxi_falcons:
你好,你这边有一个
利用poi,iText导出excel,pdf -
galo:
kakaluyi 写道PS:楼主如果抱着不分享的精神上论坛,估 ...
迷你音乐下载器V1.0拍砖版 -
galo:
kakaluyi 写道PS:楼主如果抱着不分享的精神上论坛,估 ...
迷你音乐下载器V1.0拍砖版
先声明下,本人对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; } } }
代码写了很长时间了,现在也忘记结构了,大概应该能够帮助到需要的朋友.
评论
3 楼
zhunengfei
2015-04-11
唉, 没有源码,不知道 有没有用
2 楼
xinxi_falcons
2014-02-26
你好,你这边有一个
fontSrc.properties
这个配置文件的里面的内容是什么 ?
这个配置文件 配置 是为了读系统widows 下的字体 吗 ?
能否回答下,谢谢!
fontSrc.properties
这个配置文件的里面的内容是什么 ?
这个配置文件 配置 是为了读系统widows 下的字体 吗 ?
能否回答下,谢谢!
1 楼
xinxi_falcons
2014-02-26
你好,你这边有一个
相关推荐
使用ITEXT导出EXCEL工具类使用ITEXT导出EXCEL工具类使用ITEXT导出EXCEL工具类使用ITEXT导出EXCEL工具类使用ITEXT导出EXCEL工具类
NULL 博文链接:https://jkfd.iteye.com/blog/2065757
NULL 博文链接:https://keep-going.iteye.com/blog/1907664
逻辑思路 1、先将excel转为pdf (TestForExcel2PDF测试类) 2、然后再pdf上加水印(TestWaterPrint、TestwaterMark都为加水印测试类)
SpringBoot整合poi实现Excel文件的导入和导出,其中单独分装出一个ExcelFormatUtil工具类来实现对单元格数据格式进行判断。
程序使用Struts2(SSH即Struts2+Hibernate+Spring)+POI+MySQL实现Excel动态数据导入和导出,程序源码文件附带运行说明
使用itextpdf将html模板生成pdf文档,poi导出excel,freemarker导出excel,pdf添加文字水印。
poi可以生成word和excel并进行操作,也可以导出word,excel和pdf的实现,要是导出pdf的话,需要引入itextpdf-5.2.1.jar
小demo,直接运行Test.java就行了 导出文件在D盘
工作中,经常做一些导出、读取Excel文档,但是从来没有尝试Word转PDF。我们通常使用的是POI和JXL。这两个插件对Excel已经有很好的支持了。操作PDF通常使用的是ITEXT插件,该插件可以操作复杂的PDF,当然我们也可以...
JFreeChart可生成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,可直接输出成图片文件,亦可被导出PDF或Excel文档。
会用到的拓展jar包jfreechart.jar、poi.jar、itext.jar等都集成在lib文件夹里 系统登录管理员 用户名 admin 密码 admin unit_4_myhome.sql 这个为plsql导出的数据库文件,包括了需要用到的表和需要用到的序列, ...
hd源码最终版(没有lib包,因为lib中的jar包邮70多m,太占空间了)。这一版只有代码。...这一版加入了导出功能,包括fusionchart的导出图片,然后把表格和图片导出到excel和pdf中去,其余和上一版没差别。