JAVA生成WORD文件的方法目前有以下兩種方式:
一種是jacob 但是局限於windows平台 往往許多JAVA程序運行於其他操作系統 在此不討論該方案;
一種是poi但是他的excel處理很程序 word模塊還局限於讀取word的文本內容,寫word文件就更弱項了.
用到的jar包:
iText-2.1.5.jar
iText-rtf-2.1.4.jar
iTextAsian.jar
/**
* 創建word文檔 步驟:
* 1,建立文檔
* 2,創建一個書寫器
* 3,打開文檔
* 4,向文檔中寫入數據
* 5,關閉文檔
*/
/** * * @Description: 將網頁內容導出為word * @param @param file * @param @throws DocumentException * @param @throws IOException 設定文件 * @return void 返回類型 * @throws */ public String exportDoc() throws DocumentException, IOException { // 設置紙張大小 Document document = new Document(PageSize.A4); // 建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁盤中 // ByteArrayOutputStream baos = new ByteArrayOutputStream(); File file = new File("D://report.doc"); RtfWriter2.getInstance(document, new FileOutputStream(file)); document.open(); // 設置中文字體 BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // 標題字體風格 Font titleFont = new Font(bfChinese, 12, Font.BOLD); // // 正文字體風格 // Font contextFont = new Font(bfChinese, 10, Font.NORMAL); Paragraph title = new Paragraph("統計報告"); // // 設置標題格式對齊方式 title.setAlignment(Element.ALIGN_CENTER); // title.setFont(titleFont); document.add(title); String contextString = "iText是一個能夠快速產生PDF文件的java類庫。" + " \n"// 換行 + "iText的java類對於那些要產生包含文本," + "表格,圖形的只讀文檔是很有用的。它的類庫尤其與java Servlet有很好的給合。" + "使用iText與PDF能夠使你正確的控制Servlet的輸出。"; Paragraph context = new Paragraph(contextString); // 正文格式左對齊 context.setAlignment(Element.ALIGN_LEFT); // context.setFont(contextFont); // 離上一段落(標題)空的行數 context.setSpacingBefore(5); // 設置第一行空的列數 context.setFirstLineIndent(20); document.add(context); // // // 利用類FontFactory結合Font和Color可以設置各種各樣字體樣式 // // Paragraph underline = new Paragraph("下划線的實現", FontFactory.getFont( // FontFactory.HELVETICA_BOLDOBLIQUE, 18, Font.UNDERLINE, // new Color(0, 0, 255))); // // document.add(underline); // // // 添加圖片 Image.getInstance即可以放路徑又可以放二進制字節流 // String imageString[] = imageFileUrl.split(","); Image img = Image.getInstance(Base64.decodeFast(imageString[1])); img.setAbsolutePosition(0, 0); img.setAlignment(Image.LEFT);// 設置圖片顯示位置 // // img.scaleAbsolute(60, 60);// 直接設定顯示尺寸 // // // img.scalePercent(50);//表示顯示的大小為原尺寸的50% // // // img.scalePercent(25, 12);//圖像高寬的顯示比例 // // // img.setRotation(30);//圖像旋轉一定角度 // document.add(img); document.close(); // 得到輸入流 // wordFile = new ByteArrayInputStream(baos.toByteArray()); // baos.close(); return ""; }
生成的文檔可以直接在程序中指定文件保存的路徑,也可以給瀏覽器一個輸入流,從瀏覽器中導出,具體實現有如上述程序中注釋掉的幾句代碼。