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。

java 根据word模板生成word文件

java 根据word模板生成word文件

java 根据word模板生成word文件Java可以使用Apache POI库来生成Word文件,并且也可以使用freemarker等模板引擎来实现根据Word模板生成Word 文件的功能。

下面是一个简单的示例代码,可以帮助您快速入门。

模板制作:offer,wps都行,我使用wps进行操作第一步制作模板CTRL+f9生成域------》鼠标右键编辑域------》选择邮件合并-----》在域代码后面加上英文${跟代码内的一致}。

这样模板就创建好了。

首先需要引入POI和freemarker的依赖:<!-- Apache POI --><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.core</artifactId><version>2.0.2</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.document< /artifactId><version>2.0.2</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.template< /artifactId><version>2.0.2</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.document.docx</artifactId><version>2.0.2</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId><version>2.0.2</version></dependency>接下来是一个简单的示例代码:public class WordGenerator {public static void main(String[] args) throws IOException, TemplateException {// 读取Word模板try {= null;//wordInputStream in = new (new File("模板文件.docx"));//注册xdocreport实例并加载FreeMarker模板引擎IXDocReport r = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Freemarker);// 生成Word文件//创建xdocreport上下文对象IContext context =r.createContext();//将需要替换的数据数据添加到上下文中//其中key为word模板中的域名,value是需要替换的值User user = new User("zhangsan", 18, "福建泉州");context.put("uesrname",user.getUsername());context.put("age", user.getAge()); context.put("address",user.getAddress());out = new (newFile("D://xxx.docx"));//处理word文档并输出r.process(context, out);} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}}在这个示例代码中,我们读取了名为模板文件.docx的Word 模板,然后准备了一些数据,利用Freemarker模板引擎将数据填充到模板中,最后生成了一个名为xxx.docx的Word文件。

基于java合并.doc和docx格式的Word文件

基于java合并.doc和docx格式的Word文件

基于java合并.doc和docx格式的Word⽂件注:摘录⾃之前⽤过jacob 合并.doc,但是是有jacob有弊端:服务器必须是Windows操作系统 —— ⽬前之所以web项⽬多⽤Java开发,就是因为服务器可以是Linux、Unix等⾮Windows的系统来降低项⽬的成本。

服务器上必须安装Office —— Jacob的意思就是: Java COM Bridge,java中调⽤office提供的com接⼝来实现对Office⽂件的操作。

并发问题 —— 如果多⽤户同时在线⽣成word⽂件就必须处理此并发问题,稍有不慎,就会在服务器端产⽣Office的死进程,死锁服务器的内存资源。

我遇到的问题是下载并合并附件,这⾥的附件⼤多是doc⽂件,也包含少量的docx⽂件,但是⽂件路径是从数据库中读取出来的,均不带后缀名,传统的xwpfdocument和hwpfdocument不能完全解决我的问题;尤其是将⽂件合并,不能轻易办到,需要对⽂档进⾏解析。

这⾥我采⽤的⽅法是将Word⽂件转换为HTML⽂件,把Word的合并转化为HTML的合并;这样⼀来就减少了难度,不过就是还需要再把HTML⽂件转化为doc⽂件或者docx⽂件(此时,你就可以指定是哪种⽂件了)。

在转换的时候,分两个⽅向,⼀个是doc⽂件转换,另⼀个是docx⽂件转换;这⾥的转换时必须包含⽂档中的格式的(图⽚和表格我这⾥没有进⾏测试)。

如果是没有⽂件后缀,那么就需要先判断是doc⽂件还是docx⽂件,这⾥⽤到了⼀个⼯具类,就是通过⽂件的⽂件头来判断⽂件类型,因为我这⾥只是为了区别doc和docx,所以就⽐较了前四位的16进制数,按照if和else来⾛两条转换路线。

(具体⽂件的⽂件头可上⽹查资料,各种⽂件都有)。

转换doc⽂件的时候,是按照字符读取的,判断每个字符的字体颜⾊和样式,将其转换为HTML的代码,最后应该是整个稳当的HTML的字符串的累加,因为我这⾥是合并,所以我使⽤for循环进⾏了⽂件主体的叠加,最后在循环的外⾯加上HTML的头部和尾部信息即可。

Java如何实现读取txt文件内容并生成Word文档

Java如何实现读取txt文件内容并生成Word文档

Java如何实现读取txt⽂件内容并⽣成Word⽂档⽬录导⼊Jar包1. Maven仓库下载导⼊2. ⼿动导⼊读取txt⽣成Word注意事项本⽂将以Java程序代码为例介绍如何读取txt⽂件中的内容,⽣成Word⽂档。

在编辑代码前,可参考如下代码环境进⾏配置:IntelliJ IDEAFree Spire.Doc for JavaTxt⽂档导⼊Jar包两种⽅法可在Java程序中导⼊jar⽂件1. Maven仓库下载导⼊在pom.xml中配置如下:<repositories><repository><id>com.e-iceblue</id><url>https:///repository/maven-public/</url></repository></repositories><dependencies><dependency><groupId>e-iceblue</groupId><artifactId>spire.doc.free</artifactId><version>3.9.0</version></dependency></dependencies>2. ⼿动导⼊需先下载jar包到本地,解压,找到lib路径下的jar⽂件。

然后在Java程序中打开“Project Structure”窗⼝,然后执⾏如下步骤导⼊:找到本地路径下的jar⽂件,添加到列表,然后导⼊:读取txt⽣成Word代码⼤致步骤如下:1. 实例化Document类的对象。

然后通过Document.addSection()⽅法和Section.addParagraph()⽅法添加节和段落。

2. 读取txt⽂件:创建InputStreamReader类的对象,构造⽅法中传递输⼊流和指定的编码表名称。

idea javadoc文档的生成方法

idea javadoc文档的生成方法

idea javadoc文档的生成方法【实用版3篇】目录(篇1)1.介绍 JavaDoc 文档2.JavaDoc 文档的生成方法3.使用 IDEA 自动生成 JavaDoc 文档4.手动编写 JavaDoc 文档5.结论正文(篇1)一、介绍 JavaDoc 文档JavaDoc 是 Java 开发中的一种文档编写标准,它可以描述 Java 类、方法、成员变量等的详细信息。

JavaDoc 文档通常以 HTML 格式生成,并且可以被 IDEA 等 Java 开发工具自动生成。

二、JavaDoc 文档的生成方法JavaDoc 文档的生成方法主要有两种:使用 IDEA 自动生成和手动编写。

1.使用 IDEA 自动生成 JavaDoc 文档IDEA 是一款强大的 Java 开发工具,它可以自动生成 JavaDoc 文档。

具体操作步骤如下:(1)打开 IDEA,导入 Java 项目。

(2)在项目中选择需要生成 JavaDoc 的类或方法,右键点击,选择“生成 JavaDoc”。

(3)IDEA 会自动生成 JavaDoc 文档,并将其保存在项目指定的输出目录中。

2.手动编写 JavaDoc 文档手动编写 JavaDoc 文档需要遵循一定的规范,例如使用特定的注释标签、指定文档生成工具等。

下面是一个简单的手动编写 JavaDoc 文档的示例:```java/*** 这是一个简单的 JavaDoc 注释* @author YourName* @version 1.0* @since JDK 1.8*/public class MyClass {// 类的成员变量和方法}```三、结论JavaDoc 文档是 Java 开发中重要的文档之一,它可以帮助开发者更好地理解和使用 Java 类、方法等。

使用 IDEA 可以方便地生成 JavaDoc 文档,而手动编写 JavaDoc 文档则需要遵循一定的规范。

目录(篇2)1.介绍 Javadoc2.Javadoc 的生成方法3.Javadoc 生成文档的步骤4.常见问题与解决方法5.总结正文(篇2)一、介绍 JavadocJavadoc 是 Java 开发中的一种文档生成工具,它可以从 Java 源代码中提取类、方法、成员变量等信息,并生成 HTML 格式的文档。

Java将数据写入word文档(.doc)

Java将数据写入word文档(.doc)

Java将数据写⼊word⽂档(.doc)Java可⽤org.apache.poi包来操作word⽂档。

org.apache.poi包可于上下载,解压后各jar作⽤如下图所⽰:可根据需求导⼊对应的jar。

⼀、HWPFDocument类的使⽤⽤HWPFDocument类将数据写到指定的word⽂档中,基本思路是这样的:- ⾸先,建⽴⼀个HWPFDocument类的实例,关联到⼀个临时的word⽂档;- 然后,通过Range类实例,将数据写⼊这个word⽂档中;- 接着,将这个临时的word⽂档通过write函数写⼊指定的word⽂档中。

- 最后,关闭所有资源。

下⾯详细说明各个步骤。

1.构造函数这⾥要说明⼀下,经过试验,暂时还没找到直接在程序中新建⼀个word⽂档并读取的⽅法,只能先创建好temp.doc,然后在程序中读取。

(⽤File-createNewFile和POIFSFileSystem.create创建出来的.doc⽂件,都不能被正确读取)另外,其实选择哪种参数传⼊都是⼀样的,毕竟HWPFDocument关联的word⽂档是⽆法写⼊的,只是当作⼀个临时⽂件。

所以,选择最为熟悉的InputStream较为合适。

参数1:InputStream。

可将word⽂档⽤FileInputStream流读取,然后传⼊HWPFDocument类。

主要⽤于读取word⽂档中的数据。

参数2:POIFSFileSystem。

POIFSFileSystem的构造函数参数可以是(File,boolean)【这样的话file必须是已经存在的】,后者为false时可读写。

这⾥可以写为HWPFDocument doc = new HWPFDocument(new POIFSFileSystem(new File("temp.doc"),false));2.Range类(1)获取Range类实例。

HWPFDocument类中有⼀系列获取Range类实例以操作word⽂档的⽅法。

Java使用word文档模板下载文件(内容为表格)

Java使用word文档模板下载文件(内容为表格)

Java使⽤word⽂档模板下载⽂件(内容为表格)注意:1、此Demo操作的是word的表格2、本次使⽤的word后缀为docx1、pom引⽤jar<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>2、代码import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.util.Units;import ermodel.*;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.core.io.ClassPathResource;import java.io.*;import java.util.HashMap;import java.util.List;import java.util.Map;/*** word模板赋值下载** @author a*/@SpringBootApplicationpublic class ReadResourceApplication {/*** 主⽅法** @param args*/public static void main(String[] args) {SpringApplication.run(ReadResourceApplication.class, args);Map map = new HashMap(3);map.put("${name}", "测试");map.put("${sexName}", "男");map.put("${mzName}", "汉");getBuild("wordXML/领导⼲部基本情况信息表.docx", map, "D:/aaa.doc");}/*** 赋值并下载⽂件** @param tmpFile* @param contentMap* @param exportFile*/public static void getBuild(String tmpFile, Map<String, String> contentMap, String exportFile) {InputStream inputStream = null;try {// 加载Word⽂件inputStream = new ClassPathResource(tmpFile).getInputStream();} catch (IOException e) {e.printStackTrace();}XWPFDocument document = null;try {// 加载流到documentdocument = new XWPFDocument(inputStream);} catch (IOException e) {e.printStackTrace();}// 获取⽂档中的表格List<XWPFTable> tables = document.getTables();for (int j = 0; j < tables.size(); j++) {XWPFTable table = tables.get(j);// 获取表格⾏List<XWPFTableRow> rows = table.getRows();for (int i = 0; i < rows.size(); i++) {// 得到每⼀⾏XWPFTableRow newRow = table.getRow(i);// 得到所有的单元格List<XWPFTableCell> cells = newRow.getTableCells();for (int k = 0; k < cells.size(); k++) {// 得到每⼀列XWPFTableCell cell = cells.get(k);// 以下为更新替换值逻辑List<XWPFParagraph> paragraphs = cell.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {List<XWPFRun> runs = paragraph.getRuns();String cellText = cell.getText();if (contentMap.keySet().contains(cellText)) {for (int m = 0; m < runs.size(); m++) {if (m == runs.size() - 1) {runs.get(m).setText(contentMap.get(cellText), 0);} else {runs.get(m).setText("", 0);}}} else if (cellText.equals("${picture}")) {for (int m = 0; m < runs.size(); m++) {if (m == runs.size() - 1) {try {runs.get(m).setText("", 0);runs.get(m).addPicture(new ClassPathResource("wordXML/培训⼆维码.png").getInputStream(), XWPFDocument.PICTURE_TYPE_PNG, "培训⼆维码.png,", Units.toEMU(200), Units.toEMU(200)); } catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} else {runs.get(m).setText("", 0);}}}}}}}//导出⽂件到磁盘try {ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();document.write(byteArrayOutputStream);OutputStream outputStream = new FileOutputStream(exportFile);outputStream.write(byteArrayOutputStream.toByteArray());outputStream.close();} catch (IOException e) {e.printStackTrace();}}}需要更改的地⽅:1、word⽂档路径2、图⽚路径(不需要图⽚的可直接删除相关代码)。

java导出word的6种方式(复制来的文章)

java导出word的6种方式(复制来的文章)

java导出word的6种⽅式(复制来的⽂章)来⾃:最近做的项⽬,需要将⼀些信息导出到word中。

在⽹上找了好多解决⽅案,现在将这⼏天的总结分享⼀下。

⽬前来看,java导出word⼤致有6种解决⽅案:1:Jacob是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建⼀座桥梁。

使⽤Jacob⾃带的DLL动态链接库,并通过JNI的⽅式实现了在Java平台上对COM程序的调⽤。

DLL动态链接库的⽣成需要windows平台的⽀持。

该⽅案只能在windows平台实现,是其局限性。

2:Apache POI包括⼀系列的API,它们可以操作基于MicroSoft OLE 2 Compound Document Format的各种格式⽂件,可以通过这些API在Java中读写Excel、Word等⽂件。

他的excel处理很强⼤,对于word还局限于读取,⽬前只能实现⼀些简单⽂件的操作,不能设置样式。

3:Java2word是⼀个在java程序中调⽤ MS Office Word ⽂档的组件(类库)。

该组件提供了⼀组简单的接⼝,以便java程序调⽤他的服务操作Word ⽂档。

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

填充数据到表格中读取表格数据,1.1版增强的功能:指定⽂本样式,指定表格样式。

如此,则可动态排版word⽂档。

是⼀种不错的解决⽅案。

4:iText是著名的开放源码的站点sourceforge⼀个项⽬,是⽤于⽣成PDF⽂档的⼀个java类库。

通过iText不仅可以⽣成PDF或rtf的⽂档,⽽且可以将XML、Html⽂件转化为PDF⽂件。

功能强⼤。

5:JSP输出样式,该⽅案实现简单,但是处理样式有点缺陷,简单的导出可以使⽤。

6:⽤XML做就很简单了。

Word从2003开始⽀持XML格式,⼤致的思路是先⽤office2003或者2007编辑好word的样式,然后另存为xml,将xml翻译为FreeMarker模板,最后⽤java来解析FreeMarker模板并输出Doc。

JAVA操作WORD

JAVA操作WORD

JAVA操作WORDJava操作Word主要有两种方式:一种是使用Apache POI库进行操作,另一种是使用XML模板进行操作。

下面将详细介绍如何通过XML模板实现Java操作Word。

1.准备工作:2. 创建Word模板:首先,创建一个空的Word文档,将其保存为XML格式,作为Word的模板。

可以在Word中添加一些标记或占位符,用于后续替换。

3.导入POI和相关依赖:在Java项目中,导入以下依赖:```xml<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>3.1.0</version></dependency>```4.读取模板文件:使用POI库读取Word模板文件,将其转换为XML格式的字符串,并保存为`template.xml`文件中。

```javaimport ermodel.XWPFDocument;import java.io.FileOutputStream;public class WordTemplateReaderpublic static void main(String[] args) throws ExceptionXWPFDocument document = new XWPFDocument(new FileInputStream("template.docx"));FileOutputStream out = new FileOutputStream("template.xml");document.write(out);out.close(;document.close(;}}```5.数据替换:读取template.xml文件,使用Java中的字符串替换功能,将模板中的占位符替换为实际的数据。

java实现文件下载.

java实现文件下载.

在BlogJava上已经有一位作者阐述了文件上传的问题, 地址是在Struts 2中实现文件上传 , 因此我就不再讨论那个话题了。

我今天简单介绍一下Struts 2的文件下载问题。

我们的项目名为 struts2hello ,所使用的开发环境是MyEclipse 6,当然其实用哪个 IDE 都 是一样的,只要把类库放进去就行了,文件下载不需要再加入任何额外的包。

读者可以参考 文档:http://beansoft.java­/myeclipse_doc_cn/struts2_demo.pdf ,来了解怎么下载 和配置基本的 Struts 2开发环境。

为了便于大家对比,我把完整的 struts.xml 的配置信息列出来:Xml代码1 <?xml version="1.0" encoding="UTF-8" ?>2 <!DOCTYPE struts PUBLIC3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"4 "/dtds/struts-2.0.dtd">56 <struts>7 <package name="default" extends="struts-default" >8 <!-- 在这里添加 Action 定义 -->910 <!-- 简单文件下载 -->11 <action name="download" class="example.FileDownloadAction">12 <result name="success" type="stream">13 <param name="contentType">text/plain</param>14 <param name="inputName">inputStream</param>15 <paramname="contentDisposition">attachment;filename="struts2中文.txt"</param>16 <param name="bufferSize">4096</param>17 </result>18 </action>1920 <!-- 文件下载,支持中文附件名 -->21 <action name="download2" class="example.FileDownloadAction2">22 <!-- 初始文件名 -->23 <param name="fileName">Struts 中文附件.txt</param>24 <result name="success" type="stream">25 <param name="contentType">text/plain</param>26 <param name="inputName">inputStream</param>27 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName属性28 对应 action类中的方法 getDownloadFileName() -->29 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>30 <param name="bufferSize">4096</param>31 </result>32 </action>3334 <!-- 下载现有文件 -->35 <action name="download3" class="example.FileDownloadAction3">36 <param name="inputPath">/download/系统说明.doc</param>37 <!-- 初始文件名 -->38 <param name="fileName">系统说明.doc</param>39 <result name="success" type="stream">40 <paramname="contentType">application/octet-stream;charset=ISO8859-1</param>41 <param name="inputName">inputStream</param>42 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName属性43 对应 action类中的方法 getDownloadFileName() -->44 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>45 <param name="bufferSize">4096</param>46 </result>47 </action>4849 </package>5051 </struts>Xml代码52 <?xml version="1.0" encoding="UTF-8" ?>53 <!DOCTYPE struts PUBLIC54 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"55 "/dtds/struts-2.0.dtd">5657 <struts>58 <package name="default" extends="struts-default" >59 <!-- 在这里添加 Action 定义 -->6061 <!-- 简单文件下载 -->62 <action name="download" class="example.FileDownloadAction">63 <result name="success" type="stream">64 <param name="<SPAN class=hilite3><SPANstyle="BACKGROUND-COLOR:#aaffaa">contentType</SPAN></SPAN>">text/plain</param>65 <param name="inputName">inputStream</param>66 <paramname="contentDisposition">attachment;filename="<SPAN class=hilite1><SPANstyle="BACKGROUND-COLOR: #ffff00">struts2</SPAN></SPAN>中文.txt"</param>67 <param name="bufferSize">4096</param>68 </result>69 </action>7071 <!-- 文件下载,支持中文附件名 -->72 <action name="download2" class="example.FileDownloadAction2">73 <!-- 初始文件名 -->74 <param name="fileName">Struts 中文附件.txt</param>75 <result name="success" type="stream">76 <param name="<SPAN class=hilite3><SPANstyle="BACKGROUND-COLOR:#aaffaa">contentType</SPAN></SPAN>">text/plain</param>77 <param name="inputName">inputStream</param>78 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName 属性79 对应 action类中的方法 getDownloadFileName() -->80 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>81 <param name="bufferSize">4096</param>82 </result>83 </action>8485 <!-- 下载现有文件 -->86 <action name="download3" class="example.FileDownloadAction3">87 <param name="inputPath">/download/系统说明.<SPANclass=hilite5>doc</SPAN></param>88 <!-- 初始文件名 -->89 <param name="fileName">系统说明.<SPANclass=hilite5>doc</SPAN></param>90 <result name="success" type="stream">91 <param name="<SPAN class=hilite3><SPANstyle="BACKGROUND-COLOR:#aaffaa">contentType</SPAN></SPAN>">application/octet-stream;charset=ISO885 9-1</param>92 <param name="inputName">inputStream</param>93 <!-- 使用经过转码的文件名作为下载文件名, downloadFileName 属性94 对应 action类中的方法 getDownloadFileName() -->95 <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param>96 <param name="bufferSize">4096</param>97 </result>98 </action>99100 </package>101102</struts>Struts 2中对文件下载做了直接的支持,相比起自己辛辛苦苦的设置种种HTTP 头来说,现 在实现文件下载无疑要简便的多。

javaweb页面导出word

javaweb页面导出word

javaweb页⾯导出word①我做了⼀个word模板,定义好了书签为listyd,书签是在⼀个表格中,在书签位置动态的⽣成表格,例⼦代码如下:var ole = new ActiveXObject("Word.Application");var url=c:\nsqktzs_fm.doc"var doc =ole.documents.open(url,false,false);ole.V isible = true;ole.selection.find.forward =true;var rg=ole.selection.goto(true,0,0,"listyd");var tab=doc.Tables.Add(rg, 2,2) ;for(var i=1;i<=2;i++){for(var j=1;j<=2;j++){var rgcell=tab.Cell(i,j).Range;rgcell.InsertAfter(i+j);}}⽣成的表格嵌套在以前的表格中,很难看,如何能让⽣成的表格和外边的表格看上去是⼀个整体。

rgcell.InsertAfter(i+j);可以⽤insertBefore么。

也可以考虑⽤java语⾔做word模板。

③.⼩弟最近在做JSP页⾯内容导出到Word,但遇到了很多困难,望各位⼤侠急救需求:1.将JSP页⾯中的内容导出到Word⽂件中。

2.JSP页⾯中包含图⽚,图⽚的数据是从数据库中加载出来,实时⽣成的。

⼩弟在⽹上看过N个例⼦,也测试了,就是⽆法解决,问题如下:1.通过window.document.location.href='test.action'的链接⽅式,访问加⼀个JSP页⾯,⽂件头为:<%@ page contentType="application/msword;charset=gbk"%>当点击“导出”按钮时,可以⽣成Word⽂件,但是图⽚⽆法在Word中⽣成.2.直接在页⾯中加JS脚本:var oWD = new ActiveXObject("Word.Application");oWD.WindowState = 2;var oDC = oWD.Documents.Add("",0,1);var oRange =oDC.Range(0,1);var sel = document.body.createTextRange();sel.moveToElementText(PrintA);sel.select();sel.execCommand("Copy");oRange.Paste();oWD.Application.Visible = true;在我的电脑上可以导出Word(我的office版本是2007)⽂件,并且可以显⽰图⽚。

java生成word文件并下载

java生成word文件并下载

import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import .URLEncoder;import java.util.Map;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import freemarker.template.Configuration;import freemarker.template.Template;/*** @Desc:word 操作工具类*/public class WordUtil {private static Logger log = Logger.getLogger(WordUtil.class);/*** @Desc :生成word 文件* @param dataMap word 中需要展示的动态数据,用map 集合来保存* @param templateName word 模板名称,例如:test.ftl* @param filePath 文件生成的目标路径,例如:D:/wordFile/* @param fileName 生成的文件名称,例如:test.doc*/public static void createWord(Map<String, Object> dataMap,String templateName,String filePath,String fileName){try {// 创建配置实例Configuration configuration = new Configuration();// 设置编码configuration.setDefaultEncoding("UTF-8");//ftl 模板文件File file = new File(filePath); configuration.setDirectoryForTemplateLoading(file);// 获取模板Template template = configuration.getTemplate(templateName);// 输出文件File outFile = new File(filePath + File.separator + fileName);// 如果输出目标文件夹不存在,则创建if (!outFile.getParentFile().exists()){ outFile.getParentFile().mkdirs();}// 将模板和数据模型合并生成文件Writer out = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(outFile),"UTF-8"));// 生成文件template.process(dataMap, out);// 关闭流out.flush();out.close();} catch (Exception e) {log.error(" 生成word 文档(WordUtil) 出错:【msg:"+e.getMessage()+" 】,文件名:" + fileName);e.printStackTrace();}/**文件下载* @param path 文件路径全路径,包含文件名* @param response* @return*/public static HttpServletResponse downFile(String path, HttpServletResponse response) { try { // path 是指欲下载的文件的路径。

Java读取Word模板替换内容并另存

Java读取Word模板替换内容并另存

Java读取Word模板替换内容并另存⽤到的⼯具:,⽂件解压后主要有三个⽂件:jacob.jar、jacob-1.17-M2-x64.dll和jacob-1.17-M2-x86.dll。

jacob.jar引⼊到项⽬⼯程中,jacob-1.17-M2-x64.dll放在C:\Windows\System32下,如果系统是32位的则把jacob-1.17-M2-x86.dll放在C:\Windows\System32下。

注意:⽂件名要⽤.doc,万不能⽤.docx。

那样会打不开⽂件代码⽰例:/** Java2word.java** Created on 2007年8⽉13⽇, 上午10:32** To change this template, choose Tools | Template Manager* and open the template in the editor.*//** 传⼊数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表⽤来替换的值。

* word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,如:$code$、$date$……,以免执⾏错误的替换。

* 所有要替换为图⽚的字段,Key中需包含image或者Value为图⽚的全路径(⽬前只判断⽂件后缀名为:.bmp、.jpg、.gif)。

* 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:R代表从表格的第R⾏开始替换,N代表word模板中的第N张表格;Value为ArrayList对象,ArrayList中包含的对象统⼀为String[],⼀条String[]代表⼀⾏数据,ArrayList中第⼀条记录为特殊记录,记录的是表格中要替换的列号,如:要替换第⼀列、第三列、第五列的数据,则第⼀条记录为String[3] {“1”,”3”,”5”}。

  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.}。

相关文档
最新文档