java操作word内部资料

合集下载

java使用POI操作XWPFDocument生成Word实战(一)

java使用POI操作XWPFDocument生成Word实战(一)

java使⽤POI操作XWPFDocument⽣成Word实战(⼀)注:我使⽤的word 2016功能简介:(1)使⽤jsoup解析html得到我⽤来⽣成word的⽂本(这个你们可以忽略)(2)⽣成word、设置页边距、设置页脚(页码),设置页码(⽂本)⼀、解析htmlDocument doc = Jsoup.parseBodyFragment(contents);Element body = doc.body();Elements es = body.getAllElements();⼆、循环Elements获取我需要的html标签boolean tag = false;for (Element e : es) {//跳过第⼀个(默认会把整个对象当做第⼀个)if(!tag) {tag = true;continue;}//创建段落:⽣成word(核⼼)createXWPFParagraph(docxDocument,e);}三、⽣成段落/*** 构建段落* @param docxDocument* @param e*/public static void createXWPFParagraph(XWPFDocument docxDocument, Element e){XWPFParagraph paragraph = docxDocument.createParagraph();XWPFRun run = paragraph.createRun();run.setText(e.text());run.setTextPosition(35);//设置⾏间距if(e.tagName().equals("titlename")){paragraph.setAlignment(ParagraphAlignment.CENTER);//对齐⽅式run.setBold(true);//加粗run.setColor("000000");//设置颜⾊--⼗六进制run.setFontFamily("宋体");//字体run.setFontSize(24);//字体⼤⼩}else if(e.tagName().equals("h1")){addCustomHeadingStyle(docxDocument, "标题 1", 1);paragraph.setStyle("标题 1");run.setBold(true);run.setColor("000000");run.setFontFamily("宋体");run.setFontSize(20);}else if(e.tagName().equals("h2")){addCustomHeadingStyle(docxDocument, "标题 2", 2);paragraph.setStyle("标题 2");run.setBold(true);run.setColor("000000");run.setFontFamily("宋体");run.setFontSize(18);}else if(e.tagName().equals("h3")){addCustomHeadingStyle(docxDocument, "标题 3", 3);paragraph.setStyle("标题 3");run.setBold(true);run.setColor("000000");run.setFontFamily("宋体");run.setFontSize(16);}else if(e.tagName().equals("p")){//内容paragraph.setAlignment(ParagraphAlignment.BOTH);//对齐⽅式paragraph.setIndentationFirstLine(WordUtil.ONE_UNIT);//⾸⾏缩进:567==1厘⽶run.setBold(false);run.setColor("001A35");run.setFontFamily("宋体");run.setFontSize(14);//run.addCarriageReturn();//回车键}else if(e.tagName().equals("break")){paragraph.setPageBreak(true);//段前分页(ctrl+enter)}四、设置页边距/*** 设置页边距 (word中1厘⽶约等于567)* @param document* @param left* @param top* @param right* @param bottom*/public static void setDocumentMargin(XWPFDocument document, String left,String top, String right, String bottom) {CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();CTPageMar ctpagemar = sectPr.addNewPgMar();if (StringUtils.isNotBlank(left)) {ctpagemar.setLeft(new BigInteger(left));}if (StringUtils.isNotBlank(top)) {ctpagemar.setTop(new BigInteger(top));}if (StringUtils.isNotBlank(right)) {ctpagemar.setRight(new BigInteger(right));}if (StringUtils.isNotBlank(bottom)) {ctpagemar.setBottom(new BigInteger(bottom));}}五、创建页眉/*** 创建默认页眉** @param docx XWPFDocument⽂档对象* @param text 页眉⽂本* @return返回⽂档帮助类对象,可⽤于⽅法链调⽤* @throws XmlException XML异常* @throws IOException IO异常* @throws InvalidFormatException ⾮法格式异常* @throws FileNotFoundException 找不到⽂件异常*/public static void createDefaultHeader(final XWPFDocument docx, final String text){CTP ctp = CTP.Factory.newInstance();XWPFParagraph paragraph = new XWPFParagraph(ctp, docx);ctp.addNewR().addNewT().setStringValue(text);ctp.addNewR().addNewT().setSpace(SpaceAttribute.Space.PRESERVE);CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr(); XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);XWPFHeader header = policy.createHeader(STHdrFtr.DEFAULT, new XWPFParagraph[] { paragraph });header.setXWPFDocument(docx);}}六、创建页脚/*** 创建默认的页脚(该页脚主要只居中显⽰页码)** @param docx* XWPFDocument⽂档对象* @return返回⽂档帮助类对象,可⽤于⽅法链调⽤* @throws XmlException* XML异常* @throws IOException* IO异常*/public static void createDefaultFooter(final XWPFDocument docx) {// TODO 设置页码起始值CTP pageNo = CTP.Factory.newInstance();XWPFParagraph footer = new XWPFParagraph(pageNo, docx);CTPPr begin = pageNo.addNewPPr();begin.addNewPStyle().setVal(STYLE_FOOTER);begin.addNewJc().setVal(STJc.CENTER);pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);pageNo.addNewR().addNewInstrText().setStringValue("PAGE \\* MERGEFORMAT");pageNo.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);CTR end = pageNo.addNewR();CTRPr endRPr = end.addNewRPr();endRPr.addNewNoProof();endRPr.addNewLang().setVal(LANG_ZH_CN);end.addNewFldChar().setFldCharType(STFldCharType.END);CTSectPr sectPr = docx.getDocument().getBody().isSetSectPr() ? docx.getDocument().getBody().getSectPr() : docx.getDocument().getBody().addNewSectPr(); XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);policy.createFooter(STHdrFtr.DEFAULT, new XWPFParagraph[] { footer });}七、⾃定义标题样式(这个在我另⼀篇word基础中也有提及)* 增加⾃定义标题样式。

JAVA读取WORD文档解决方案

JAVA读取WORD文档解决方案

JAVA读取WORD文档解决方案在Java中读取Word文档需要使用特定的Java库或API来解析和处理Word文档格式(.doc或.docx)。

在下面的解决方案中,我们将介绍两种流行的Java库,即Apache POI和JavaFX的XSSF。

1. Apache POI:Apache POI是一个流行的开源Java库,用于处理Microsoft Office 格式的文件,包括Word文档。

下面是使用Apache POI库读取Word文档的步骤:1.1 添加Apache POI依赖库到项目中。

在Maven项目中,可以在pom.xml文件中添加以下依赖项:```xml<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>```1.2 使用`XWPFDocument`类打开Word文档。

下面是一个示例代码:```javaFileInputStream fis = newFileInputStream("path/to/word/document.docx");XWPFDocument document = new XWPFDocument(fis);fis.close(;```1.3 使用`XWPFParagraph`类和`XWPFRun`类来遍历Word文档中的段落和文本。

Java 读取Word中的文本的图片

Java 读取Word中的文本的图片

Java 提取Word中的文本和图片本文将介绍通过Java来提取或读取Word文档中文本和图片的方法。

这里提取文本和图片包括同时提取文档正文当中以及页眉、页脚中的的文本和图片。

使用工具:Spire.Doc for JavaJar文件导入方法(参考):方法1:下载jar文件包。

下载后解压文件,并将lib文件夹下的Spire.Doc.jar文件导入到java程序。

导入效果参考如下:方法2:可通过maven导入。

参考导入方法。

测试文档如下:Java 代码示例(供参考)【示例1】提取Word 中的文本 import com.spire.doc.*; import java.io.FileWriter;import java.io.IOException;public class ExtractText {public static void main(String[] args) throws IOException{//加载测试文档Document doc = new Document();doc.loadFromFile("test.docx");//获取文本保存为StringString text = doc.getText();//将String写入TxtwriteStringToTxt(text,"提取文本.txt");}public static void writeStringToTxt(String content, String txtFileName) throws IOException {FileWriter fWriter= new FileWriter(txtFileName,true);try {fWriter.write(content);}catch(IOException ex){ex.printStackTrace();}finally{try{fWriter.flush();fWriter.close();} catch (IOException ex) {ex.printStackTrace();}}}}文本提取结果:【示例2】提取Word中的图片import com.spire.doc.Document;import com.spire.doc.documents.DocumentObjectType;import com.spire.doc.fields.DocPicture;import com.spire.doc.interfaces.ICompositeObject;import com.spire.doc.interfaces.IDocumentObject;import javax.imageio.ImageIO;import java.awt.image.RenderedImage;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class ExtractImg {public static void main(String[] args) throws IOException { //加载Word文档Document document = new Document();document.loadFromFile("test.docx");//创建Queue对象Queue nodes = new LinkedList();nodes.add(document);//创建List对象List images = new ArrayList();//遍历文档中的子对象while (nodes.size() > 0) {ICompositeObject node = (ICompositeObject) nodes.poll();for (int i = 0; i < node.getChildObjects().getCount(); i++) {IDocumentObject child = node.getChildObjects().get(i);if (child instanceof ICompositeObject) {nodes.add((ICompositeObject) child);//获取图片并添加到Listif (child.getDocumentObjectType() == DocumentObjectType.Picture) { DocPicture picture = (DocPicture) child;images.add(picture.getImage());}}}}//将图片保存为PNG格式文件for (int i = 0; i < images.size(); i++) {File file = new File(String.format("图片-%d.png", i));ImageIO.write((RenderedImage) images.get(i), "PNG", file);}}}图片提取结果:(本文完)。

如何通过java给word模板当中的内容进行换行

如何通过java给word模板当中的内容进行换行

如何通过java给word模板当中的内容进⾏换⾏代码⽰例/*** 换⾏⽅法* @param wordPath word模板的地址* @param wordOutPath 换⾏后输出word的新地址*/public static void wordNewLine(String wordPath,String wordOutPath){//获取⽂档docXWPFDocument doc = null;try {doc = new XWPFDocument(new FileInputStream(wordPath));} catch (IOException e) {e.printStackTrace();}//遍历所有表格for(XWPFTable table : doc.getTables()) {for(XWPFTableRow row : table.getRows()) {for(XWPFTableCell cell : row.getTableCells()) {//单元格 : 直接cell.setText()只会把⽂字加在原有的后⾯,删除不了⽂字addBreakInCell(cell);}}}try {doc.write(new FileOutputStream(wordOutPath));} catch (IOException e) {e.printStackTrace();}}/*** 匹配单元格内容\n 替换为换⾏* @param cell*/private static void addBreakInCell(XWPFTableCell cell) {if (cell.getText() != null && cell.getText().contains("\n")) {for (XWPFParagraph paragraph : cell.getParagraphs()) {paragraph.setAlignment(ParagraphAlignment.LEFT);for (XWPFRun run : paragraph.getRuns()) {if (run.getText(0) != null && run.getText(0).contains("\n")) {String[] lines = run.getText(0).split("\n");if (lines.length > 0) {// set first line into XWPFRunrun.setText(lines[0], 0);for (int i = 1; i < lines.length; i++) {// add break and insert new textrun.addBreak();run.setText(lines[i]);}}}}}}}这⾥需要注意⼀点⽹络上⾯我测试了/n ,/r,/n/r,包括/r/n都不能完美实现换⾏,所以最后通过addBreak这个函数实现了函数的换⾏。

JavaPOI操作word文档内容、表格

JavaPOI操作word文档内容、表格

JavaPOI操作word⽂档内容、表格⼀、pom<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.0.0</version></dependency>⼆、直接上代码word模板中${content} 注意我只有在.docx⽤XWPFDocument才有效2.1/*** 获取document**/XWPFDocument document = null;try {document = new XWPFDocument(inputStream);} catch (IOException ioException) {ioException.printStackTrace();}/*** 替换段落⾥⾯的变量** @param doc 要替换的⽂档* @param params 参数*/private void replaceInPara(XWPFDocument doc, Map<String, String> params) {for (XWPFParagraph para : doc.getParagraphs()) {replaceInPara(para, params);}}/*** 替换段落⾥⾯的变量** @param para 要替换的段落* @param params 参数*/private void replaceInPara(XWPFParagraph para, Map<String, String> params) {List<XWPFRun> runs;Matcher matcher;replaceText(para);//如果para拆分的不对,则⽤这个⽅法修改成正确的if (matcher(para.getParagraphText()).find()) {runs = para.getRuns();for (int i = 0; i < runs.size(); i++) {XWPFRun run = runs.get(i);String runText = run.toString();matcher = matcher(runText);if (matcher.find()) {while ((matcher = matcher(runText)).find()) {runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));}//直接调⽤XWPFRun的setText()⽅法设置⽂本时,在底层会重新创建⼀个XWPFRun,把⽂本附加在当前⽂本后⾯, para.removeRun(i);para.insertNewRun(i).setText(runText);}}}}/*** 替换⽂本内容* @param para* @return*/private List<XWPFRun> replaceText(XWPFParagraph para) {List<XWPFRun> runs = para.getRuns();String str = "";boolean flag = false;for (int i = 0; i < runs.size(); i++) {XWPFRun run = runs.get(i);String runText = run.toString();if (flag || runText.equals("${")) {str = str + runText;flag = true;para.removeRun(i);if (runText.equals("}")) {flag = false;para.insertNewRun(i).setText(str);str = "";}i--;}}return runs;}2.22.2.1XWPFTable table = document.getTableArray(0);//获取当前表格XWPFTableRow twoRow = table.getRow(2);//获取某⼀⾏XWPFTableRow nextRow = table.insertNewTableRow(3);//插⼊⼀⾏XWPFTableCell firstRowCellOne = firstRow.getCell(0);firstRowCellOne.removeParagraph(0);//删除默认段落,要不然表格内第⼀条为空⾏XWPFParagraph pIO2 =firstRowCellOne.addParagraph();XWPFRun rIO2 = pIO2.createRun();rIO2.setFontFamily("宋体");//字体rIO2.setFontSize(8);//字体⼤⼩rIO2.setBold(true);//是否加粗rIO2.setColor("FF0000");//字体颜⾊rIO2.setText("这是写⼊的内容");//rIO2.addBreak(BreakType.TEXT_WRAPPING);//软换⾏,亲测有效/*** 复制单元格和样式** @param targetRow 要复制的⾏* @param sourceRow 被复制的⾏*/public void createCellsAndCopyStyles(XWPFTableRow targetRow, XWPFTableRow sourceRow) {targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr());List<XWPFTableCell> tableCells = sourceRow.getTableCells();if (CollectionUtils.isEmpty(tableCells)) {return;}for (XWPFTableCell sourceCell : tableCells) {XWPFTableCell newCell = targetRow.addNewTableCell();newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());List sourceParagraphs = sourceCell.getParagraphs();if (CollectionUtils.isEmpty(sourceParagraphs)) {continue;}XWPFParagraph sourceParagraph = (XWPFParagraph) sourceParagraphs.get(0);List targetParagraphs = newCell.getParagraphs();if (CollectionUtils.isEmpty(targetParagraphs)) {XWPFParagraph p = newCell.addParagraph();p.getCTP().setPPr(sourceParagraph.getCTP().getPPr());XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0);run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily());} else {XWPFParagraph p = (XWPFParagraph) targetParagraphs.get(0);p.getCTP().setPPr(sourceParagraph.getCTP().getPPr());XWPFRun run = p.getRuns().isEmpty() ? p.createRun() : p.getRuns().get(0);if (sourceParagraph.getRuns().size() > 0) {run.setFontFamily(sourceParagraph.getRuns().get(0).getFontFamily());}}}}#### 2.2.3/*** 合并单元格** @param table 表格对象* @param beginRowIndex 开始⾏索引* @param endRowIndex 结束⾏索引* @param colIndex 合并列索引*/public void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) { if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) {return;}//合并⾏单元格的第⼀个单元格CTVMerge startMerge = CTVMerge.Factory.newInstance();startMerge.setVal(STMerge.RESTART);//合并⾏单元格的第⼀个单元格之后的单元格CTVMerge endMerge = CTVMerge.Factory.newInstance();endMerge.setVal(STMerge.CONTINUE);table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge); for (int i = beginRowIndex + 1; i <= endRowIndex; i++) {table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge);}}/*** insertRow 在word表格中指定位置插⼊⼀⾏,并将某⼀⾏的样式复制到新增⾏* @param copyrowIndex 需要复制的⾏位置* @param newrowIndex 需要新增⼀⾏的位置* */public static void insertRow(XWPFTable table, int copyrowIndex, int newrowIndex) {// 在表格中指定的位置新增⼀⾏XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);// 获取需要复制⾏对象XWPFTableRow copyRow = table.getRow(copyrowIndex);//复制⾏对象targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());//或许需要复制的⾏的列List<XWPFTableCell> copyCells = copyRow.getTableCells();//复制列对象XWPFTableCell targetCell = null;for (int i = 0; i < copyCells.size(); i++) {XWPFTableCell copyCell = copyCells.get(i);targetCell = targetRow.addNewTableCell();targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr()); if (copyCell.getParagraphs().get(0).getRuns() != null&& copyCell.getParagraphs().get(0).getRuns().size() > 0) {XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());}}}}/*** 正则匹配字符串** @param str* @return*/private Matcher matcher(String str) {Pattern pattern = pile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(str);return matcher;}。

Java解析OFFICE(word,excel,powerpoint)以及PDF的实现方案。。。

Java解析OFFICE(word,excel,powerpoint)以及PDF的实现方案。。。

Java解析OFFICE(word,excel,powerpoint)以及PDF的实现⽅案。

Java解析OFFICE(word,excel,powerpoint)以及PDF的实现⽅案及开发中的点滴分享 在此,先分享下写此⽂前的经历与感受,我所有的感觉浓缩到⼀个字,那就是:"坑",如果是两个字那就是"巨坑"=>因为这个需求⼀开始并不是这样⼦的,且听我漫漫道来: ⼀开始客户与我们商量的是将office和PDF上传,将此类⽂件解析成html格式,在APP端调⽤内置server直接以html"播放" 经历⼀个⽉~,两个⽉~,三个⽉~~~ 到需求开发阶段,发现这是个坑。

:按照需规的意思这个整体是当做⼀个功能来做的,技术难度也就算了,⽽且按照估算的⼯时也很难做成需规所需要的样⼦(缺陷太多!) 然后⼀周~,⼀周~,⼜⼀周~~~ 各种⽅案下来将需求做成能⽤的样⼦,然后需求确认时客户说:“我们没有要求你们能解析这些⽂档,我们只要求你们当做⼀个源⽂件上传,在APP端点击直接能选择调⽤第三⽅应⽤打开就⾏了,⽽且⼀开始我们的需求就是这样的。

” /**听完,顿时泪流满⾯( _ ),如果业务⼀开始就确认这样做,何⾄于浪费如此多的时间,花费如此多的精⼒绕⽼⼤⼀圈。

*/ 需求绕了⼀圈⼜绕回来了,作为经历过的⼈,现在总结下这需求⾥⾯⽆尽的坑: A>开源社区有很多Demo,这些Demo有很多缺陷,⽐如office⾥⾯的艺术字、图⽚、公式、颜⾊样式、视频和⾳频不能解析 B>能解析的对象,解析出来的效果不是很好,⽐如word和ppt⾃⾝的排版乱了,excel单元格⾥⾯的⾃定义格式全变成数字了~等等 C>开源社区的资料并不是很全,导致的结果是不同的⽂档类型需要⽤不同的解析⽅式去解析,⽐如word⽤docx4j解析、excel⽤poi解析带来的代码量巨⼤ D>由于代码⾃⾝的解析效果不是很好,更改后的⽅案需要在上传之前将源⽂件处理成其他的形式,如pdf需要切成图⽚,ppt需要转换成视频或是图⽚,这样⼀来需求实现的⽅式就变成半⾃动了╥﹏╥... E>word⽤docx4j解析⼀个很⼤的问题是解析的效率太低了,5MB以上的⽂件或者内容⽐较复杂的word⽂档解析⼗分耗时,解析效率太低,再⼀就是poi解析数据量⽐较⼤的Exel(⽐如>1000⾏)容易造成内存溢出,不好控制 F>⼯时太短,只有15天。

Java解析word文档

Java解析word文档
for(int j=1;j<imgCount+1;j++){ Dispatch shape = Dispatch.call(imgDispatch, "Item", new Variant(1)).toDispatch(); Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch(); Dispatch.call(imageRange, "Copy"); (imageRange, "Paste"); } }
Java解 析 word文 档 背景 在互联网教育行业,做内容相关的项目经常碰到的一个问题就是如何解析word文档。 因为系统如果无法智能的解析word,那么就只能通过其他方式手动录入word内容,效率低下,而且人工成本和录入出错率都较高。 疑难点 word解析可以预见的困难主要有以下几个方面: word 结构问题 —— word不开源,且含有很多非文本内容,比如图表,而已知的常规方法只能解析纯文本内容,所以如果不知道word内部 层级结构,解析将难以进行。 word 公式问题 —— word公式来源并非单一,可能是用MathType插件生成的latex公式,也可能是用word自带公式编辑器生成的公式,还有 可能公式部分手敲,部分使用搜狗输入法或者其它编辑器输入。不同来源处理方式是否一样?且能否有效读取文档各种上下脚标?方便后 期展示? word 非文本问题 —— word含有很多的非文本内容,比如图表。来源也多样,图表可能是用word自带的画图工具生成的,也有可能是复制 粘贴的,不同来源解析方式是否一样?且读取的时候是否能有效获取图片的位置及大小信息?方便文档内容后期在PC端和移动端展示。无 论最终方案是什么,肯定是将所有的且需要的非文本信息转换为文本信息。 word 版本问题 —— word有03、07等好几个版本,还有WPS版本,解析是否要全部兼容?后缀名有docx和doc,是否全部兼容?当然,前 提是已经成功解析一种类型。 word 规范问题 —— 有些word可能是早期制作的,返工代价太大,所以格式内容多样化。而且就算制定word格式规范,新制作的word也无 法保证格式一定正确,除非是程序自动生成的文档。举个例子,试题的题序,肉眼无法区分的格式就有好几种。程序只可能尽量覆盖绝大 部分情况,考虑的情况越多,解析正确率越高,当然程序也更复杂。

java解析world 文件 修改内容

java解析world 文件 修改内容

java解析world 文件修改内容Java解析World文件是一种常见的操作,可以通过读取并修改World文档中的内容。

World文件是一种二进制文件格式,通常用于Microsoft Office中的Word软件。

在Java中,我们可以使用一些库来实现这个功能,例如Apache POI。

首先,我们需要导入Apache POI的相关依赖。

可以在Maven项目的pom.xml 文件中添加以下代码:```xml<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>```接下来,我们可以通过以下步骤来解析并修改World文件的内容:1. 创建一个`FileInputStream`对象,用于打开World文件:```javaFileInputStream file = new FileInputStream("path/to/your/world.doc");```2. 创建一个`XWPFDocument`对象,用于表示整个解析后的文档:```javaXWPFDocument document = new XWPFDocument(file);```3. 遍历文档中的段落,并修改需要修改的内容:```javafor (XWPFParagraph paragraph : document.getParagraphs()) {String text = paragraph.getText();// 进行内容修改,例如替换指定文本text = text.replace("需要修改的内容", "替换后的内容");// 将修改后的文本重新设置回段落中paragraph.setText(text);}```4. 保存修改后的文档到新的文件中:```javaFileOutputStream outputStream = newFileOutputStream("path/to/your/modified_world.doc");document.write(outputStream);outputStream.close();```通过以上步骤,我们可以实现Java解析并修改World文件的功能。

通过Java往word中写入内容

通过Java往word中写入内容
xlsheet.Cells(2,2).Value="密码";
xlsheet.Cells(2,3).Value="计费方式";
xlsheet.Cells(2,4).Value="有效天数";
xlsheet.Cells(2,5).Value="金额";
xlsheet.Cells(2,6).Value="所属服务项目";
xlsheet.Rows(1)="黑体";
<!--设置列宽xlsheet.Columns(2)=14;-->
xlsheet.Columns("A:D").ColumnWidth=18;
<!--设置显示字符而不是数字-->
xlsheet.Columns(2).NumberFormatLocal="@";
<!--设置行高-->
xlsheet.Rows(1).RowHeight=25;
<!--设置字体ws.Range(ws.Cells(i0+1,j0),ws.Cells(i0+1,j1)).Font.Size=13-->
xlsheet.Rows(1).Font.Size=14;
<!--设置字体设置选定区的字体xlsheet.Range(xlsheet.Cells(i0,j0),ws.Cells(i0,j0))="黑体"-->
sel.moveEnd('character');
myRange.Paste();
myRange=mydoc.Range(myRange.End-1,myRange.End);

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利用word模版导出word文档详细说明

java利用word模版导出word文档详细说明
//定义Template对象
t = configuration.getTemplate(fileName);
//configuration.setDirectoryForTemplateLoading(new File("E:/"));
public class DocumentHandler {
private Configuration configuration = null;
public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
我用的jar包为freemarker-2.3.15.jar
首先把代码贴了,这是主程序
package com.tiger.document;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
}
public void createDoc(String dir,String fileName, String savePath,String[][] sDate) {

Java 复制Word文档

Java 复制Word文档

Java 复制Word文档本文介绍在Java程序中如何复制Word文档。

复制方法均以带格式复制,代码示例将从以下要点展示:复制Word正文内容,可支持包括文本、图片、表格、超链接、书签、批注、形状、编号列表、脚注、尾注等在内的多种元素。

复制时,可复制整篇文档内容和复制指定段落内容复制Word页眉页脚,包括页眉页脚中的文本、图片、页码域等等复制Word水印效果,包括文本水印、图片水印工具:Free Spire.Doc for Java(免费版)可下载jar包,并解压将lib文件夹下的jar文件导入Java程序,或通过maven仓库下载导入。

参考如下导入效果:用于测试的两个文档如下,将左边文档内容复制到右边的文档:【示例1】复制Word正文内容1.1 复制整篇文档内容import com.spire.doc.*;public class CopyDoc {public static void main(String[] args) {//加载文档1Document doc1 = new Document();doc1.loadFromFile("test.docx");//加载文档2Document doc2 = new Document();doc2.loadFromFile("target.docx");//遍历文档1中的所有子对象for (int i = 0; i < doc1.getSections().getCount(); i++) {Section section = doc1.getSections().get(i);for( int j = 0;j< section.getBody().getChildObjects().getCount();j++){Object object = section.getBody().getChildObjects().get(j);//复制文档1中的正文内容添加到文档2doc2.getSections().get(0).getBody().getChildObjects().add(((DocumentObject) object).deepClone());}}//保存文档2doc2.saveToFile("CopyDoc.docx", FileFormat.Docx_2013);doc2.dispose();}}复制效果(这里复制的效果不含水印、页眉页脚等内容):1.2 复制指定段落内容import com.spire.doc.*;import com.spire.doc.documents.Paragraph;public class CopyPara {public static void main(String[] args) {//加载文档1Document doc1 = new Document();doc1.loadFromFile("test.docx");//获取文档1中的第三段Section section1 = doc1.getSections().get(0);Paragraph paragraph = section1.getParagraphs().get(2);//加载文档2,获取sectionDocument doc2 = new Document();doc2.loadFromFile("target.docx");Section section2 = doc2.getSections().get(0);//复制文档1中段落,添加到文档2Paragraph newparagraph = (Paragraph) paragraph.deepClone(); section2.getParagraphs().add(newparagraph);//保存文档2doc2.saveToFile("CopyPara.docx",FileFormat.Docx_2013);doc2.dispose();}}段落复制结果:【示例2】复制Word页眉页脚import com.spire.doc.*;public class CopyHeaderFooter {public static void main(String[] args) {//加载文档1Document doc1 = new Document();doc1.loadFromFile("test.docx");//获取sectionSection section1 = doc1.getSections().get(0);//获取文档1的页眉页脚HeaderFooter header = section1.getHeadersFooters().getHeader(); HeaderFooter footer = section1.getHeadersFooters().getFooter();//加载文档2Document doc2 = new Document();doc2.loadFromFile("target.docx");//遍历文档2的sectionfor (int i = 0; i< doc2.getSections().getCount();i++){Section section2 = doc2.getSections().get(i);//遍历页眉中的对象for(int j = 0 ; j< header.getChildObjects().getCount();j++){//获取页眉中的所有子对象Object object1 = header.getChildObjects().get(j);//复制文档1的页眉添加到文档2section2.getHeadersFooters().getHeader().getChildObjects().add(((DocumentObject) object1).deepClone());}//同理复制页脚for(int z = 0 ; z< footer.getChildObjects().getCount();z++){Object object2 = footer.getChildObjects().get(z);section2.getHeadersFooters().getFooter().getChildObjects().add(((DocumentObject) object2).deepClone());}}//保存文档2doc2.saveToFile("CopyHeaderFooter.docx",FileFormat.Docx_2013);doc2.dispose();}}页眉复制效果:页脚复制效果:【示例3】复制Word水印import com.spire.doc.*;public class CopyWatermark {public static void main(String[] args) {//加载文档1Document doc1 = new Document();doc1.loadFromFile("test.docx");//加载文档2Document doc2 = new Document();doc2.loadFromFile("target.docx");//获取文档1的水印效果,设置到文档2doc2.setWatermark(doc1.getWatermark());//保存文档2doc2.saveToFile("CopyWatermark.docx",FileFormat.Docx_2013);doc2.dispose();}}水印复制效果(此方法均适用于复制文本水印或图片水印):注:对于文档结构比较复制的Word,可综合以上方法来进行复制,查看复制效果。

java使用POI操作XWPFDocumen创建和读取OfficeWord文档基础篇

java使用POI操作XWPFDocumen创建和读取OfficeWord文档基础篇

java使⽤POI操作XWPFDocumen创建和读取OfficeWord⽂档基础篇注:有不正确的地⽅还望⼤神能够指出,抱拳了⽼铁!参考 API:主要参考⽂章 1:主要参考⽂章 2:主要参考⽂章 3:⼀、基本属性建议⼤家使⽤ office word 来创建⽂档。

(wps 和 word 结构有些不⼀样)IBodyElement ------------------- 迭代器(段落和表格)XWPFComment ------------------- 评论(个⼈理解应该是批注)XWPFSDTXWPFFooter ------------------- 页脚XWPFFootnotes ------------------- 脚注XWPFHeader ------------------- 页眉XWPFHyperlink ------------------- 超链接XWPFNumbering ------------------- 编号(我也不知是啥...)XWPFParagraph ------------------- 段落XWPFPictureData ------------------- 图⽚XWPFStyles ------------------- 样式(设置多级标题的时候⽤)XWPFTable ------------------- 表格⼆、正⽂段落⼀个⽂档包含多个段落,⼀个段落包含多个 Runs,⼀个 Runs 包含多个 Run,Run 是⽂档的最⼩单元获取所有段落:List paragraphs = word.getParagraphs();获取⼀个段落中的所有 Runs:List xwpfRuns = xwpfParagraph.getRuns();获取⼀个 Runs 中的⼀个 Run:XWPFRun run = xwpfRuns.get(index);XWPFRun-- 代表具有相同属性的⼀段⽂本三、正⽂表格⼀个⽂档包含多个表格,⼀个表格包含多⾏,⼀⾏包含多列(格),每⼀格的内容相当于⼀个完整的⽂档获取所有表格:List xwpfTables = doc.getTables();获取⼀个表格中的所有⾏:List xwpfTableRows = xwpfTable.getRows();获取⼀⾏中的所有列:List xwpfTableCells = xwpfTableRow.getTableCells();获取⼀格⾥的内容:List paragraphs = xwpfTableCell.getParagraphs();之后和正⽂段落⼀样注:1. 表格的⼀格相当于⼀个完整的 docx ⽂档,只是没有页眉和页脚。

java操作word(内部资料)

java操作word(内部资料)

JAVA操作wordJava操作Microsoft Word之jacob(1)现在我们一起来看看,用J1ava如何操作Microsoft Word。

jacob,官网是/jacob 这是一个开源的工具。

最新版本1.7官方的解释是:The JACOB Project: A JAva-COM Bridge这是官方对下载文件的说明:jacob.jar: a JAR file for the java classes which you must add to your CLASSPATH. The package names replace com.ms with com.jacob (for example .Variant maps to .Variant.jacob.dll: a small Win32 DLL which you must add to your PATH.samples: provided in Java source and compiled form to demonstrate various features of the product. In particular, a set of wrapper classes for Microsoft® ADO are provided as samples.开发环境:JDK 1.6MyEclipse Enterprise Workbench Version: 7.0 Milestone-1Tomcat 5.5.27现在MyEclipse中新建一个项目jacob,将jacob的jar包放到该项目的类库中。

我的jacob版本是1.14.3 。

下面这一步非常重要,就是拷贝jacob目录中jacob-1.14.3-x86.dll文件到系统环境变量目录中一般情况就放在当前jdk中bin目录下。

这里有一个MSWordManager 类,是jacob官方发布的工具类,里面有大多数Java操作MS Office的工具。

java操作word可操作书签

java操作word可操作书签

最近有个需求,在word模板文档上设置书签,然后从数据库中查询数据,填充到word 文档书签位置,刚拿到需求时,使劲在网上找资料。

幻想第三方jar包,帮我实现。

有Apatch 的POI,java2word,jcob等,一直让我无法实现。

POI操作word只能获取word中的书签,并不能进行操作.java2word可以实现,但是除了java2word.jar包以外,还要一个dll文件放在system32文件夹下,环境部署在linux服务器上,谁允许你放这样的文件,结果死心了.下面新建一个word2007文件告诉大家不用第三方技术怎么一一实现。

现在新建一个word,在请输入用户名处添加书签userName,请输入年龄处添加书签ageWord2007版本其实就是zip格式,将新建word后缀名改.zip,解压会发现,里面全是文件夹,打开word文件夹会有一个document.xml文件,在word所有内容,都在这xml文件中, <w:bookmarkStart w:id="0" w:name="userName"/><w:r><w:rPr><w:rFonts w:hint="eastAsia"/></w:rPr><w:t>请输入用户名</w:t></w:r><w:bookmarkEnd w:id="0"/>这是新建书签处的内容,细心的会发现,书签处内容在<w:bookmarkStart/> <w:bookmarkEnd w:id="0"/>标签之间,<w:bookmarkStart>标签中的w:id跟w:name标识书签的唯一,中间是书签处的内容,会不会可以这样呢,找到用dom或者sax解析这个xml 文档找到<w:bookmarkStart/>标签,然后找到<w:r>标签,再找到<w:r>标签里面的<w:t>标签内容,替换就Ok了呢。

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(doc)(docx)标题和内容----POI

JAVA读取word(doc)(docx)标题和内容----POI

JAVA读取word(doc)(docx)标题和内容----POI 1、下载poi的jar包 下载地址:下载解压后⽤到的jar包maven:<!-- https:///artifact/org.apache.poi/poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.5.7</version></dependency><!-- https:///artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><!-- https:///artifact/org.apache.poi/poi-ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency><!-- https:///artifact/org.apache.poi/poi-scratchpad --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency>⼀、读取word全部内容(这个不区分doc和docx)1package com.wordcom;23import java.io.File;4import java.io.FileInputStream;5import java.io.InputStream;6import org.apache.poi.POIXMLDocument;7import org.apache.poi.POIXMLTextExtractor;8import org.apache.poi.hwpf.extractor.WordExtractor;9import org.apache.poi.openxml4j.opc.OPCPackage;10import org.apache.poi.xwpf.extractor.XWPFWordExtractor;11/**12 * @Author:hp13 * @Description:14 * @Date:2021年11⽉4⽇14:58:1115 * @Modified by:读取word所有内容16 **/17public class DocUtil {18public static void main(String[] args) {19 String filePath = "C:\\Users\\hp\\Desktop\\新建⽂件夹 (2)\\忻州地调中⼼站11楼机房更换通信电源三措⼀案.docx";20 String content = readWord(filePath);21 System.out.println(content);22 }2324public static String readWord(String path) {25 String buffer = "";26try {27if (path.endsWith(".doc")) {28 InputStream is = new FileInputStream(new File(path));29 WordExtractor ex = new WordExtractor(is);30 buffer = ex.getText();31 ex.close();32 } else if (path.endsWith("docx")) {33 OPCPackage opcPackage = POIXMLDocument.openPackage(path);34 POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);35 buffer = extractor.getText();36 extractor.close();37 } else {38 System.out.println("此⽂件不是word⽂件!");39 }4041 } catch (Exception e) {42 e.printStackTrace();43 }4445return buffer;46 }47 }⼆、获取word各级标题(doc格式)这个需要保证word格式提前定义好标题格式才能读出来1package com.wordcom;2import org.apache.poi.hwpf.HWPFDocument;3import org.apache.poi.hwpf.model.StyleDescription;4import org.apache.poi.hwpf.model.StyleSheet;5import ermodel.Paragraph;6import ermodel.ParagraphProperties;7import ermodel.Range;8import java.io.*;910/**11 * @author hp12 *获取doc⽂档的标题13*/14public class WordTitle {15public static void main(String[] args) throws Exception {1617 String filePath = "C:\\Users\\hp\\Desktop\\新建⽂件夹 (2)\\正⽂查找.doc";18 printWord(filePath);1920 }21public static void printWord(String filePath) throws IOException {2223 InputStream is = new FileInputStream(filePath);2425 HWPFDocument doc = new HWPFDocument(is);2627 Range r = doc.getRange();// ⽂档范围2829for (int i = 0; i < r.numParagraphs(); i++) {3031 Paragraph p = r.getParagraph(i);// 获取段落32int numStyles = doc.getStyleSheet().numStyles();3334int styleIndex = p.getStyleIndex();3536if (numStyles > styleIndex) {3738 StyleSheet style_sheet = doc.getStyleSheet();3940 StyleDescription style = style_sheet.getStyleDescription(styleIndex);41 ParagraphProperties style1 = style_sheet.getParagraphStyle(styleIndex); 4243 String styleName = style.getName();// 获取每个段落样式名称44//System.out.println(style_sheet);45//System.out.println(styleName);46// 获取⾃⼰理想样式的段落⽂本信息47//String styleLoving = "标题";48 String text = p.text();// 段落⽂本49//if (styleName != null && styleName.contains(styleLoving)) {50if (styleName.equals("标题")) {5152 System.out.println(text);53 }54 }55 }56 doc.close();57 }58 }三、按段落读取word(doc)(docx)可以按照⾃⼰的需求提取特定的内容doc1package com.wordcom;2import org.apache.poi.hwpf.HWPFDocument;3import org.apache.poi.hwpf.model.StyleDescription;4import org.apache.poi.hwpf.model.StyleSheet;5import ermodel.Paragraph;6import ermodel.ParagraphProperties;7import ermodel.Range;8import java.io.*;910/**11 *12 * @author hp13 *获取doc⽂档的标题14*/15public class WordTitledoc {16public static void main(String[] args) throws Exception {1718 String filePath = "C:\\Users\\hp\\Desktop\\新建⽂件夹 (2)\\⼀案 .doc";1920 printWord(filePath);2122 }2324public static void printWord(String filePath) throws IOException {2526 InputStream is = new FileInputStream(filePath);2728 HWPFDocument doc = new HWPFDocument(is);2930 Range r = doc.getRange();// ⽂档范围3132for (int i = 0; i < r.numParagraphs(); i++) {3334 Paragraph p = r.getParagraph(i);// 获取段落35int numStyles = doc.getStyleSheet().numStyles();3637int styleIndex = p.getStyleIndex();3839if (numStyles > styleIndex) {4041 StyleSheet style_sheet = doc.getStyleSheet();4243 StyleDescription style = style_sheet.getStyleDescription(styleIndex);44 ParagraphProperties style1 = style_sheet.getParagraphStyle(styleIndex);4546 String styleName = style.getName();// 获取每个段落样式名称47//System.out.println(style_sheet);48//System.out.println(styleName);49// 获取⾃⼰理想样式的段落⽂本信息50//String styleLoving = "标题";51 String text = p.text();// 段落⽂本52//if (styleName != null && styleName.contains(styleLoving)) {53if (text.contains(".") || text.contains("、")) {54//String text = p.text();// 段落⽂本55if (!text.contains(",") && !text.contains(";") && !text.contains("。

Java Word中的文本、图片替换功能

Java Word中的文本、图片替换功能

Java Word中的文本、图片替换功能Word中的替换功能以查找指定文本然后替换为新的文本,可单个替换或全部替换。

以下将要介绍的内容,除常见的以文本替换文本外,还将介绍不同对象间相互替换的方法,具体可包括:1. 指定字符串内容替换文本(通过方法replce(matchString, newValue, caseSensitive, wholeWord );直接指定替换的新字符串内容)2. 获取文档内容替换文本(通过方法replace(String matchString, TextSelection textSelection, boolean caseSensitive, boolean wholeWord);替换指定文本)3. 图片替换文本4. 图片替换图片需要使用Free Spire.Doc for Java的jar包,可手动下载并解压导入Spire.Doc.jar文件到Java 程序,也可以通过maven仓库下载导入。

【示例1】指定字符串内容替换文本import com.spire.doc.*;public class ReplaceTextWithText {public static void main(String[] args) {//加载文档Document doc = new Document();doc.loadFromFile("test.docx");//要替换第一个出现的指定文本,只需在替换前调用setReplaceFirst方法来指定只替换第一个出现的指定文本//doc.setReplaceFirst(true);//调用方法用新文本替换原文本内容doc.replace("系统测试", "System Testing", false, true);//保存文档doc.saveToFile("ReplaceAllText.docx",FileFormat.Docx_2013);doc.dispose();}}【示例2】获取文档内容替换文本import com.spire.doc.*;import com.spire.doc.documents.TextSelection;public class ReplaceTextWithDocument {public static void main(String[] args) {//加载文档1Document doc1 = new Document();doc1.loadFromFile("test.docx");//加载文档2Document doc2 = new Document();doc2.loadFromFile("TargetFile.docx");//查找文档2中的指定内容TextSelection textSelection = doc2.findString("Falling under the scope of black box testing, " +"system testing is a phase in the software " +"testing cycle where a total and integrated" +" application /system is tested.",false,false);//用文档2中查找到的内容替换文档1中的指定字符串doc1.replace("System Test, ST",textSelection,false,true);//保存文档1doc1.saveToFile("ReplaceTextWithDocument.docx",FileFormat.Docx_2013);doc1.dispose();}}两个用于测试的文档如下,将文档2中的文本内容替换文档1中的指定文本内容:替换结果:【示例3】图片替换文本import com.spire.doc.*;import com.spire.doc.documents.TextSelection;import com.spire.doc.fields.DocPicture;import com.spire.doc.fields.TextRange;public class ReplaceTextWithImg {public static void main(String[] args) {//加载文档Document doc = new Document("test.docx");//查找需要替换的字符串TextSelection[] textSelection = doc.findAllString("系统测试",true,false);int index ;//加载图片替换文本字符串for (Object obj : textSelection) {TextSelection Selection = (TextSelection)obj;DocPicture pic = new DocPicture(doc);pic.loadImage("tp.png");TextRange range = Selection.getAsOneRange();index = range.getOwnerParagraph().getChildObjects().indexOf(range); range.getOwnerParagraph().getChildObjects().insert(index,pic);range.getOwnerParagraph().getChildObjects().remove(range);}//保存文档doc.saveToFile("ReplaceTextWithImage.docx", FileFormat.Docx_2013);doc.dispose();}}【示例4】图片替换图片import com.spire.doc.*;import com.spire.doc.documents.Paragraph;import com.spire.doc.fields.DocPicture;public class ReplacePictureWithPicture {public static void main(String[] args) {//加载Word文档Document doc = new Document();doc.loadFromFile("sample.docx");//获取文档中的指定段落Section section = doc.getSections().get(0);Paragraph para = section.getParagraphs().get(0);//替换段落中的第一张图片Object obj = para.getChildObjects().get(0);if(obj instanceof DocPicture){DocPicture pic = (DocPicture)obj;pic.loadImage("tp.png");}/*//批量替换图片for(int i =0;i < section.getParagraphs().getCount();i++){Object obj = section.getParagraphs().get(i).getChildObjects(); if(obj instanceof DocPicture){DocPicture pic = (DocPicture)obj;pic.loadImage("tp.png");}}*///保存结果文档doc.saveToFile("ReplaceWithImage.docx", FileFormat.Docx_2013);doc.dispose();}}(完)。

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

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中的字符串替换功能,将模板中的占位符替换为实际的数据。

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

JAVA操作wordJava操作Microsoft Word之jacob(1)现在我们一起来看看,用J1ava如何操作Microsoft Word。

官方的解释是:The JACOB Project: A JAva-COM Bridge这是官方对下载文件的说明:jacob.jar: a JAR file for the java classes which you must adjacob.dll: a small Win32 DLL which you must add to your PATH.samples: provided in Java source and compiled form to demonstrate various features of the product. In particular, a set of wrapper classes for Microsoft? ADO are provided as samples.开发环境:JDK 1.6MyEclipse Enterprise Workbench Version: 7.0 Milestone-1Tomcat现在MyEclipse中新建一个项目jacob,将jacob的jar包放到该项目的类库中。

我的jacob版本是1.14.3 。

下面这一步非常重要,就是拷贝jacob目录中jacob-1.14.3-x86.dll文件到系统环境变量目录中一般情况就放在当前jdk中bin目录下。

这里有一个MSWordManager 类,是jacob官方发布的工具类,里面有大多数Java操作MS Office的工具。

package com.test;import .Dispatch;public class MSWordManager {// word文档private Dispatch doc;// word运行程序对象private ActiveXComponent word;// 所有word文档集合private Dispatch documents;// 选定的范围或插入点private Dispatch selection;private boolean saveOnExit = true;/** *//**** @param visible 为true表示word应用程序可见*/public MSWordManager(boolean visible) {if (word == null) {word = newActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));}if (documents == null)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();}/** *//*** 打开一个已存在的文档* @param docPath*/public void openDocument(String docPath) {closeDocument();doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/** *//*** 把选定的内容或插入点向上移动** @param pos 移动的距离*/public void moveUp(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i &lt; pos; i++)Dispatch.call(selection,"MoveUp");}/** *//*** 把选定的内容或者插入点向下移动** @param pos 移动的距离*/public void moveDown(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i &lt; pos; i++)Dispatch.call(selection, "MoveDown");}/** *//*** 把选定的内容或者插入点向左移动** @param pos 移动的距离*/public void moveLeft(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i &lt; pos; i++) {Dispatch.call(selection, "MoveLeft");}}/** *//*** 把选定的内容或者插入点向右移动** @param pos 移动的距离*/public void moveRight(int pos) {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();for (int i = 0; i &lt; pos; i++)Dispatch.call(selection, "MoveRight");}/** *//*** 把插入点移动到文件首位置**/public void moveStart() {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();Dispatch.call(selection, "HomeKey", new Variant(6));}public void moveEnd() {if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();Dispatch.call(selection, "EndKey", newVariant(6));}/** *//*** 从选定内容或插入点开始查找文本** @param toFindText 要查找的文本* @return boolean true-查找到并选中该文本,false-未查找到文本*/public boolean find(String toFindText) {if (toFindText == null || toFindText.equals(""))return false;// 从selection所在位置开始查询Dispatch find = word.call(selection, "Find").toDispatch();// 设置要查找的内容Dispatch.put(find, "Text", toFindText);// 向前查找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 toFindText 查找字符串* @param newText 要替换的内容* @return*/public boolean replaceText(String toFindText, String newText) {if (!find(toFindText))return false;Dispatch.put(selection, "Text", newText);return true;}/** *//*** 全局替换文本** @param toFindText 查找字符串* @param newText 要替换的内容*/public void replaceAllText(String toFindText, String newText) {while (find(toFindText)) {Dispatch.put(selection, "Text", newText);Dispatch.call(selection, "MoveRight");}}/** *//*** 在当前插入点插入字符串** @param newText 要插入的新字符串*/public void insertText(String newText) {Dispatch.put(selection, "Text", newText);}/** *//**** @param toFindText 要查找的字符串* @param imagePath 图片路径* @return*/public boolean replaceImage(String toFindText, String imagePath) {if (!find(toFindText))return false;Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),"AddPicture", imagePath);return true;}/** *//*** 全局替换图片** @param toFindText 查找字符串* @param imagePath 图片路径*/public void replaceAllImage(String toFindText, String imagePath) {while (find(toFindText)) {Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);Dispatch.call(selection, "MoveRight");}}/** *//*** 在当前插入点插入图片** @param imagePath 图片路径*/public void insertImage(String imagePath) {Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),"AddPicture", imagePath);}/** *//*** 合并单元格** @param tableIndex* @param fstCellRowIdx* @param fstCellColIdx* @param secCellRowIdx* @param secCellColIdx*/public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,int secCellRowIdx, int secCellColIdx) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();Dispatch fstCell = Dispatch.call(table, "Cell",newVariant(fstCellRowIdx), new Variant(fstCellColIdx)).toDispatch();Dispatch secCell = Dispatch.call(table, "Cell",newVariant(secCellRowIdx), new Variant(secCellColIdx)).toDispatch();Dispatch.call(fstCell, "Merge", secCell);}/** *//*** 在指定的单元格里填写数据** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,String txt) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),newVariant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");Dispatch.put(selection, "Text", txt);}/** *//*** 在当前文档拷贝数据** @param pos*/public void copy(String toCopyText) {moveStart();if (this.find(toCopyText)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Copy");}}/** *//*** 在当前文档粘帖剪贴板数据** @param pos*/public void paste(String pos) {moveStart();if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}}/** *//*** 在当前文档指定的位置拷贝表格* @param pos 当前文档指定的位置* @param tableIndex 被拷贝的表格在word文档中所处的位置*/public void copyTable(String pos,int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();Dispatch range = Dispatch.get(table, "Range").toDispatch();Dispatch.call(range, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}}/** *//*** 在当前文档末尾拷贝来自另一个文档中的段落** @param anotherDocPath 另一个文档的磁盘路径* @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始)*/public void copyParagraphFromAnotherDoc(String anotherDocPath,int paragraphIndex) {Dispatch wordContent = Dispatch.get(doc, "Content").toDispatch(); // 取得当前文档的内容Dispatch.call(wordContent, "InsertAfter", "$selection$");// 插入特殊符定位插入点copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex,"$selection$");}/** *//*** 在当前文档指定的位置拷贝来自另一个文档中的段落** @param anotherDocPath 另一个文档的磁盘路径* @param tableIndex 被拷贝的段落在另一格文档中的序号(从1开始)* @param pos 当前文档指定的位置*/public void copyParagraphFromAnotherDoc(String anotherDocPath,int paragraphIndex, String pos) {Dispatch doc2 = null;try {doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();Dispatch paragraph =Dispatch.call(paragraphs, "Item",new Variant(paragraphIndex)).toDispatch();Dispatch range =Dispatch.get(paragraph, "Range").toDispatch();Dispatch.call(range, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}} catch (Exception e) {e.printStackTrace();} finally {if (doc2 != null) {Dispatch.call(doc2, "Close", new Variant(saveOnExit));doc2 = null;}}}/** *//*** 在当前文档指定的位置拷贝来自另一个文档中的表格** @param anotherDocPath 另一个文档的磁盘路径* @param tableIndex 被拷贝的表格在另一格文档中的序号(从1开始)* @param pos 当前文档指定的位置*/public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,String pos) {Dispatch doc2 = null;try {doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();Dispatch tables =Dispatch.get(doc2, "Tables").toDispatch();Dispatch table =Dispatch.call(tables, "Item",new Variant(tableIndex)).toDispatch();Dispatch range =Dispatch.get(table, "Range").toDispatch();Dispatch.call(range, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}} catch (Exception e) {e.printStackTrace();} finally {if (doc2 != null) { Dispatch.call(doc2, "Close", new Variant(saveOnExit));doc2 = null;}}}/** *//*** 在当前文档指定的位置拷贝来自另一个文档中的图片** @param anotherDocPath 另一个文档的磁盘路径* @param shapeIndex 被拷贝的图片在另一格文档中的位置* @param pos 当前文档指定的位置*/public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,String pos) {Dispatch doc2 = null;try {doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();Dispatch shapes =Dispatch.get(doc2, "InLineShapes").toDispatch();Dispatch shape =Dispatch.call(shapes, "Item",new Variant(shapeIndex)).toDispatch();Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();Dispatch.call(imageRange, "Copy");if (this.find(pos)) {Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();Dispatch.call(textRange, "Paste");}} catch (Exception e) {e.printStackTrace();} finally {if (doc2 != null) { Dispatch.call(doc2, "Close", new Variant(saveOnExit));doc2 = null;}}}Java操作Microsoft Word之jacob(2)(接上)/** *//*** 创建表格** @param pos 位置* @param cols 列数* @param rows 行数*/public void createTable(int numCols, int numRows){//(String pos, int numCols, int numRows) {// if (!find(pos)) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();Dispatch range =Dispatch.get(selection, "Range").toDispatch();Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(numRows), new Variant(numCols)).toDispatch();Dispatch.call(selection, "MoveRight");moveEnd();// }}/** *//*** 在指定行前面增加行** @param tableIndex word文件中的第N张表(从1开始)* @param rowIndex 指定行的序号(从1开始)*/public void addTableRow(int tableIndex, int rowIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex)).toDispatch ();Dispatch.call(rows, "Add", newVariant(row));}* 在第1行前增加一行** @param tableIndex word文档中的第N张表(从1开始)*/public void addFirstTableRow(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.get(rows, "First").toDispatch();Dispatch.call(rows, "Add", newVariant(row));}* 在最后1行前增加一行** @param tableIndex* word文档中的第N张表(从1开始)*/public void addLastTableRow(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.get(rows, "Last").toDispatch();Dispatch.call(rows, "Add", newVariant(row));}/** *//*** 增加一行** @param tableIndex word文档中的第N张表(从1开始)*/public void addRow(int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch.call(rows, "Add");}/** *//**** @param tableIndex word文档中的第N张表(从1开始)*/public void addCol(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch.call(cols, "Add").toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在指定列前面增加表格的列* @param tableIndex word文档中的第N张表(从1开始)* @param colIndex 指定列的序号 (从1开始)*/public void addTableCol(int tableIndex, int colIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex)).toDispatch ();// Dispatch col = Dispatch.get(cols, "First").toDispatch();col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在第1列前增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addFirstTableCol(int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.get(cols, "First").toDispatch();col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在最后一列前增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addLastTableCol(int tableIndex) {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch ();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.get(cols, "Last").toDispatch();col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 自动调整表格**/public void autoFitTable() {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();int count = Dispatch.get(tables, "Count").toInt();for (int i = 0; i &lt; count; i++) {Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)).toDispatch();Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 调用word里的宏以调整表格的宽度,其中宏保存在document下**/public void callWordMacro() {Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();int count = Dispatch.get(tables, "Count").toInt();Variant vParam = new Variant("param1");Variant para[] = new Variant[] { vMacroName };for (int i = 0; i &lt; para.length; i++) {Dispatch table =Dispatch.call(tables, "Item", new Variant(i + 1)).toDispatch();Dispatch.call(table, "Select");Dispatch.call(word, "Run", "tableFitContent");}/** *//*** 设置当前选定内容的字体** @param boldSize* @param italicSize* @param underLineSize 下划线* @param colorSize 字体颜色* @param size 字体大小* @param name 字体名称*/public void setFont(boolean bold, boolean italic, boolean underLine,String colorSize, String size, String name) {Dispatch font = Dispatch.get(selection, "Font").toDispatch();Dispatch.put(font, "Name", newVariant(name));Dispatch.put(font, "Bold", newVariant(bold));Dispatch.put(font, "Italic", newVariant(italic));Dispatch.put(font, "Underline", new Variant(underLine));Dispatch.put(font, "Color", colorSize);Dispatch.put(font, "Size", size);}/** *//*** 文件保存或另存为** @param savePath 保存或另存为路径*/public void save(String savePath) {Dispatch.call((Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);}/** *//*** 关闭当前word文档**/public void closeDocument() {if (doc != null) {Dispatch.call(doc, "Save");Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}/** *//*** 关闭全部应用**/public void close() {closeDocument();if (word != null) {Dispatch.call(word, "Quit");word = null;}selection = null;documents = null;}/** *//*** 打印当前word文档**/public void printFile() {if (doc != null) {Dispatch.call(doc, "PrintOut");}}public static void main(String args[])throws Exception {MSWordManager msWordManager = new MSWordManager(true);msWordManager.createNewDocument(); msWordManager.insertText("aaaaaaaaaaaaaaaaaaaaa");msWordManager.moveEnd();msWordManager.close();}}。

相关文档
最新文档