文件管理 · 2022年8月21日

poiword占位符|Java POI 如何操作word 格式

A. 使用poi操作word时如何在有多个表格的word中定位到其中一个表格

关键代码如下:FileInputStream fileInputStream = new FileInputStream( soureFile);POIFSFileSystem pfs = new POIFSFileSystem( fileInputStream );HWPFDocument hwpf = new HWPFDocument(pfs);// make a HWPFDocument objectOutputStream output = new FileOutputStream( targetFile );hwpf.write(output);// write to the target fileoutput.close();(2)再word中插入表格。HWPF的情况:Table tcDataTable = range.insertTableBefore( (short)column , row);//column and row列数和行数tcDataTable.getRow(i).getCell(j).getParagraph(0).getCharacterRun(0).insertBefore("插入i行j列的内容" );XWPF的情况:String outputFile = "D:\\test.doc";XWPFDocument document = new XWPFDocument();XWPFTable tableOne = document.createTable();XWPFTableRow tableOneRowOne = tableOne.getRow(0);tableOneRowOne.getCell(0).setText("11");XWPFTableCell cell12 = tableOneRowOne.createCell();cell12.setText("12");// tableOneRowOne.addNewTableCell().setText("第1行第2列");// tableOneRowOne.addNewTableCell().setText("第1行第3列");// tableOneRowOne.addNewTableCell().setText("第1行第4列");XWPFTableRow tableOneRowTwo = tableOne.createRow();tableOneRowTwo.getCell(0).setText("21");tableOneRowTwo.getCell(1).setText("22");// tableOneRowTwo.getCell(2).setText("第2行第3列");XWPFTableRow tableOneRow3 = tableOne.createRow();tableOneRow3.addNewTableCell().setText("31");tableOneRow3.addNewTableCell().setText("32");FileOutputStream fOut;try {fOut = new FileOutputStream(outputFile);document.write(fOut); fOut.flush();// 操作结束,关闭文件fOut.close();} catch (Exception e) {e.printStackTrace();}

B. poi操作word好像只能获取版式为“嵌入型”的图片,而其它版式的图片如何获取比如:"四周型"的。

poi没用过不知道,WORD中“嵌入型”的图片是与文字等同处理的,与前后字符紧密联系,占一行,只是它把一行撑得很高,如果你把行间距设为固定且小于图片高度,则图片显示不全。其他版式均与此不同。

C. java POI 如何操作word 格式

1、环境支持 1.1 添加poi支持:包下载地址http://www.apache.org/dyn/closer.cgi/poi/release/ 1.2 POI对Excel文件的读取操作比较方便,POI还提供对Word的DOC格式文件的读取。但在它的发行版本中没有发布对Word支持的模块,需要另外下载一个POI的扩展的Jar包。下载地址为http://www.ibiblio.org/maven2/org/textmining/tm-extractors/0.4/ 下载extractors-0.4_zip这个文件package com.ray.poi.util;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import org.apache.poi.poifs.filesystem.DirectoryEntry;import org.apache.poi.poifs.filesystem.DocumentEntry;import org.apache.poi.poifs.filesystem.POIFSFileSystem;import org.textmining.text.extraction.WordExtractor;/** * 读写doc * @author wangzonghao * */public class POIWordUtil { /** * 读入doc * @param doc * @return * @throws Exception */ public static String readDoc(String doc) throws Exception { // 创建输入流读取DOC文件 FileInputStream in = new FileInputStream(new File(doc)); WordExtractor extractor = null; String text = null; // 创建WordExtractor extractor = new WordExtractor(); // 对DOC文件进行提取 text = extractor.extractText(in); return text; } /** * 写出doc * @param path * @param content * @return */ public static boolean writeDoc(String path, String content) { boolean w = false; try { // byte b[] = content.getBytes("ISO-8859-1"); byte b[] = content.getBytes(); ByteArrayInputStream s = new ByteArrayInputStream(b); POIFSFileSystem fs = new POIFSFileSystem(); DirectoryEntry directory = fs.getRoot(); DocumentEntry de = directory.createDocument("WordDocument", s); FileOutputStream ostream = new FileOutputStream(path); fs.writeFilesystem(ostream); s.close(); ostream.close(); } catch (IOException e) { e.printStackTrace(); } return w; } }测试package com.ray.poi.util;import junit.framework.TestCase;public class POIUtilTest extends TestCase { public void testReadDoc() { try{ String text = POIWordUtil.readDoc("E:/work_space/poi/com/ray/poi/util/demo.doc"); System.out.println(text); }catch(Exception e){ e.printStackTrace(); } } public void testWriteDoc() { String wr; try { wr = POIWordUtil.readDoc("E:/work_space/poi/com/ray/poi/util/demo.doc"); boolean b = POIWordUtil.writeDoc("c:\\demo.doc",wr); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}

