导出各种类型的文件的简单方法(暂时)
把html导出为excel或者word文档1.jsp页面简单导出
导出为excel:
<% response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition","attachment;filename=test.xls");//这里的filename如果是中文的话,需要先把中文转成utf8编码%>
导出为word:
<% response.setContentType("application/msword;charset=UTF-8"); response.setHeader("Content-Disposition","attachment;filename=test.doc"); %>
2.pdf 导出
步骤1: 写出html模板 muban.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><title>无标题文档</title><style type="text/css">div *{font-size:10px;}</style></head> <body style="width:900px; margin:auto ;padding-top:15px;"><table cellspacing="0" border="1" cellpadding="0" width="80%"><tr> <td width="45%"> <p id="post">#邮政编码</p> <p id="addr">#地址</p> <p id="addr2">#具体地址(几号楼几单元几室)</p> <p userName="userName">#userName&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;亲启</p> </td> <td > <img src="ad.jpg" /> </td> </tr></table><h3 style="padding-left:280px;">债权转让及受让协议</h3><div><p userName="userName">尊敬的&nbsp;&nbsp; #userName &nbsp;&nbsp;先生 ,您好!</p><p id="date">通过宜信公司信用评估与筛选,推荐您&nbsp; #date &nbsp;通过受让他人既有的个人间借贷合同的方式,出借资金给如下借款人,</p><p>详见《债权列表》,在您接受该批债权转让并按时支付对价的情况下,预期您的出借获益情况如下: 货币单位:人民币(元)</p><table cellspacing="0" border="1" cellpadding="0" ><tr id="lenderAcountInfo"> <th style='width:100px;align:center;'>出借编号</th> <th style='width:100px;align:center;'>资金出借及<br/>回收方式</th> <th style='width:100px;align:center;'>初始出借日期</th> <th style='width:100px;align:center;'>初始出借金额</th> <th style='width:100px;align:center;'>下一个报告日</th> <th style='width:100px;align:center;'>下一个报告期借款人<br/>应还款额</th> <th style='width:100px;align:center;'>账户管理费</th> <th style='width:100px;align:center;'>预计下一个报告日您的<br/>资产总额</th> </tr></table></div></body></html>
步骤2: 写出 Pdf 类,这个类用于生成你想要的pdf文件,包括往模板内填充数据,以及导出!
import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.OutputStream;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;import org.xhtmlrenderer.pdf.ITextRenderer;public class Pdf {private Document document;private String fileTemplete;public Pdf() {super();}/** * 通过构造方法获取pdf类的基本模板样式 * @param fileTemplete * @throws Exception */public Pdf(String fileTemplete) throws Exception {super();//初始化documentdocument = this.getHTMLTemplete(fileTemplete);}public void createPdf() throws Exception {String outputFile = "test.pdf";OutputStream os = new FileOutputStream(outputFile);ITextRenderer renderer = new ITextRenderer();//得到最终html对象String html = document.html();//设置pdf内容renderer.setDocumentFromString(html);// 解决图片的相对路径问题renderer.getSharedContext().setBaseURL("file:/E:/");//设置pdf样式renderer.layout();//最终生成pdfrenderer.createPDF(os);os.close();System.out.println("生成成功!");}/** * 获取模板 * @param templeteName * @return * @throws Exception */publicDocument getHTMLTemplete(String templeteName) throws Exception {String path = Test.class.getResource("/").getPath();File file = new File(path + templeteName);Document document = Jsoup.parse(file, "GBK");return document;}/** * 设置用户名 * @param userName */public void setUserName(String userName) {Elements es = document.getElementsByAttribute("userName");for(Element e:es){String s=e.html();String[] text=s.split("#userName");if(text.length==2){s=text+userName+text;}else if(text.length==1)s=userName+text;e.html(s);}}/** * 设置邮编 * @param post */public void setPost(String post) {Element e = document.getElementById("post");e.html(post);}/** * 设置地址 * @param addr */public void setAddr( String addr) {Element e = document.getElementById("addr");e.html(addr);}/** * 设置详细地址 * @param addr2 */public void setAddr2( String addr2) {Element e = document.getElementById("addr2");e.html(addr2);}/** * 设置日期 * @param date */public void setDate( String date) {Element e = document.getElementById("date");String s=e.html();String[] text=s.split("#date");if(text.length==2){s=text+date+text;}else if(text.length==1)s=date+text;e.html(s);}/** * 设置出借人账户收益信息 * @param info */public void setLenderAccountInfo(String info){Element e = document.getElementById("lenderAcountInfo");e.after(info);}public Document getDocument() {return document;}public void setDocument(Document document) {this.document = document;}public String getFileTemplete() {return fileTemplete;}public void setFileTemplete(String fileTemplete) {this.fileTemplete = fileTemplete;}}
步骤3:测试类PdfTest
import junit.framework.TestCase;public class PdfTest extends TestCase {@Overrideprotected void setUp() throws Exception {super.setUp();}@Overrideprotected void tearDown() throws Exception {super.tearDown();}public void testPdf() throws Exception{Pdf pdf=new Pdf("/muban.html"); //使用哪个模板//以下部分为往模板内填数据pdf.setPost("100000");pdf.setUserName("张伟");//填用户名pdf.setAddr("北京市朝阳区红领巾南路朝阳园");//设置地址pdf.setAddr2("9号楼1单元801室");//设置具体地址pdf.setDate("2010-08-10");//设置日期参数String info="<tr>" +"<td>8808010100029781-005</td>" +"<td >宜信宝</td>" + "<td>宜信宝2010-08-12</td>" +"<td>1,200,000.00</td>" +"<td>2010-08-30</td>" +"<td>64,368.82</td>" +"<td>0.00</td>" +"<td>1,207,499.14</td>" +"</tr>";pdf.setLenderAccountInfo(info);//生成pdfpdf.createPdf();}}
最后,jar包,放出供各位下载!
3.由于最近的项目只有导出word功能,没有导出pdf功能,而又不想再做导出pdf的工作,于是使用word直接转换成pdf的方式获得pdf文件
提供2种方案:
3.1使用jacob.不过有使用前提,必须先把jar包中的dll文件放到jre/bin下.同时安装adobe acrobat7.0以上版本的软件.再配置下adobe的虚拟打印机,即可.之后运行java类,代码很简单,如下(拷贝自别人):
/** *//*** * @version 1.00, 2007-4-9**/import java.io.File;import com.jacob.activeX.ActiveXComponent;import com.jacob.com.ComThread;import com.jacob.com.Dispatch;import com.jacob.com.Variant;/* * 注意word转pdf要安装虚拟打印机,且要配置 * 使用jacob框架,把dll文件放到jre/bin目录下 */public class WordToPdf { private ActiveXComponent wordCom = null; private Object wordDoc = null; private final Variant False = new Variant(false); private final Variant True = new Variant(true); /** * 打开word文档 * * @param filePath word文档 * @return 返回word文档对象 */ public boolean openWord(String filePath) { //建立ActiveX部件 wordCom = new ActiveXComponent("Word.Application"); try { //返回wrdCom.Documents的Dispatch Dispatch wrdDocs = wordCom.getProperty("Documents").toDispatch(); //调用wrdCom.Documents.Open方法打开指定的word文档,返回wordDoc wordDoc = Dispatch.invoke(wrdDocs, "Open", Dispatch.Method, new Object[] { filePath }, new int).toDispatch(); return true; } catch (Exception ex) { ex.printStackTrace(); } return false; } /** * 关闭word文档 */ public void closeWord(boolean saveOnExit) { if (wordCom!=null) { //关闭word文件 //Dispatch.call(wordDoc, "Close", new Variant(saveOnExit)); wordCom.invoke("Quit",new Variant[]{}); //wordCom.invoke("Quit",new Variant); wordCom=null; //释放在程序线程中引用的其它com,比如Adobe PDFDistiller ComThread.Release(); } } /** * 将word文档打印为PS文件后,使用Distiller将PS文件转换为PDF文件 * * @param sourceFilePath * 源文件路径 * @param destinPSFilePath * 首先生成的PS文件路径 * @param destinPDFFilePath * 生成PDF文件路径 */ public void docToPDF(String sourceFilePath, String destinPSFilePath, String destinPDFFilePath) { if (!openWord(sourceFilePath)) { closeWord(true); return; } //建立Adobe Distiller的com对象 ActiveXComponent distiller = new ActiveXComponent("PDFDistiller.PDFDistiller.1"); try { //设置当前使用的打印机,我的Adobe Distiller打印机名字为 "Adobe PDF" wordCom.setProperty("ActivePrinter", new Variant("Adobe PDF")); //设置printout的参数,将word文档打印为postscript文档。现在只使用了前5个参数,假如要使用更多的话可以参考MSDN的office开发相关api //是否在后台运行 Variant Background = False; //是否追加打印 Variant Append = False; //打印所有文档 int wdPrintAllDocument = 0; Variant Range = new Variant(wdPrintAllDocument); //输出的postscript文件的路径 Variant OutputFileName = new Variant(destinPSFilePath); Dispatch.callN((Dispatch) wordDoc, "PrintOut", new Variant[] { Background, Append, Range, OutputFileName }); System.out.println("由word文档打印为ps文档成功!"); //调用Distiller对象的FileToPDF方法所用的参数,具体内容参考Distiller Api手册 //作为输入的ps文档路径 Variant inputPostScriptFilePath = new Variant(destinPSFilePath); //作为输出的pdf文档的路径 Variant outputPDFFilePath = new Variant(destinPDFFilePath); //定义FileToPDF方法要使用adobe pdf设置文件的路径,在这里没有赋值表示并不使用pdf配置文件 Variant PDFOption = new Variant(""); //调用FileToPDF方法将ps文档转换为pdf文档 Dispatch.callN(distiller, "FileToPDF", new Variant[] { inputPostScriptFilePath, outputPDFFilePath, PDFOption }); System.out.println("由ps文档转换为pdf文档成功!"); } catch (Exception ex) { ex.printStackTrace(); } finally { closeWord(true); } } public static void main(String[] argv) { WordToPdf d2p = new WordToPdf(); d2p.docToPDF("f:\\1043_王燕春_lender账单_2010-06-15_1.doc", "f:\\1043_王燕春_lender账单_2010-06-15_1.ps", "f:\\1043_王燕春_lender账单_2010-06-15_1.pdf");// boolean success = (new File("D:\\test.ps")).delete();// if(success){// System.out.println("删除打印机文件成功");// } } }
3.2 但是由于公司服务器在linux上跑,jacob不适用,于是使用openOffice+jodconverter,实现很不错哦!不想再写字了,直接上工程吧,呵呵!
有些前提限制,原版说明如下:
JODConverter needs to connect to a running OpenOffice.org instance in order to perform the document conversions. This is different from starting the OpenOffice.org program as you would normally do. OpenOffice.org can be configured to run as a service and listen for commands on a TCP port; there are a few ways to accomplish this but the simplest one is to start it from the command line with the following options: soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
附件中有的下载!提供io流的方式转换pdf!自创!
页:
[1]