Java生产WORD并下载到本地

合集下载

Java使用Poi-tlword模板导出word

Java使用Poi-tlword模板导出word

Java使⽤Poi-tlword模板导出word 1.导⼊依赖<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.7.3</version></dependency>2.新建⼀个word,制作导出模板模板放⼊ resource/static/word/template⽂件夹下3.编写⼯具类⼯具类--WordExportServer.javapublic class WordExportServer {/*** 导出word**/public static void export(WordExportData wordExportData) throws IOException {HttpServletResponse response=wordExportData.getResponse();OutputStream out = response.getOutputStream();;XWPFTemplate template =null;try{ClassPathResource classPathResource = new ClassPathResource(wordExportData.getTemplateDocPath());String resource = classPathResource.getURL().getPath();resource= PdfUtil1.handleFontPath(resource);//渲染表格HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();Configure config = Configure.newBuilder().bind(wordExportData.getTableDataField(), policy).build();template = pile(resource, config).render(wordExportData.getWordData());String fileName=getFileName(wordExportData);/** ===============⽣成word到设置浏览默认下载地址=============== **/// 设置强制下载不打开response.setContentType("application/force-download");// 设置⽂件名response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);template.write(out);}catch (Exception e){e.printStackTrace();}finally {out.flush();out.close();template.close();}}/*** 获取导出下载的word名称* @param wordExportData* @return ng.String**/public static String getFileName(WordExportData wordExportData){if(null !=wordExportData.getFileName()){return wordExportData.getFileName()+".docx";}return System.currentTimeMillis()+".docx";}}word数据包装类--WordExportData .java@Datapublic class WordExportData {/*** word模板路径(static/wordTemplate/dealerListDocTemplate.docx)**/private String templateDocPath;/*** word填充数据(key值与模板中的key值要保持⼀致)**/private Map<String,Object> wordData;/*** word表格数据key值**/private String tableDataField;/*** word导出后的⽂件名(不填则⽤当前时间代替)**/private String fileName;private HttpServletResponse response;}4.controller层调⽤@RequestMapping("/printWord")public void printWord(HttpServletRequest request, HttpServletResponse response) throws IOException{String[] ids=request.getParameter("ids").split(";");List<DealerDto> goodsDataList=goodsService.getDealerListByIds(ids);Map<String,Object> docData=new HashMap<>(3);docData.put("detailList",goodsDataList);docData.put("title",标题);docData.put("subTitle",副标题);WordExportData wordExportData=new WordExportData();wordExportData.setResponse(response);wordExportData.setTableDataField("detailList");wordExportData.setTemplateDocPath(DEALER_DOC_TEMPLATE_PATH);//副本存放路径wordExportData.setWordData(docData);WordExportServer.export(wordExportData);}5.前端调⽤var ids = [];for (var index in checkData) {ids.push(checkData[index].id);}var batchIds = ids.join(";");layer.confirm('确定下载选中的数据吗?', function (index) {layer.close(index);window.location.href ='/goods/printWord?ids=' + batchIds;});6.总结优点:使⽤⽅法很简单,使⽤⼯具类的⽅法,⽅便复⽤于其他模块。

java根据模板生成pdf文件并导出

java根据模板生成pdf文件并导出

java根据模板生成pdf文件并导出首先你的制作一个pdf模板:1.先用word做出模板界面2.文件另存为pdf格式文件3.通过Adobe Acrobat pro软件打开刚刚用word转换成的pdf文件(注:如果没有这个软件可以通过我的百度云下载,链接:/s/1pL2klzt)如果无法下载可以联系博主。

4.点击右边的"准备表单"按钮,选择"测试.pdf"选择开始进去到编辑页面,打开后它会自动侦测并命名表单域,右键表单域,点击属性,出现文本域属性对话框(其实无需任何操作,一般情况下不需要修改什么东西,至少我没有修改哦。

如果你想修改fill1等信息,可以进行修改)5.做完上面的工作后,直接"另存为"将pdf存储就可以****************************************************************** ***********以上部分是制作pdf模板操作,上述完成后,就开始通过程序来根据pdf模板生成pdf文件了,上java程序:1.首先需要依赖包:itext的jar包,我是maven项目,所以附上maven依赖[html] view plain copy print?&lt;!--https:///artifact/com.itextpdf/itextpdf--&gt; &lt;dependency&gt;&lt;groupId&gt;com.itextpdf&lt;/groupId&gt;&lt;artifactId&gt;itextpdf&lt;/artifactId&gt;&lt;version&gt;5.5.10&lt;/version&gt;&lt;/dependency&gt; [html] view plain copy print?&lt;!-- https:///artifact/com.itextpdf/itext-asian --&gt; &lt;span style="white-space:pre;"&gt;&lt;/span&gt;&lt;dependency&gt; &lt;spanstyle="white-space:pre;"&gt; &lt;/span&gt;&lt;groupId&gt;com.itextpdf&lt;/groupId&gt; &lt;span style="white-space:pre;"&gt; &lt;/span&gt;&lt;artifactId&gt;itext-asian&lt;/artifactId&gt; &lt;span style="white-space:pre;"&gt; &lt;/span&gt;&lt;version&gt;5.2.0&lt;/version&gt; &lt;spanstyle="white-space:pre;"&gt;&lt;/span&gt;&lt;/dependency&gt; 2.下面就是生成pdf代码了[java] view plain copy print?importjava.io.ByteArrayOutputStream; importjava.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; importcom.itextpdf.text.DocumentException; importcom.itextpdf.text.pdf.AcroFields; importcom.itextpdf.text.pdf.PdfCopy; importcom.itextpdf.text.pdf.PdfImportedPage; importcom.itextpdf.text.pdf.PdfReader; importcom.itextpdf.text.pdf.PdfStamper; public class Snippet { // 利用模板生成pdf public static void fillTemplate() { // 模板路径String templatePath = "E:/测试3.pdf"; // 生成的新文件路径String newPDFPath = "E:/ceshi.pdf"; PdfReader reader; FileOutputStream out; ByteArrayOutputStream bos; PdfStamper stamper; try { out = new FileOutputStream(newPDFPath);// 输出流reader = new PdfReader(templatePath);// 读取pdf模板bos = new ByteArrayOutputStream();stamper = new PdfStamper(reader, bos);AcroFields form = stamper.getAcroFields();String[] str = { "123456789", "TOP__ONE", "男","1991-01-01", "130222111133338888", "河北省保定市" };int i = 0; java.util.Iterator&lt;String&gt; it = form.getFields().keySet().iterator(); while (it.hasNext()) { String name =it.next().toString();System.out.println(name);form.setField(name, str[i++]); }stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为truestamper.close(); Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, out); doc.open(); PdfImportedPage importPage =copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); copy.addPage(importPage);doc.close(); } catch (IOException e){ System.out.println(1); } catch (DocumentException e){ System.out.println(2); }} public static void main(String[] args){ fillTemplate(); } } 3.运行结果如下****************************************************************** ***如果没有模板,就行自己生成pdf文件保存到磁盘:下面的方法可以实现:[java] view plain copy print?public static void test1(){//生成pdf Document document = new Document();try { PdfWriter.getInstance(document, new FileOutputStream("E:/1.pdf"));document.open(); document.add(new Paragraph("hello word"));document.close(); } catch (Exception e){ System.out.println("file create exception"); } } 但是上述方法中包含中文时就会出现问题,所以可以使用下面这行代码实现,所使用的jar包,上面的两个依赖都包含了:[java] view plain copy print?public static voidtest1_1(){ BaseFont bf; Font font = null; try { bf =BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//创建字体font = new Font(bf,12);//使用字体} catch (Exception e){ e.printStackTrace(); }Document document = new Document(); try{ PdfWriter.getInstance(document, new FileOutputStream("E:/2.pdf"));document.open(); document.add(new Paragraph("hello word 你好世界",font));//引用字体document.close(); } catch (Exception e){ System.out.println("file create exception"); } }****************************************************************** ********************当然,如果你想弄的炫一点,想实现其他字体,可以去网上搜字体文件然后下载下来,放到项目里,我这里是在项目里新建了一个font文件夹,将字体文件放到了里面。

java根据模板生成word文档,兼容富文本、图片

java根据模板生成word文档,兼容富文本、图片

java根据模板⽣成word⽂档,兼容富⽂本、图⽚Java⾃动⽣成带图⽚、富⽂本、表格等的word⽂档使⽤技术 freemark+jsoup ⽣成mht格式的伪word⽂档,已经应⽤项⽬中,确实是可⾏的,⽆论是富⽂本中是图⽚还是表格,都能在word中展现出来使⽤jsoup解析富⽂本框,将其中的图⽚进⾏Base64位转码,使⽤freemark替换模板的占位符,将变量以及图⽚资源放⼊模板中在输出⽂件maven地址<!--freemarker--><!--<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version></dependency><!--JavaHTMLParser--><!--<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version></dependency>制作word的freemark模板1. 先将wrod的格式内容定义好,如果需要插⼊参数的地⽅以${xxx}为表⽰,例:${product}模板例⼦: 2. 将模板另存为mht格式的⽂件,打开该⽂件检查每个变量(${product})是否完整,有可能在${}中出现其他代码,需要删除。

3. 将mht⽂件变更⽂件类型,改成ftl为结尾的⽂件,引⼊到项⽬中 4. 修改ftl模板⽂件,在⽂件中加上图⽚资源占位符${imagesBase64String},${imagesXmlHrefString}具体位置如下图所⽰: 5. ftl⽂件中由⼏个关键配置需要引⼊到代码中:docSrcParent = word.filesdocSrcLocationPrex =nextPartId = 01D2C8DD.BC13AF60上⾯三个参数,在模板⽂件中可以找到,需要进⾏配置,如果配置错误,图⽚⽂件将不会显⽰下⾯这三个参数固定,切换模板也不会改变shapeidPrex = _x56fe__x7247__x0020typeid = #_x0000_t75spidPrex = _x0000_i 6. 模板引⼊之后进⾏代码编辑源码地址为:下载源码后需要进⾏调整下内容:1. 录⼊步骤5中的6个参数2. 修改freemark获取模板⽅式下⾯这种⽅式能获取模板,但是在项⽬打包之后⽆法获取jar包内的⽂件Configuration configuration=newConfiguration(Configuration.getVersion());configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());configuration.setDirectoryForTemplateLoading(newFile(templatePath));Template template=configuration.getTemplate("xxx.ftl");通过流的形式直接创建模板对象Configuration configuration=newConfiguration(Configuration.getVersion());configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());configuration.setDirectoryForTemplateLoading(newFile(templatePath));InputStream inputStream=newFileInputStream(newFile(templatePath+"/"+templateName)); InputStreamReader inputStreamReader=newInputStreamReader(inputStream,StandardCharsets.UTF_8); Template template=newTemplate(templateName,inputStreamReader,configuration);。

Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

Java操作word⽂档使⽤JACOB和POI操作word,Excel,PPT需要的jar包可参考⽂档:下载jar包如上是jacob-1.17-M2.jar对应的jar包和dll⽂件....但是我在maven仓库中并没有发现jacob-1.17版本的.所以如果使⽤maven项⽬的话推荐下载jacob-1.14版本的jar包和dll⽂件.使⽤⽅式:import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Arrays;import com.jacob.activeX.ActiveXComponent;public class WriteDoc2 {public static void main(String[] args) {//在正式批量跑之前,做单个word⽂档的测试.WordUtils util = new WordUtils(true);util.openDocument("C:\\Users\\ABC\\Desktop\\test.docx");util.setSaveOnExit(true);util.insertText("xxx444dddd4x");util.saveAs("C:\\Users\\ABC\\Desktop\\test.docx");util.closeDocument();}}对应WordUtils.java⼯具类,我是使⽤的如下:import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;public class WordUtils {// word运⾏程序对象private ActiveXComponent word;// 所有word⽂档集合private Dispatch documents;// word⽂档private Dispatch doc;// 选定的范围或插⼊点private Dispatch selection;// 保存退出private boolean saveOnExit;public WordUtils(boolean visible) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));documents = word.getProperty("Documents").toDispatch();}/*** 设置退出时参数** @param saveOnExit* boolean true-退出时保存⽂件,false-退出时不保存⽂件 */public void setSaveOnExit(boolean saveOnExit) {this.saveOnExit = saveOnExit;}/*** 创建⼀个新的word⽂档*/public void createNewDocument() {doc = Dispatch.call(documents, "Add").toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个已经存在的word⽂档** @param docPath*/public void openDocument(String docPath) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 打开⼀个有密码保护的word⽂档* @param docPath* @param password*/public void openDocument(String docPath, String password) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();unProtect(password);selection = Dispatch.get(word, "Selection").toDispatch();}/*** 去掉密码保护* @param password*/public void unProtect(String password){try{String protectionType = Dispatch.get(doc, "ProtectionType").toString();if(!"-1".equals(protectionType)){Dispatch.call(doc, "Unprotect", password);}}catch(Exception e){e.printStackTrace();}}/*** 添加密码保护* @param password*/public void protect(String password){String protectionType = Dispatch.get(doc, "ProtectionType").toString();if("-1".equals(protectionType)){Dispatch.call(doc, "Protect",new Object[]{new Variant(3), new Variant(true), password});}}/*** 显⽰审阅的最终状态*/public void showFinalState(){Dispatch.call(doc, "AcceptAllRevisionsShown");}/*** 打印预览:*/public void printpreview() {Dispatch.call(doc, "PrintPreView");}/*** 打印*/public void print(){Dispatch.call(doc, "PrintOut");}public void print(String printerName) {word.setProperty("ActivePrinter", new Variant(printerName));print();}/*** 指定打印机名称和打印输出⼯作名称* @param printerName* @param outputName*/public void print(String printerName, String outputName){word.setProperty("ActivePrinter", new Variant(printerName));Dispatch.call(doc, "PrintOut", new Variant[]{new Variant(false), new Variant(false), new Variant(0), new Variant(outputName)}); }/*** 把选定的内容或插⼊点向上移动** @param pos*/public void moveUp(int pos) {move("MoveUp", pos);}/*** 把选定的内容或者插⼊点向下移动** @param pos*/public void moveDown(int pos) {move("MoveDown", pos);}/*** 把选定的内容或者插⼊点向左移动** @param pos*/public void moveLeft(int pos) {move("MoveLeft", pos);}/*** 把选定的内容或者插⼊点向右移动** @param pos*/public void moveRight(int pos) {move("MoveRight", pos);}/*** 把选定的内容或者插⼊点向右移动*/public void moveRight() {Dispatch.call(getSelection(), "MoveRight");}/*** 把选定的内容或者插⼊点向指定的⽅向移动* @param actionName* @param pos*/private void move(String actionName, int pos) {for (int i = 0; i < pos; i++)Dispatch.call(getSelection(), actionName);}/*** 把插⼊点移动到⽂件⾸位置*/public void moveStart(){Dispatch.call(getSelection(), "HomeKey", new Variant(6));}/*** 把插⼊点移动到⽂件末尾位置*/public void moveEnd(){Dispatch.call(getSelection(), "EndKey", new Variant(6));}/*** 插⼊换页符*/public void newPage(){Dispatch.call(getSelection(), "InsertBreak");}public void nextPage(){moveEnd();moveDown(1);}public int getPageCount(){Dispatch selection = Dispatch.get(word, "Selection").toDispatch();return Dispatch.call(selection,"information", new Variant(4)).getInt(); }/*** 获取当前的选定的内容或者插⼊点* @return当前的选定的内容或者插⼊点*/public Dispatch getSelection(){if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();return selection;}/*** 从选定内容或插⼊点开始查找⽂本* @param findText 要查找的⽂本* @return boolean true-查找到并选中该⽂本,false-未查找到⽂本*/public boolean find(String findText){if(findText == null || findText.equals("")){return false;}// 从selection所在位置开始查询Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();// 设置要查找的内容Dispatch.put(find, "Text", findText);// 向前查找Dispatch.put(find, "Forward", "True");// 设置格式Dispatch.put(find, "Format", "True");// ⼤⼩写匹配Dispatch.put(find, "MatchCase", "True");// 全字匹配Dispatch.put(find, "MatchWholeWord", "True");// 查找并选中return Dispatch.call(find, "Execute").getBoolean();}/*** 查找并替换⽂字* @param findText* @param newText* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceText(String findText, String newText){moveStart();if (!find(findText))return false;Dispatch.put(getSelection(), "Text", newText);return true;}/*** 进⼊页眉视图*/public void headerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "9");}/*** 进⼊页脚视图*/public void footerView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", "10");}/*** 进⼊普通视图*/public void pageView(){//取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(view, "SeekView", new Variant(0));//普通视图}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText){int count = getPageCount();for(int i = 0; i < count; i++){headerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveEnd();}footerView();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}pageView();moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}nextPage();}}/*** 全局替换⽂本* @param findText* @param newText*/public void replaceAllText(String findText, String newText, String fontName, int size){ /****插⼊页眉页脚*****///取得活动窗体对象Dispatch ActiveWindow = word.getProperty( "ActiveWindow").toDispatch();//取得活动窗格对象Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();//取得视窗对象Dispatch view = Dispatch.get(ActivePane, "View").toDispatch();/****设置页眉*****/Dispatch.put(view, "SeekView", "9");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}/****设置页脚*****/Dispatch.put(view, "SeekView", "10");while (find(findText)){Dispatch.put(getSelection(), "Text", newText);moveStart();}Dispatch.put(view, "SeekView", new Variant(0));//恢复视图moveStart();while (find(findText)){Dispatch.put(getSelection(), "Text", newText);putFontSize(getSelection(), fontName, size);moveStart();}}/*** 设置选中或当前插⼊点的字体* @param selection* @param fontName* @param size*/public void putFontSize(Dispatch selection, String fontName, int size){Dispatch font = Dispatch.get(selection, "Font").toDispatch();Dispatch.put(font, "Name", new Variant(fontName));Dispatch.put(font, "Size", new Variant(size));}/*** 在当前插⼊点插⼊字符串*/public void insertText(String text){Dispatch.put(getSelection(), "Text", text);}/*** 将指定的⽂本替换成图⽚* @param findText* @param imagePath* @return boolean true-查找到并替换该⽂本,false-未查找到⽂本*/public boolean replaceImage(String findText, String imagePath, int width, int height){moveStart();if (!find(findText))return false;Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();return true;}/*** 全局将指定的⽂本替换成图⽚* @param findText* @param imagePath*/public void replaceAllImage(String findText, String imagePath, int width, int height){moveStart();while (find(findText)){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveStart();}}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath, int width, int height){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch(); Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveRight();}/*** 在当前插⼊点中插⼊图⽚* @param imagePath*/public void insertImage(String imagePath){Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 获取书签的位置* @param bookmarkName* @return书签的位置*/public Dispatch getBookmark(String bookmarkName){try{Dispatch bookmark = Dispatch.call(this.doc, "Bookmarks", bookmarkName).toDispatch();return Dispatch.get(bookmark, "Range").toDispatch();}catch(Exception e){e.printStackTrace();}return null;}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath*/public void insertImageAtBookmark(String bookmarkName, String imagePath){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath);}/*** 在指定的书签位置插⼊图⽚* @param bookmarkName* @param imagePath* @param width* @param height*/public void insertImageAtBookmark(String bookmarkName, String imagePath, int width, int height){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null){Dispatch picture = Dispatch.call(Dispatch.get(dispatch, "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));}}/*** 在指定的书签位置插⼊⽂本* @param bookmarkName* @param text*/public void insertAtBookmark(String bookmarkName, String text){Dispatch dispatch = getBookmark(bookmarkName);if(dispatch != null)Dispatch.put(dispatch, "Text", text);}/*** ⽂档另存为* @param savePath*/public void saveAs(String savePath){Dispatch.call(doc, "SaveAs", savePath);}/*** ⽂档另存为PDF* <b><p>注意:此操作要求word是2007版本或以上版本且装有加载项:Microsoft Save as PDF 或 XPS</p></b>* @param savePath*/public void saveAsPdf(String savePath){Dispatch.call(doc, "SaveAs", new Variant(17));}/*** 保存⽂档* @param savePath*/public void save(String savePath){Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);}/*** 关闭word⽂档*/public void closeDocument(){if (doc != null) {Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}public void exit(){word.invoke("Quit", new Variant[0]);}}具体WordUtils类的使⽤暂时没有看到更多的例⼦,上⾯的util的使⽤是⾃⼰摸索出来的,可能不是最优,最恰当的.//==================================================================================================使⽤Java⼯具POI操作MicroSoft Office套件Word,Excle和PPT使⽤Maven⼯程的话需要在Pom.xml⽂件中引⼊的jar包.⼀开始是想使⽤POI⼯具操作,但是从⽹上找来的代码始终报编译错误,代码中的⼀些类找不到,但是也明明已经引⼊了poi-3.x.jar包⽂件,更换了好⼏个poi版本的jar包仍是⼀样的效果.随后调查,到底需要哪些jar包.....结果如下:<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>2.3.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.8</version></dependency>所依赖的全部jar包的截图如果只引⼊⼀个poi-3.x.jar包是会报错的. POI具体操作Word,Excel,和PPT的代码,⾃⾏百度.只要jar包引⼊的正确,运⾏编译代码就没有问题.。

JAVA不使用POI,用PageOffice动态导出Word文档

JAVA不使用POI,用PageOffice动态导出Word文档

JAVA不使用POI,用PageOffice动态导出Word文档很多情况下,软件开发者需要从数据库读取数据,然后将数据动态填充到手工预先准备好的Word模板文档里,这对于大批量生成拥有相同格式排版的正式文件非常有用,这个功能应用PageOffice的基本动态填充功能即可实现。

但若是用户想动态生成一个没有固定模版的公文时,换句话说,没有办法事先准备一个固定格式的模板时,就需要开发人员在后台用代码实现Word文档的从零到图文并茂的动态生成功能了。

这里的“零”指的是Word空白文档。

那如何实现Word文档的从无到有呢,下面我就把自己实现这一功能的过程介绍一下。

例如,我想打开一个Word文档,里面的内容为:标题(粗体、黑体、字体大小为20、居中显示)、第一段内容(内容(略)、字体倾斜、字体大小为10、中文“楷体”、英文“Times New Roman”、红色、最小行间距、左对齐、首行缩进)、第二段内容(内容(略)、字体大小为12、黑体、1.5倍行间距、左对齐、首行缩进、插入图片)、第三段内容(内容(略)、字体大小为14、华文彩云、2倍行间距、左对齐、首行缩进)第一步:请先安装PageOffice的服务器端的安装程序,之后在WEB项目下的“WebRoot/WEB-INF/lib”路径中添加pageoffice.cab和pageoffice.jar(在网站的“下载中心”中可下载相应的压缩包,解压之后直接将pageoffice.cab和pageoffice.jar文件拷贝到该目录下就可以了)文件。

第二步:修改WEB项目的配置文件,将如下代码添加到配置文件中:<!-- PageOffice Begin --><servlet><servlet-name>poserver</servlet-name><servlet-class>com.zhuozhengsoft .pageoffice.poserver.Server</servlet-class></servlet><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/poserver.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/pageoffice.cab</url-pattern></servlet-mapping><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/popdf.cab</url-pattern></servlet-mapping><servlet-mapping><servlet-name>poserver</servlet-name><url-pattern>/sealsetup.exe</url-pattern></servlet-mapping><servlet><servlet-name>adminseal</servlet-name><servlet-class>com.zhuozhengsoft.pageoffice.poserver.AdminSeal </servlet-class></servlet><servlet-mapping><servlet-name>adminseal</servlet-name><url-pattern>/adminseal.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>adminseal</servlet-name><url-pattern>/loginseal.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>adminseal</servlet-name><url-pattern>/sealimage.do</url-pattern></servlet-mapping><mime-mapping><extension>mht</extension><mime-type>message/rfc822</mime-type></mime-mapping><context-param><param-name>adminseal-password</param-name><param-value>123456</param-value></context-param><!-- PageOffice End -->第三步:在WEB项目的WebRoot目录下添加文件夹存放word模板文件,在此命名为“doc”,将要打开的空白Word文件拷贝到该文件夹下,我要打开的Word文件为“test.doc”。

Java实现word文档在线预览,读取office(word,excel,ppt)文件

Java实现word文档在线预览,读取office(word,excel,ppt)文件

Java实现word⽂档在线预览,读取office(word,excel,ppt)⽂件想要实现word或者其他office⽂件的在线预览,⼤部分都是⽤的两种⽅式,⼀种是使⽤openoffice转换之后再通过其他插件预览,还有⼀种⽅式就是通过POI读取内容然后预览。

⼀、使⽤openoffice⽅式实现word预览主要思路是:1.通过第三⽅⼯具openoffice,将word、excel、ppt、txt等⽂件转换为pdf⽂件2.通过swfTools将pdf⽂件转换成swf格式的⽂件3.通过FlexPaper⽂档组件在页⾯上进⾏展⽰我使⽤的⼯具版本:openof:3.4.1swfTools:1007FlexPaper:这个关系不⼤,我随便下的⼀个。

推荐使⽤1.5.1JODConverter:需要jar包,如果是maven管理直接引⽤就可以操作步骤:1.office准备下载openoffice:从过往⽂件,其他语⾔中找到中⽂版3.4.1的版本下载后,解压缩,安装然后找到安装⽬录下的program ⽂件夹在⽬录下运⾏soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard如果运⾏失败,可能会有提⽰,那就加上 .\ 在运⾏试⼀下这样openoffice的服务就开启了。

2.将flexpaper⽂件中的js⽂件夹(包含了flexpaper_flash_debug.js,flexpaper_flash.js,jquery.js,这三个js⽂件主要是预览swf⽂件的插件)拷贝⾄⽹站根⽬录;将FlexPaperViewer.swf拷贝⾄⽹站根⽬录下(该⽂件主要是⽤在⽹页中播放swf⽂件的播放器)项⽬结构:页⾯代码:fileUpload.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>⽂档在线预览系统</title><style>body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;}a {color:#CE4614;}#msg-box {color: #CE4614; font-size:0.9em;text-align:center;}#msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;}#msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;}#msg-box .nav {margin-top:20px;}</style></head><body><div id="msg-box"><form name="form1" method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp"><div class="title">请上传要处理的⽂件,过程可能需要⼏分钟,请稍候⽚刻。

java html内容生成word文件实现代码

java html内容生成word文件实现代码

java html内容生成word文件实现代码处理HTML标签我用的是Jsoup组件,生成word文档这方面我用的是Jacob组件。

有兴趣的朋友可以去Google搜索一下这两个组件。

大致思路如下:先利用jsoup将得到的html代码“标准化”(Jsoup.parse(String html))方法,然后利用FileWiter将此html内容写到本地的template.doc文件中,此时如果文章中包含图片的话,template.doc就会依赖你的本地图片文件路径,如果你将图片更改一个名称或者将路径更改,再打开这个template.doc,图片就会显示不出来(出现一个叉叉)。

为了解决此问题,利用jsoup组件循环遍历html文档的内容,将img元素替换成${image_自增值}的标识,取出img元素中的src属性,再以键值对的方式存储起来,例如:此时你的html内容会变成如下格式:(举个示例)保存到本地文件以后,利用MSOfficeGeneratorUtils类(工具类详见下面,基于开源组件Jacob)打开你保存的这个template.doc,调用replaceText2Image,将上面代码的图片标识替换为图片,这样就消除了本地图片路径的问题。

然后再调用copy方法,复制整篇文档,关闭template.doc文件,新建一个doc文件(createDocument),调用paste方法粘贴你刚复制的template.doc里的内容,保存。

基本上就ok了。

关于copy整个word文档的内容,也会出现一个隐式问题。

就是当复制的内容太多时,关闭word程序的时候,会谈出一个对话框,问你是否将复制的数据应用于其它的程序。

对于这个问题解决方法很简单,你可以在调用quit(退出word程序方法)之前,新建一篇文档,输入一行字,然后调用copy方法,对于复制的数据比较少时,关闭word程序时,它不会提示你的。

见如下代码//复制一个内容比较少的*.doc文档,防止在关闭word程序时提示有大量的copy内容在内存中,是否应用于其它程序对话框,msOfficeUtils.close();msOfficeUtils.quit();Jacob在sourceforge上的链接Jsoup官网MsOfficeGeneratorUtilspackage com.to ps tar.test;import java.io.File;import java.io.IOException;import java.util.List;import com.jacob.activeX.ActiveXComponent;import Thread;import .Dispatch;import .Variant;/*** 利用JACOB对Microsoft Office Word 进行相关操作** @author xiaowu* @category topstar* @version 1.0* @since 2011-12-5*/public class MSOfficeGeneratorUtils {/*** Microsoft Office Word 程序对象*/private ActiveXComponent word = null;/*** Word 活动文档对象*/private Dispatch document = null;/*** 所有 Word 文档对象*/private Dispatch documents = null;/*** select ion 代表当前活动文档窗口中的所选内容。

JAVA读取WORD_pdf等

JAVA读取WORD_pdf等

JAVA读取WORD,EXCEL,POWERPOINT,PDF文件的方式OFFICE文档使用POI控件,PDF可以使用PDFBOX0.7.3控件,完全支持中文,用XPDF也行.java2word 是一个在java程序中调用MS Office Word 文档的组件(类库)。

该组件提供了一组简单的接口,以便java 档。

这些服务包括:打开文档、新建文档、查找文字、替换文字,插入文字、插入图片、插入表格,在书签处插入文字、插入图片、插入表格等。

填充数据到表格中读取表格数据更多激动人心的功能见详细说明:用jacob.其实jacob是一个bridage,连接java和com或者win32函数的一个中间件,jacob并不能直接抽取word,excel等文有为你写好的了,就是jacob的作者一并提供了。

jacob下载:下载了jacob并放到指定的路径之后(dll放到path,jar文件放到classpath),就可以写你自己的抽取程序了,下面是一个import java.io.File;import .*;import com.jacob.activeX.*;public class FileExtracter{public static void main(String[] args) {ActiveXComponent app = new ActiveXComponent("Word.Application");String inFile = "c:\\test.doc";String tpFile = "c:\\temp.htm";String otFile = "c:\\temp.xml";boolean flag = false;try {app.setProperty("Visible", new Variant(false));Object docs = app.getProperty("Documents").toDispatch();Object doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{inFile,new Variant(false), new int[1]).toDispatch();Dispatch.invoke(doc,"SaveAs", Dispatch.Method, new Object[]{tpFile,new Variant(8)}, new int[1]); Variant f = new Variant(false);Dispatch.call(doc, "Close", f);flag = true;} catch (Exception e) {e.printStackTrace();} finally {app.invoke("Quit", new Variant[] {});}}}2。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.为你的项目导入freeMarker包我的项目是依靠maven来维护依赖的,所以引入很方便,只需要在pom文件中加入下面这个依赖就好[html]view plain copy1.<dependency>2.<groupId>org.freemarker</groupId>3.<artifactId>freemarker</artifactId>4.<version>2.3.23</version>5.</dependency>如果还是比较传统的话,就像那个链接里的项目一样,把jar包导入项目吧2.依据模板动态生成word文档,首先你得有个模板模板是doc类型就好,注意不是docx,docx没有尝试,doc类型已经满足了我的需求,朋友们如果尝试成功了可以告诉我一下test.doc,注意“产品品质证明书”是一张图片哦,图片会漂亮的留在生成的新文档中。

将变量替换成${xxx}即可,这里只选了两个变量3.点击文件->另存为将test.doc保存为xml类型,即Word XML文档.xml类型,得到test.xml4.用notepad或者sublime打开test.xml,你会发现${xxx}会被分割成${*********xxx********)的样子,将*******删除,保证它又成了完整的变量标签,像这样5.将文件已utf-8编码保存,另存为为.ftl,找不到该格式直接改文件后缀名就行,这样得到test.ftl6.前台触发事件我的项目是基于SpringMVC的,所以前台触发只需要在view层的文件里加个按钮事件即可,直接上代码[javascript]view plain copy1.function generateMillCertificate(id) {//点击下载按钮触发的事件2. window.location.href = '../deliveryOrder/exportMillCertificate?id='+ id;3. }7.后台生成文件,并返回给客户的浏览器这里又分为两步a.controller层接收请求,根据参数拼凑数据,放在map中[java]view plain copy1./***2. * 导出Word材质单3. *4. * @return5. * @throws Exception6. */7.@RequestMapping(value = "exportMillCertificate", method = RequestMethod.GET)8.@ResponseBody9.public void exportMillCertificate(HttpServletRequest request,10. HttpServletResponse response) throws Exception {11.//获得数据,系统相关,就不展示了12. Map<String, Object> map = new HashMap<String, Object>();13. map.put("customerShortName",deliveryOrder.getRepositoryName());14. map.put("productName",deliveryOrderDetail.getProductName());15. WordUtils.exportMillCertificateWord(request,response,map);16. }b.工具类WordUtils利用传来的map和将要返回给用户的HTTPServletReponse,将map里的数据和模板中${xxx}标签对应的变量值填入,生成新的文档,通过response返回给浏览器并提供用户下载[java]view plain copy1.public class WordUtils {2.//配置信息,代码本身写的还是很可读的,就不过多注解了3.private static Configuration configuration = null;4.//这里注意的是利用WordUtils的类加载器动态获得模板文件的位置5.private static final String templateFolder = WordUtils.class.getClassLoader().getResource("../../").getPath() + "asserts/templete/";6.static {7. configuration = new Configuration();8. configuration.setDefaultEncoding("utf-8");9.try {10. configuration.setDirectoryForTemplateLoading(new File(templateFolder));11. } catch (IOException e) {12. e.printStackTrace();13. }14. }15.16.private WordUtils() {17.throw new AssertionError();18. }19.20.public static void exportMillCertificateWord(HttpServletRequest request,HttpServletResponse response, Map map) throws IOException {21. Template freemarkerTemplate = configuration.getTemplate("test.ftl");22. File file = null;23. InputStream fin = null;24. ServletOutputStream out = null;25.try {26.// 调用工具类的createDoc方法生成Word文档27. file = createDoc(map,freemarkerTemplate);28. fin = new FileInputStream(file);29.30. response.setCharacterEncoding("utf-8");31. response.setContentType("application/msword");32.// 设置浏览器以下载的方式处理该文件名33. String fileName = "材质单"+DateUtils.curDateTimeStr14() + ".doc";34. response.setHeader("Content-Disposition", "attachment;filename="35. .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));36.37. out = response.getOutputStream();38.byte[] buffer = new byte[512]; // 缓冲区39.int bytesToRead = -1;40.// 通过循环将读入的Word文件的内容输出到浏览器中41.while((bytesToRead = fin.read(buffer)) != -1) {42. out.write(buffer, 0, bytesToRead);43. }44. } finally {45.if(fin != null) fin.close();46.if(out != null) out.close();47.if(file != null) file.delete(); // 删除临时文件48. }49. }50.51.private static File createDoc(Map<?, ?> dataMap, Template template) {52. String name = "test.doc";53. File f = new File(name);54. Template t = template;55.try {56.// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开57. Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");58. t.process(dataMap, w);59. w.close();60. } catch (Exception ex) {61. ex.printStackTrace();62.throw new RuntimeException(ex);63. }64.return f;65. }66.}。

相关文档
最新文档