D. poi word

java poi? 老兄 你发错地方了 编程方面的东西发这里估计没人懂的poi 你不改变式样 他怎么会变呢 你肯定是无意中改变了风格 检查检查代码吧

E. java poi导出word 可以设置格式吗

读取word 2003及word 2007需要的jar包

读取 2003 版本(.doc)的word文件相对来说比较简单,只需要 poi-3.5-beta6-.jar 和 poi-scratchpad-3.5-beta6-.jar 两个 jar 包即可, 而 2007 版本(.docx)就麻烦多,我说的这个麻烦不是我们写代码的时候麻烦,是要导入的 jar 包比较的多,有如下 7 个之多:

1. openxml4j-bin-beta.jar

2. poi-3.5-beta6-.jar

3. poi-ooxml-3.5-beta6-.jar

4 .dom4j-1.6.1.jar

5. geronimo-stax-api_1.0_spec-1.0.jar

6. ooxml-schemas-1.0.jar

7. xmlbeans-2.3.0.jar

其中 4-7 是 poi-ooxml-3.5-beta6-.jar 所依赖的 jar 包(在 poi-bin-3.5-beta6-.tar.gz 中的 ooxml-lib 目录下可以找到)。

2.换行符号

硬换行:文件中换行,如果是键盘中使用了"enter"的换行。

软换行:文件中一行的字符数容量有限,当字符数量超过一定值时,会自动切到下行显示。

对程序来说,硬换行才是可以识别的、确定的换行,软换行与字体大小、缩进有关。

3.读取的注意事项

值得注意的是: POI 在读取不会读取 word 文件中的图片信息; 还有就是对于 2007 版的 word(.docx), 如果 word 文件中有表格,所有表格中的数据都会在读取出来的字符串的最后。

4.读取word文本内容代码

1 import java.io.File;

2 import java.io.FileInputStream;

3 import java.io.InputStream;

4

5 import org.apache.poi.POIXMLDocument;

6 import org.apache.poi.POIXMLTextExtractor;

7 import org.apache.poi.hwpf.extractor.WordExtractor;

8 import org.apache.poi.openxml4j.opc.OPCPackage;

9 import org.apache.poi.xwpf.extractor.XWPFWordExtractor;

10

11 public class Test {

12 public static void main(String[] args) {

13 try {

14 InputStream is = new FileInputStream(new File("2003.doc"));

15 WordExtractor ex = new WordExtractor(is);

16 String text2003 = ex.getText();

17 System.out.println(text2003);

18

19 OPCPackage opcPackage = POIXMLDocument.openPackage("2007.docx");

20 POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);

21 String text2007 = extractor.getText();

22 System.out.println(text2007);

23

24 } catch (Exception e) {

25 e.printStackTrace();

26 }

27 }

28 }

F. POI 生成WORD文档为什么WORD文档打不开

