代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Java
】
导出pdf,excel,word
作者:
yuyuanhua
/ 发布于
2014/8/4
/
858
package cls.taishan.util.report.controller; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cls.taishan.util.report.factory.ExportReportFactory; import cls.taishan.util.report.intf.IExportReport; import cls.taishan.util.report.intf.IExportReport.ReportType; public class ExportReportServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; private String encoding="UTF-8"; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); //获取报表相关数据 Map<String, Object> mapInfo = getReportInfo(request); // 生成Excel报表 if (mapInfo.get("type").equals("excel")) { try{ IExportReport exportReport =ExportReportFactory.newInstance(ReportType.Excel); exportReport.createReport(request, response, mapInfo); }catch(Exception e){ e.printStackTrace(); } } else if(mapInfo.get("type").equals("pdf")){ //生成PDF报表 try { IExportReport exportReport =ExportReportFactory.newInstance(ReportType.PDF); exportReport.createReport(request, response, mapInfo); } catch (Exception e) { e.printStackTrace(); } }else if(mapInfo.get("type").equals("word")){ //生成WORD报表 try { IExportReport exportReport =ExportReportFactory.newInstance(ReportType.Word); exportReport.createReport(request, response, mapInfo); } catch (Exception e) { e.printStackTrace(); } }else { //生成jpg图片 try { IExportReport exportReport =ExportReportFactory.newInstance(ReportType.JPG); exportReport.createReport(request, response, mapInfo); } catch (Exception e) { e.printStackTrace(); } } } /** * Function:获取生产报表的相关信息 * @author chenck * CreateTime 2011年7月2日 * * @param HttpServletRequest request * * @return Map<String, Object> */ private Map<String, Object> getReportInfo(HttpServletRequest request) { // 存放报表内容的相关信息 Map<String, Object> report_map = new HashMap<String, Object>(); //获取客户端信息 String type = request.getParameter("type"); // 要导出的文件类型 String title = request.getParameter("title"); // 导出的文件名称 String tableCaption = request.getParameter("tableCaption"); // 表示前台<table>中元素<caption>的集合 String tableCol = request.getParameter("tableCol"); // 表示前台<table>的最大列数的集合 String tableContext = request.getParameter("tableBody"); // 表示前台<table>的内容的集合 String widthTD = request.getParameter("widthTD"); // 表示前台<table>第一行所有列的宽度 String[] tableCaptionList = tableCaption.split("#CAPTION#"); String[] tableColList = tableCol.split(";"); String[] tableList = tableContext.split("#TABLE#"); String[] widthList = widthTD.split(";"); report_map.put("widthList", widthList); //将处理后的信息放入HashMap中 report_map.put("type", type); report_map.put("title", title); report_map.put("tableCaptionList", tableCaptionList); report_map.put("tableColList", tableColList); report_map.put("tableList", tableList); //返回map return report_map; } @Override public void init() throws ServletException { String _encoding=getInitParameter("encoding"); if(null!=_encoding && !"".equals(_encoding)){ this.encoding=_encoding; } } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } } 2. [文件] ReportFontFactory.java ~ 2KB 下载(7) ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 package cls.taishan.util.report.factory; import java.io.IOException; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.pdf.BaseFont; public class ReportFontFactory { public enum Font_Type{ TITLE,HEADER,CONTENT; } private ReportFontFactory(){} /** * Function 创建PDF报表字体 * CreateTime 2014年7月22日 * @author yyh * @param fontType 字体类型(enum) * @return Font 字体 * @throws DocumentException * @throws IOException */ public static Font getFontChinese(Font_Type fontType) throws DocumentException, IOException{ BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); com.lowagie.text.Font fontChinese=null; switch (fontType){ case TITLE: fontChinese= new com.lowagie.text.Font(bfChinese,12, com.lowagie.text.Font.BOLD); break; case HEADER: fontChinese = new com.lowagie.text.Font(bfChinese,8, com.lowagie.text.Font.BOLD); break; case CONTENT: fontChinese = new com.lowagie.text.Font(bfChinese,8, com.lowagie.text.Font.NORMAL); break; default: fontChinese = new com.lowagie.text.Font(bfChinese,7, com.lowagie.text.Font.NORMAL); break; } return fontChinese; } /** * Function 创建PDF报表字体 * CreateTime 2014年7月22日 * @author yyh * @param fontType 字体类型(enum) * @return Font 字体 * @throws DocumentException * @throws IOException */ public static Font getFontCambodia(Font_Type fontType)throws DocumentException, IOException{ BaseFont bfCambodia=BaseFont.createFont("c://Windows/Fonts/KhmerOSsys.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //BaseFont.createFont("c://Windows/Fonts/Khmviravuth.ttf", BaseFont.WINANSI,BaseFont.EMBEDDED); com.lowagie.text.Font fontCambodia=null; switch (fontType){ case TITLE: fontCambodia= new com.lowagie.text.Font(bfCambodia,12, com.lowagie.text.Font.BOLD); break; case HEADER: fontCambodia = new com.lowagie.text.Font(bfCambodia,8, com.lowagie.text.Font.BOLD); break; case CONTENT: fontCambodia = new com.lowagie.text.Font(bfCambodia,8, com.lowagie.text.Font.NORMAL); break; default: fontCambodia = new com.lowagie.text.Font(bfCambodia,7, com.lowagie.text.Font.NORMAL); break; } return fontCambodia; } } package cls.taishan.util.report.encodingfilter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class EncodingFilter implements Filter{ private static String encoding="UTF-8"; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(EncodingFilter.encoding); response.setCharacterEncoding(EncodingFilter.encoding); chain.doFilter(request,response); } @Override public void init(FilterConfig config) throws ServletException { String charset=config.getInitParameter("encoding"); if(null!=charset && !"".equals(charset.trim())){ EncodingFilter.encoding=charset; } } @Override public void destroy() { } } 4. [文件] ExportReportFactory.java ~ 1KB 下载(7) ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 package cls.taishan.util.report.factory; import cls.taishan.util.report.impl.ExportReportForExcel; import cls.taishan.util.report.impl.ExportReportForJPG; import cls.taishan.util.report.impl.ExportReportForPDF; import cls.taishan.util.report.impl.ExportReportForWord; import cls.taishan.util.report.intf.IExportReport; import cls.taishan.util.report.intf.IExportReport.ReportType; /** * Function 实例化对象的报表对象 * CreateTime 2014年7月22日 * @author yyh * @version 1.1.0 */ public class ExportReportFactory { private static IExportReport exportReport; private ExportReportFactory(){} /** * Function 根据报表类型实例化报表对象 * CreateTime 2011年7月8日 * @param reportType 报表类型(enum) * @return IExportReport 报表实例 */ public static IExportReport newInstance(ReportType reportType) { switch (reportType) { case Excel: exportReport=new ExportReportForExcel(); break; case PDF: exportReport=new ExportReportForPDF(); break; case Word: exportReport=new ExportReportForWord(); break; case JPG: exportReport=new ExportReportForJPG(); break; } return exportReport; } } 5. [文件] ExportReportForExcel.java ~ 16KB 下载(13) 6. [文件] ExportReportForPDF.java ~ 12KB 下载(5) ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 package cls.taishan.util.report.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cls.taishan.util.report.factory.ReportFontFactory; import cls.taishan.util.report.factory.ReportFontFactory.Font_Type; import cls.taishan.util.report.intf.IExportReport; 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.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.Rectangle; import com.lowagie.text.Table; import com.lowagie.text.pdf.PdfWriter; /** * Function 生成PDF报表 * CreateTime 2014年7月22日 * @author yyh * @version 1.2.0 */ public class ExportReportForPDF implements IExportReport{ /** * Function 生成PDF报表 * CreateTime 2014年7月22日 * @author yyh * @version 1.0.0 * @param HttpServletRequest request * @param HttpServletResponse response * @param Map<?,?> reportInfo 生成报表所需要的数据 * * 说明:不能同时跨行跨列;可设置Cell宽度 * (yyh UpdateTime 2014-7-22) */ @Override public void createReport(HttpServletRequest request, HttpServletResponse response, Map<?, ?> reportInfo) throws Exception { String[] tableCaptionList = (String[])reportInfo.get("tableCaptionList"); String[] tableList = (String[])reportInfo.get("tableList"); String[] tableColList = (String[])reportInfo.get("tableColList"); String[] widthList = (String[])reportInfo.get("widthList"); //判断生成数据是否为空 if(tableList == null || tableList.length < 0){ System.out.println("没有导出数据"); } //生成PDF文档 Document document = new Document(PageSize.A4, 36,36,36,36); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { String fileTitle = (String) reportInfo.get("title"); if ("".equals(fileTitle)) { fileTitle = "export"; } //设置文件响应信息 String showFileName = URLEncoder.encode(fileTitle + ".pdf", "UTF-8"); showFileName = new String(showFileName.getBytes("iso8859-1"), "gb2312"); //定义输出类型 response.reset(); response.setContentType("application/pdf"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "max-age=30"); response.setHeader("Content-disposition", "attachment; filename="+ new String(showFileName.getBytes("gb2312"), "iso8859-1")); PdfWriter.getInstance(document, bos); //添加页眉 //HeaderFooter headerFooter = new HeaderFooter(new Phrase(),true); //headerFooter.setBorder(Rectangle.NO_BORDER); //headerFooter.setAlignment(Element.ALIGN_CENTER); //document.setHeader(headerFooter); //添加页脚 //HeaderFooter footer = new HeaderFooter(new Phrase("第 ",ReportFontFactory.getFontChinese(Font_Type.CONTENT)),new Phrase(" 页",ReportFontFactory.getFontChinese(Font_Type.CONTENT))); HeaderFooter footer = new HeaderFooter(new Phrase("第 ",ReportFontFactory.getFontCambodia(Font_Type.CONTENT)),new Phrase(" 页",ReportFontFactory.getFontCambodia(Font_Type.CONTENT))); footer.setBorder(Rectangle.NO_BORDER); footer.setAlignment(Element.ALIGN_CENTER); document.setFooter(footer); //打开doc document.open(); // PdfPTable table = null; // PdfPCell cell =null; // 不能同时跨行跨列 Table table = null; Cell cell = null; // 能同时跨行跨列 Paragraph paragraph = null; for (int i = 0; i < tableColList.length; i++) { String colInfo = tableColList[i]; String colStr = colInfo.indexOf("#PAGINATION#") >= 0 ? colInfo.substring(0,colInfo.indexOf("#PAGINATION#")) : colInfo; colStr = colStr.indexOf("#NOBORDER#") >= 0 ? colStr.substring(0,colStr.indexOf("#PAGINATION#")) : colStr; int col = Integer.parseInt(colStr); boolean flag = false; // 判断是否存在图片 if (tableCaptionList.length > 0) { //添加标题 //paragraph = new Paragraph(""+tableCaptionList[i].replaceAll("#IMG#", ""),ReportFontFactory.getFontChinese(Font_Type.TITLE)); paragraph = new Paragraph(""+tableCaptionList[i].replaceAll("#IMG#", ""),ReportFontFactory.getFontCambodia(Font_Type.TITLE)); paragraph.setAlignment(Paragraph.ALIGN_CENTER); paragraph.setSpacingAfter(4); paragraph.setSpacingBefore(10); document.add(paragraph); flag = tableCaptionList[i].indexOf("#IMG#") >= 0 ? true : false; } if (col > 0) { // table = new PdfPTable(col); // table.setWidthPercentage(98f);// 设置table宽度所占百分比 // table.setHeaderRows(0);// 0:可导出一行 // table.setHorizontalAlignment(Element.ALIGN_CENTER); // table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER); // ----- table = new Table(col); table.setWidth(100f); table.setBorder(0); table.setAutoFillEmptyCells(true); table.setPadding(2); // table.setAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); if(widthList.length>i)// 说明:设置表格第一行所有列的width属性 { String[] width = widthList[i].split(","); if (width.length > 0 ) { int [] ai = new int[width.length]; for (int j = 0; j < width.length; j++) { if (!"".equals(width[j].trim())) { ai[j] = Integer.parseInt(width[j]); } } table.setWidths(ai); // 设置表格Cell的宽度,注意列的数量 } } String[] rows = null; Object[][] cellInfo = null; for (int j = 0; j < tableList.length; j++) { if (i == j) { rows = tableList[j].split("#ROW#"); for (int k = 0; k < rows.length; k++) { String cells[] = rows[k].split("#TD#"); if (cellInfo == null) { cellInfo = new Object[rows.length][cells.length]; } cellInfo[k] = cells; } //生成PDF数据 for(int k=0;k<cellInfo.length;k++){ Object[] datapdf=cellInfo[k]; // if (datapdf.length==1) { // String e = URLEncoder.encode(datapdf[0].toString() , "utf-8").replaceAll("%C2%A0", ""); // e = URLDecoder.decode(e , "utf-8"); // if ("".equals("")) { // break; // } // } for (int l = 0; l < datapdf.length; l++) { if (flag) { String url = datapdf[l].toString().trim(); // http 形式的url if (!"".equals(url)) { // 转换成绝对路径得url // String path = request.getSession().getServletContext().getRealPath("/") + "temp" + "/" + url.substring(url.lastIndexOf('/')+1); // Image img = Image.getInstance(URLDecoder.decode(path,"utf-8")); Image img = Image.getInstance(URLDecoder.decode(datapdf[l].toString().trim(),"utf-8")); // 设置图片的对齐方式 img.setAlignment(1); // 设置图片的绝对宽度和高度 img.scaleAbsoluteWidth(400); img.scaleAbsoluteHeight(400); document.add(img); document.newPage(); } }else { String value = datapdf[l].toString().indexOf("#COLSPAN#") >= 0 ? datapdf[l].toString().substring(0,datapdf[l].toString().indexOf("#COLSPAN#")) : datapdf[l].toString(); value = value.indexOf("#ROWSPAN#") >= 0 ? value.substring(0,value.indexOf("#ROWSPAN#")) : value; value = value.indexOf("#ALIGN#") >= 0 ? value.substring(value.indexOf("#ALIGN#")+7) : value; value = value.indexOf("#VALIGN#") >= 0 ? value.substring(value.indexOf("#VALIGN#")+8) : value; //paragraph=new Paragraph(value.trim() , ReportFontFactory.getFontChinese(Font_Type.CONTENT)); paragraph=new Paragraph(value.trim() , ReportFontFactory.getFontCambodia(Font_Type.CONTENT)); // cell= new PdfPCell(paragraph); cell= new Cell(paragraph); if (colInfo.indexOf("#NOBORDER#") >= 0) { cell.setBorder(0); } cellStyleConsole(cell , datapdf[l].toString()); table.addCell(cell); } } } } } if (colInfo.indexOf("#PAGINATION#") >= 0) { table.deleteLastRow(); } if (flag) { table.deleteLastRow(); } //添加table到Document对象中 document.add(table); if (colInfo.indexOf("#PAGINATION#") >= 0) { document.newPage(); } } } //关闭document document.close(); //生成pdf文档品并响应客户端 response.setContentLength(bos.size()); ServletOutputStream out = response.getOutputStream(); response.setContentLength(bos.size()); bos.writeTo(out); out.flush(); out.close(); bos.flush(); bos.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if (document.isOpen()) { //关闭document document.close(); } } } /** * * Cell样式控制:跨行、跨列、居中 * 说明:不能同时跨行跨列 * @param cell * @param context */ // public void cellStyleConsole(PdfPCell cell, String context) { public void cellStyleConsole(Cell cell, String context) { // 默认 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中 // cell.setNoWrap(false); // 自动换行 cell.setHorizontalAlignment(Element.ALIGN_LEFT); int colspan = 0; int rowspan = 0; if (context.indexOf("#ROWSPAN#") >= 0 && context.indexOf("#COLSPAN#") >= 0) {// 跨行且跨列 colspan = Integer.parseInt(context.substring(context.indexOf("#COLSPAN#")+9).trim()); rowspan = Integer.parseInt(context.substring(context.indexOf("#ROWSPAN#")+9 , context.indexOf("#COLSPAN#")).trim()); cell.setRowspan(rowspan); cell.setColspan(colspan); }else if (context.indexOf("#ROWSPAN#") >= 0) {// 跨行 rowspan = Integer.parseInt(context.substring(context.indexOf("#ROWSPAN#")+9).trim()); cell.setRowspan(rowspan); }else if (context.indexOf("#COLSPAN#") >= 0) {// 跨列 colspan = Integer.parseInt(context.substring(context.indexOf("#COLSPAN#")+9).trim()); cell.setColspan(colspan); } // 位置设置:居中、右、左对齐 if (context.indexOf("#ALIGN#") >=0) { String align = context.substring(0, context.indexOf("#ALIGN#")).trim(); if ("right".equals(align)) { cell.setHorizontalAlignment(Element.ALIGN_RIGHT); }else if ("left".equals(align)) { cell.setHorizontalAlignment(Element.ALIGN_LEFT); }else if ("center".equals(align)) { cell.setHorizontalAlignment(Element.ALIGN_CENTER); } } // 垂直对齐方式: if (context.indexOf("#VALIGN#") >=0) { String vAlign = context.substring(context.indexOf("#ALIGN#")>=0?(context.indexOf("#ALIGN#")+7):0, context.indexOf("#VALIGN#")).trim(); if ("top".equals(vAlign)) { cell.setVerticalAlignment(Element.ALIGN_TOP); }else if ("bottom".equals(vAlign)) { cell.setVerticalAlignment(Element.ALIGN_BOTTOM); }else if ("middle".equals(vAlign)) { cell.setVerticalAlignment(Element.ALIGN_MIDDLE); } } } } 7. [文件] ExportReportForJPG.java ~ 3KB 下载(5) 跳至 [1] [2] [3] [4] [6] [7] [8] [9] [10] [11] [全屏预览] ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 package cls.taishan.util.report.impl; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.net.URLEncoder; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cls.taishan.util.report.intf.IExportReport; /** * Function 生成图片(JPG)报表 * CreateTime 2014年7月22日 * @author yyh * @version 1.1.0 */ public class ExportReportForJPG implements IExportReport{ /** * Function 生成图片(JPG)报表 * CreateTime 2014年7月22日 * @author yyh * @version 1.1.0 * @param HttpServletRequest request * @param HttpServletResponse response * @param Map<?,?> reportInfo 生成报表所需要的数据 */ @Override public void createReport(HttpServletRequest request, HttpServletResponse response, Map<?, ?> reportInfo) throws Exception { //判断生成数据是否为空 if(reportInfo.get("cellInfo")==null){ throw new Exception("没有导出数据"); } //设置文件响应信息 String showFileName =URLEncoder.encode(reportInfo.get("title") + ".jpg", "UTF-8"); showFileName = new String(showFileName.getBytes("iso8859-1"), "gb2312"); //定义输出类型 response.reset(); response.setContentType("image/jpeg"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "max-age=30"); response.setHeader("Content-disposition", "attachment; filename="+ new String(showFileName.getBytes("gb2312"), "iso8859-1")); //创建一个图像 String [] header=(String[])reportInfo.get("header"); int width = header.length*360,height =768; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //得到图形环境对象 Graphics graphics = image.getGraphics(); //填充背景 graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, width, height); graphics.setColor(Color.WHITE); graphics.fillRect(11, 35, width-21, height-47); graphics.setColor(Color.BLACK); graphics.drawRect(10, 35, width-20, height-46); graphics.setColor(Color.black); graphics.setFont(new Font("宋体", Font.BOLD, 28)); graphics.drawString(""+reportInfo.get("title"), width/2, 25); //生成表头 for(int i=0;i<header.length;i++){ graphics.setColor(Color.black); graphics.setFont(new Font("宋体", Font.PLAIN, 24)); graphics.drawString(header[i],i*345+20,60); } //生成Image数据 Object[][] datas=(Object[][])reportInfo.get("cellInfo"); for(int i=0;i<datas.length;i++){ Object[] data=datas[i]; for(int j=0;j<data.length;j++){ graphics.setColor(Color.BLACK); graphics.setFont(new Font("宋体", Font.PLAIN, 18)); graphics.drawString(""+data[j],j*345+20,(i+3)*35); } } //利用ImageIO类的write方法对图像输出 ServletOutputStream sos = response.getOutputStream(); ImageIO.write(image, "jpeg", sos); sos.flush(); sos.close(); } } 8. [文件] IExportReport.java ~ 663B 下载(5) ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package cls.taishan.util.report.intf; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface IExportReport { /** * 功能描述:定义字体类型 * 创建时间:2014-07-22 * @author yyh * */ public enum ReportType { JPG, PDF, Excel, Word } /** * 功能描述:根据data创建报表 * @param HttpServletRequest request * @param HttpServletResponse response * @param Map data * @throws Exception */ public void createReport(HttpServletRequest request,HttpServletResponse response,Map<?,?> reportInfo) throws Exception; } package cls.taishan.util.report.tags; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.PageContext; /** * Function 动态生成JS * CreateTime 2014年7月22日 * @author yyh * @version 1.1.0 */ public class ERTagUtil { /** * Function 创建js文件 * CreateTime 2014年7月22日 * @author yyh * @param pageContext * @version 1.1.0 */ public void createReportJS(PageContext pageContext){ try{ HttpServletRequest request=(HttpServletRequest)pageContext.getRequest(); // String root=request.getRealPath("/"); String root=request.getSession().getServletContext().getRealPath("/"); File file=new File(root,"er_js"); if(!file.exists()){ file.mkdir(); } //生成Report JS String createPath=root+"er_js\\"; file=new File(createPath,"export_report.js"); if(!file.exists()){ file.createNewFile(); createJs(root,createPath); } }catch(Exception e){ e.printStackTrace(); } } /** * Function 将js文件拷贝到服务器下 * CreateTime 2014年7月22日 * @author yyh * @param root * @param createPath * @version 1.1.0 */ private void createJs(String root,String createPath){ try { InputStream is=this.getClass().getResourceAsStream("/META-INF/export_report.js"); BufferedReader br=new BufferedReader(new InputStreamReader(is)); FileWriter fw = new FileWriter(createPath+"\\export_report.js"); BufferedWriter bw = new BufferedWriter(fw); String myreadline; while (br.ready()) { myreadline = br.readLine(); bw.write(myreadline); bw.newLine(); } bw.close(); br.close(); fw.close(); br.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } } package cls.taishan.util.report.tags; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager; /** * Function:报表导出标签 * CreateTime:2014年7月22日 * @author yyh * @version 1.1.0 * */ public class ExportReportTag extends BodyTagSupport{ /** * */ private static final long serialVersionUID = 1L; private Object tableId; //tableID // private String tableId; //tableID private String title; //文档标题 private String tableTitle; //Table的标题 private String types; //报表类型(支持pdf,word,excel,jpg) private String url; //请求路径 private String classs; //样式 private String icons; // private String imageId; //图片id private String imageUrl; //图片url @Override public int doEndTag() throws JspException { JspWriter out = pageContext.getOut(); try { //new ERTagUtil().createReportJS(pageContext); HttpServletRequest request=(HttpServletRequest)pageContext.getRequest(); out.print("<script type=\"text/javascript\" src=\""+request.getContextPath()+"/js/export_report.js\"></script>"); } catch (Exception e) { e.printStackTrace(); } return super.doEndTag(); } @Override public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); try{ String er_types []=(null!=this.getTypes() && !"".equals(this.getTypes())) ? this.getTypes().split(",") : null; String er_classs []=(null!=this.getClasss() && !"".equals(this.getClasss())) ? this.getClasss().split(",") : null; String er_icons []=(null!=this.getIcons() && !"".equals(this.getIcons())) ? this.getIcons().split(",") : null; StringBuffer sbER=new StringBuffer(); if(null!=er_types && er_types.length>0){ for(int i=0;i<er_types.length;i++){ if(null!=er_types[i] && !"".equals(er_types[i].trim()) && "pdf".equalsIgnoreCase(er_types[i])){ sbER.append(" <a id=\"expor_pdf\" class=\""+getStypeC(er_classs,i)+"\" icon=\""+getStyleIcon(er_icons,i)+"\" href=\"javascript:export_report('"+this.tableId+"','pdf','"+this.title+"','"+this.url+ "','" + this.imageId + "');\" >导出"+er_types[i]+"</a>"); } if(null!=er_types[i] && !"".equals(er_types[i].trim()) && "excel".equalsIgnoreCase(er_types[i])){ sbER.append(" <a id=\"expor_excel\" class=\""+getStypeC(er_classs,i)+"\" icon=\""+getStyleIcon(er_icons,i)+"\" href=\"javascript:export_report('"+this.tableId+"','excel','"+this.title+"','"+this.url+ "','" + this.imageId + "');\" >导出"+er_types[i]+"</a>"); } if(null!=er_types[i] && !"".equals(er_types[i].trim()) && "word".equalsIgnoreCase(er_types[i])){ sbER.append(" <a id=\"expor_word\" class=\""+getStypeC(er_classs,i)+"\" icon=\""+getStyleIcon(er_icons,i)+"\" href=\"javascript:export_report('"+this.tableId+"','word','"+this.title+"','"+this.url+ "','" + this.imageId + "');\" >导出"+er_types[i]+"</a>"); } if(null!=er_types[i] && !"".equals(er_types[i].trim()) && "jpg".equalsIgnoreCase(er_types[i])){ sbER.append(" <a id=\"expor_Jpg\" class=\""+getStypeC(er_classs,i)+"\" icon=\""+getStyleIcon(er_icons,i)+"\" href=\"javascript:export_report('"+this.tableId+"','jpg','"+this.title+"','"+this.url+"');\" >导出"+er_types[i]+"</a>"); } } out.print(sbER); } }catch(Exception e){ e.printStackTrace(); } return super.doStartTag(); } /** * Function:报表导出标签 * CreateTime:2014年7月22日 * @author yyh * @param er_classs * @param i * @return String 当前有效样式 */ private String getStypeC(String[] er_classs ,int i){ String cl = ""; if (null != er_classs && er_classs.length > 0) { if (er_classs.length > 1 && er_classs.length>=(i+1)) { cl = er_classs[i]; } else { cl = er_classs[er_classs.length - 1]; } } return cl; } /** * Function:报表导出标签 * CreateTime:2014年7月22日 * @author chenck * @param er_icons * @param i * @return 当前有效icon */ private String getStyleIcon(String[] er_icons ,int i){ String icon=""; if(null!=er_icons && er_icons.length>0 ){ if(er_icons.length>1 && er_icons.length>=(i+1)){ icon=(null!=er_icons[i]) ? er_icons[i] : er_icons[0]; }else{ icon=er_icons[er_icons.length-1]; } } return icon; } public Object getTableId() { return tableId; } public void setTableId(Object tableId) throws JspException { this.tableId = (String) ExpressionEvaluatorManager.evaluate("tableId", tableId.toString(), Object.class, this, pageContext); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTableTitle() { return tableTitle; } public void setTableTitle(String tableTitle) { this.tableTitle = tableTitle; } public String getTypes() { return types; } public void setTypes(String types) { this.types = types; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getClasss() { return classs; } public void setClasss(String classs) { this.classs = classs; } public String getIcons() { return icons; } public void setIcons(String icons) { this.icons = icons; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } } /** * => 将要导出为 文档的<Ttable>内容,以字符串形式传递到后台 * => 实现导出多个<Table>、多个<img> * * 图片导出说明::前台<table>必须包含<caption>元素 * * @param {Object} tableId 表示<Table>的id: 此方法中是使用匹配id的方式来传递多个<Table>的内容,以便导出 * @param {Object} type 导出的类型(pdf、excel、jpg、doc) * @param {Object} title 导出文件的标题 * @param {Object} url servlet URL * @param {Object} imgId 表示<img>的id * @memberOf {TypeName} * @return {TypeName} * @author yyh 2014年7月22日 */ function export_report(tableId, type, title ,url, imgId ) { var tableBody = ""; var tableCaption = ""; // 从<caption>中取<Table>的标题 var tableCol = ""; // 表示table的列数 var widthTD = ""; // 用于存储每个table的所有列的宽度值,列与列的分隔符“,”,表与表的分隔符“;” $("table[id^=" + tableId + "]").each(function(j, _table) { var len = $("#" + $(this).attr("id") + " img").size(); if( len > 0 ) { var url = ""; $("#" + $(this).attr("id") + " img").each(function(){ url += $(this).attr("src") + " #TD#"; //以每一张图片作为一个TD }); tableCaption += "#IMG#"; //用于标识图片table tableCol = tableCol + 1 + ";" ; tableBody += url + " #TD#"; // 作为Cell<td>分隔符 tableBody += "#ROW#"; // 作为Row<tr>分隔符 } else { var col = 0; $("#" + $(this).attr("id") + " tr").each(function(i, _tr) { $(_tr).children().each(function(k, _td) { var colspan = $(_td).attr("colspan"); var rowspan = $(_td).attr("rowspan"); var align = $(_td).attr("align"); var valign = $(_td).attr("valign"); if(align != ""){ tableBody += align + "#ALIGN#"; } if(valign != ""){ tableBody += valign + "#VALIGN#"; } if (i == 0) { var width = $(_td).attr("width"); // 说明:设置表格第一行所有列的width属性 if(colspan > 1){ // 跨列 col = col + colspan; if(width > 0){ for(var t = 0;t < colspan;t++){ // 第一行中存在跨列的情况下,平均分配列宽 widthTD += width/colspan + ","; } } }else{ col ++; if(width > 0){ widthTD += width + ","; } } } if(colspan > 1){ // 跨列 if(rowspan > 1){ // 跨行 tableBody += $.trim($(_td).text()) + "#ROWSPAN#" + rowspan + "#COLSPAN#" + colspan + " #TD#"; }else{ tableBody += $.trim($(_td).text()) + "#COLSPAN#" + colspan + " #TD#";// 作为Cell<td>分隔符 } }else{ if(rowspan > 1){ // 跨行 tableBody += $.trim($(_td).text()) + "#ROWSPAN#" + rowspan + " #TD#"; }else{ tableBody += $.trim($(_td).text()) + " #TD#";// 作为Cell<td>分隔符 } } }); tableBody += "#ROW#"; // 作为Row<tr>分隔符 }); tableCol = tableCol + col; if($("#" + $(this).attr("id") + " input[id=pagination]").length>0) { tableCol += "#PAGINATION#";// 用来判断是否分页的标识,在需要分页的表格后边加上一个<input id="pagination" type="hidden">用来new Page } if($("#" + $(this).attr("id") + " input[id=noBorder]").length>0) { tableCol += "#NOBORDER#"; // 用来判断是否显示边框的标识,在需要分页的表格后边加上一个<input id="noBorder" type="hidden"> } tableCol += ";" ; } widthTD += ";"; tableBody += "#TABLE#"; // 作为Table<table>分隔符 tableCaption += $("#" + $(this).attr("id") + " caption").text() + "#CAPTION#"; }); if (tableBody == "") { alert("TableBody Error!"); return false; } $("#export_report_div").remove(); var dataDiv = "<div id='export_report_div'>"; dataDiv += "<form action='" + url + "' method='post' id='report_export_form'>" dataDiv += "<input type='hidden' name='title' value='" + title + "' />"; dataDiv += "<input type='hidden' name='type' value='" + type + "'/>"; dataDiv += "<input type='hidden' name='tableCol' value='" + tableCol + "'/>"; dataDiv += "<input type='hidden' name='tableBody' value='" + tableBody + "'/>"; dataDiv += "<input type='hidden' name='tableCaption' value='" + tableCaption+ "'/>"; dataDiv += "<input type='hidden' name='widthTD' value='" + widthTD+ "'/>"; dataDiv += "</form>"; dataDiv += "</div>"; $(document.body).append(dataDiv); $("#report_export_form").submit(); }
试试其它关键字
导出pdf
excel
word
同语言下
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
yuyuanhua
贡献的其它代码
(
2
)
.
使用PHPMailer发送邮件方法
.
导出pdf,excel,word
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3