Jacob解决Word文档的读写问题收藏Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。Jacob下载的地址为:http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368配置:(1)将解压包中的jacob.dll(x86常用,x64)拷到jdk安装目录下的jre\bin文件夹或windows安装路径下的WINDOWS\system32文件夹下(2)将jacob.jar文件拷到classpath下即可常见问题解决:对于”java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll: 由于应用程序配置不正确,应用程序未能启动。重新安装应用程序可能会纠正”这个问题,可以通过重新下载Jacob的jar及dll文件(最好版本比现在的低,如1.11)解决实例制作(主要功能:标题制作,表格制作,合并表格,替换文本,页眉页脚,书签处理):import com.jacob.activeX.ActiveXComponent;import com.jacob.com.Dispatch;import com.jacob.com.Variant;public class WordOperate {public static void main(String args[]) {ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 启动word// Set the visible property as required.Dispatch.put(wordApp, "Visible", new Variant(true));// //设置word可见Dispatch docs = wordApp.getProperty("Documents").toDispatch();// String inFile = "d:\\test.doc";// Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,// new Object[] { inFile, new Variant(false), new Variant(false)},//参数3,false:可写,true:只读// new int[1]).toDispatch();//打开文档Dispatch document = Dispatch.call(docs, "Add").toDispatch();// create new documentString userName = wordApp.getPropertyAsString("Username");// 显示用户信息System.out.println("用户名:" + userName);// 文档对齐,字体设置////////////////////////Dispatch selection = Dispatch.get(wordApp, "Selection").toDispatch();Dispatch align = Dispatch.get(selection, "ParagraphFormat").toDispatch(); // 行列格式化需要的对象Dispatch font = Dispatch.get(selection, "Font").toDispatch(); // 字型格式化需要的对象// 标题处理////////////////////////Dispatch.put(align, "Alignment", "1"); // 1:置中 2:靠右 3:靠左Dispatch.put(font, "Bold", "1"); // 字型租体Dispatch.put(font, "Color", "1,0,0,0"); // 字型颜色红色Dispatch.call(selection, "TypeText", "Word文档处理"); // 写入标题内容Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左Dispatch.put(selection, "Text", " ");Dispatch.call(selection, "MoveDown"); // 光标标往下一行//表格处理////////////////////////Dispatch tables = Dispatch.get(document, "Tables").toDispatch();Dispatch range = Dispatch.get(selection, "Range").toDispatch();Dispatch table1 = Dispatch.call(tables, "Add", range, new Variant(3),new Variant(2), new Variant(1)).toDispatch(); // 设置行数,列数,表格外框宽度// 所有表格Variant tableAmount = Dispatch.get(tables, "count");System.out.println(tableAmount);// 要填充的表格Dispatch t1 = Dispatch.call(tables, "Item", new Variant(1)).toDispatch();Dispatch t1_row = Dispatch.get(t1, "rows").toDispatch();// 所有行int t1_rowNum = Dispatch.get(t1_row, "count").getInt();Dispatch.call(Dispatch.get(t1, "columns").toDispatch(), "AutoFit");// 自动调整int t1_colNum = Dispatch.get(Dispatch.get(t1, "columns").toDispatch(),"count").getInt();System.out.println(t1_rowNum + " " + t1_colNum);for (int i = 1; i <= t1_rowNum; i++) {for (int j = 1; j <= t1_colNum; j++) {Dispatch cell = Dispatch.call(t1, "Cell", new Variant(i),new Variant(j)).toDispatch();// 行,列Dispatch.call(cell, "Select");Dispatch.put(selection, "Text", "cell" + i + j); // 写入word的内容Dispatch.put(font, "Bold", "0"); // 字型租体(1:租体 0:取消租体)Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色Dispatch.put(font, "Italic", "1"); // 斜体 1:斜体 0:取消斜体Dispatch.put(font, "Underline", "1"); // 下划线Dispatch Range = Dispatch.get(cell, "Range").toDispatch();String cellContent = Dispatch.get(Range, "Text").toString();System.out.println((cellContent.substring(0, cellContent.length() – 1)).trim());}Dispatch.call(selection, "MoveDown"); // 光标往下一行(才不会输入盖过上一输入位置)}//合并单元格////////////////////////Dispatch.put(selection, "Text", " ");Dispatch.call(selection, "MoveDown"); // 光标标往下一行Dispatch range2 = Dispatch.get(selection, "Range").toDispatch();Dispatch table2 = Dispatch.call(tables, "Add", range2, new Variant(8),new Variant(4), new Variant(1)).toDispatch(); // 设置行数,列数,表格外框宽度Dispatch t2 = Dispatch.call(tables, "Item", new Variant(2)).toDispatch();Dispatch beginCell = Dispatch.call(t2, "Cell", new Variant(1),new Variant(1)).toDispatch();Dispatch endCell = Dispatch.call(t2, "Cell", new Variant(4),new Variant(4)).toDispatch();Dispatch.call(beginCell, "Merge", endCell);for (int row = 1; row <= Dispatch.get(Dispatch.get(t2, "rows").toDispatch(), "count").getInt(); row++) {for (int col = 1; col <= Dispatch.get(Dispatch.get(t2, "columns").toDispatch(), "count").getInt(); col++) {if (row == 1) {Dispatch cell = Dispatch.call(t2, "Cell", new Variant(1),new Variant(1)).toDispatch();// 行,列Dispatch.call(cell, "Select");Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色Dispatch.put(selection, "Text", "merge Cell!");} else {Dispatch cell = Dispatch.call(t2, "Cell", new Variant(row),new Variant(col)).toDispatch();// 行,列Dispatch.call(cell, "Select");Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色Dispatch.put(selection, "Text", "cell" + row + col);}}Dispatch.call(selection, "MoveDown");}//Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));// 取消选择// Object content = Dispatch.get(doc,"Content").toDispatch();// Word文档内容查找及替换////////////////////////Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左Dispatch.put(font, "Color", 0);Dispatch.put(selection, "Text", "欢迎,Hello,world!");Dispatch.call(selection, "HomeKey", new Variant(6));// 移到开头Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件Dispatch.put(find, "Text", "hello"); // 查找字符串"hello"Dispatch.put(find, "Forward", "True");// 向前查找// Dispatch.put(find, "Format", "True");// 设置格式Dispatch.put(find, "MatchCase", "false");// 大小写匹配Dispatch.put(find, "MatchWholeWord", "True"); // 全字匹配Dispatch.call(find, "Execute"); // 执行查询Dispatch.put(selection, "Text", "你好");// 替换为"你好"//使用方法传入的参数parameter调用word文档中的MyWordMacro宏////Dispatch.call(document,macroName,parameter);//Dispatch.invoke(document,macroName,Dispatch.Method,parameter,new int[1]);//页眉,页脚处理////////////////////////Dispatch ActiveWindow = wordApp.getProperty("ActiveWindow").toDispatch();Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();Dispatch.put(View, "SeekView", "9"); //9是设置页眉Dispatch.put(align, "Alignment", "1"); // 置中Dispatch.put(selection, "Text", "这里是页眉"); // 初始化时间Dispatch.put(View, "SeekView", "10"); // 10是设置页脚Dispatch.put(align, "Alignment", "2"); // 靠右Dispatch.put(selection, "Text", "这里是页脚"); // 初始化从1开始//书签处理(打开文档时处理)//////////////////////////Dispatch activeDocument = wordApp.getProperty("ActiveDocument").toDispatch();Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();boolean isExist = Dispatch.call(bookMarks, "Exists", "bookMark1").getBoolean();if (isExist == true) {Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1").toDispatch();Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();Dispatch.put(range1, "Text", new Variant("当前是书签1的文本信息!"));String bookMark1Value = Dispatch.get(range1, "Text").toString();System.out.println(bookMark1Value);} else {System.out.println("当前书签不存在,重新建立!");Dispatch.call(bookMarks, "Add", "bookMark1", selection);Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1").toDispatch();Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();Dispatch.put(range1, "Text", new Variant("当前是书签1的文本信息!"));String bookMark1Value = Dispatch.get(range1, "Text").toString();System.out.println(bookMark1Value); }//保存操作////////////////////////Dispatch.call(document, "SaveAs", "D:/wordOperate.doc");//Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method, new Object[]{htmlPath, new Variant(8)}, new int[1]); //生成html文件// 0 = wdDoNotSaveChanges// -1 = wdSaveChanges// -2 = wdPromptToSaveChanges//Dispatch.call(document, "Close", new Variant(0));// // worddoc.olefunction("protect",2,true,"");// // Dispatch bookMarks = wordApp.call(docs,"Bookmarks").toDispatch();// // System.out.println("bookmarks"+bookMarks.getProgramId());// //Dispatch.call(doc, "Save"); //保存// // Dispatch.call(doc, "Close", new Variant(true));// //wordApp.invoke("Quit",new Variant[]{});// wordApp.safeRelease();//Finalizers call this method}

G. 怎么使用poi修改word(doc和docx),如何修改带表格的word。高手指点下。小弟刚接触。非常着急

把word内容用poi读出来,成字符串,把字符串在内存中修改,修改字符串可用各种方法,正则是比较好的了

H. 如何使用POI解决word2007中字符替换问题

首先就是要明白解决的方案是:先删后添。就是利用Paragraph创建run,在创建完毕后循环遍历tableàrowàcell,获得到cell里的值,即cell.getText();在这里注意cell中value的长度,建议打出来看看已在后面于替换后的cell的值做对比。同时我们应该多多关注底层文件和源码,这样可以更加方便的了解他的底层构造。可以将word的后缀名改为zip然后打开找到word/document.xml文件,查看构造尤其是表的结构(比如说多关注关注-<w:tc>- <w:tcPr><w:tcW w:w="852" w:type="dxa" /></w:tcPr>- <w:p w:rsidR="00B2466A" w:rsidRDefault="004E26BC">- <w:r>- <w:rPr><w:rFonts w:hint="eastAsia" /></w:rPr><w:t>02</w:t></w:r></w:p></w:tc>)这样有助于思维的扩展;

I. 用poi读取word总是抱异常,我真无语了,我的QQ是450713994,如果做过类似的,请具体探讨 !

/** * 读取OFFICE文件 * @param office * @return * @throws Exception */ public String readOffice(String officePath) { String text = null; FileInputStream in = null; try { in = new FileInputStream(officePath); POITextExtractor extractor = ExtractorFactory.createExtractor(in); text = extractor.getText(); } catch (Exception e) { e.printStackTrace(); }finally{ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return text; }不知道你需要实现什么功能,这个是我通过POI读取office文件的方法,你试试,看是否会报错,通过office文件路径读取文件中字符串,如果遇到是图片的肯定不能读取的。