java操作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;}。
aspose.wordsforjava操作文档doc,设置一级二级三级标题以及段落表格等详情

aspose.wordsforjava操作⽂档doc,设置⼀级⼆级三级标题以及段落表格等详情实现将aspose.words的相关组件jar包以下是我⾃⼰编辑整理的⼯具类,欢迎交流package com;import java.io.InputStream;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.aspose.words.CellMerge;import com.aspose.words.CellVerticalAlignment;import com.aspose.words.Document;import com.aspose.words.DocumentBuilder;import com.aspose.words.FontSettings;import com.aspose.words.HeightRule;import com.aspose.words.License;import com.aspose.words.LineStyle;import com.aspose.words.ParagraphAlignment;import com.aspose.words.SaveFormat;import com.aspose.words.Table;/**** @ClassName:AsposeUtils* @Description: aspose.words操作⽂档⼯具类* @Date:2019年1⽉11⽇**/public class AsposeUtils {private static final Logger LOGGER = LoggerFactory.getLogger(AsposeUtils.class);private static boolean AsposeLicense = false;static{try {//license.xmlInputStream is = AsposeUtils.class.getClassLoader().getResourceAsStream("license.xml");new License().setLicense(is);AsposeLicense = true;} catch (Exception e) {e.printStackTrace();}}/*** 验证License* @return boolean*/private static void getLicense() {if (!AsposeLicense) { // 验证License 若不验证则转化出的pdf⽂档会有⽔印产⽣("**********验证失败,会产⽣⽔印***********");}("************验证成功,已去除默认⽔印***********");}/*** 保存pdf* @param path保存⽬录* @param doc原⽂档*/public static void savePdf(String path,Document doc){String format = "pdf";save(path,doc,SaveFormat.PDF,format);}/*** 保存doc* @param path保存⽬录* @param doc原⽂档*/public static void saveDoc(String path,Document doc){String format = "doc";save(path,doc,SaveFormat.DOC,format);}public static void saveDocx(String path,Document doc){String format = "docx";save(path,doc,SaveFormat.DOCX,format);}/*** 保存各种格式的⽂档* @param path保存地址* @param doc保存⽂件* @param saveFormat保存格式*/private static void save(String path,Document doc,int saveFormat,String format){getLicense();try {String os = System.getProperty("");if(os.toLowerCase().indexOf("linux") >= 0){("************当前使⽤*****linux**"+ os +"*********");//设置⼀个字体⽬录FontSettings.getDefaultInstance().setFontsFolder("/usr/share/fonts/", false);}doc.save(path, saveFormat);} catch (Exception e) {("************保存⽂档(格式为"+format+")出现异常***********");e.printStackTrace();}}/*** 制作报表总标题* @param builder* @param title*/public static void setTitle(DocumentBuilder builder,String title){try {//设置字体格式builder.insertHtml("<p style='text-align:center'><font face='宋体' size='30' color='black'>"+ title +"</font></p>"); } catch (Exception e) {("************制作标题"+title+"出现异常***********");e.printStackTrace();}}/*** 制作⼀级标题* @param builder* @param title*/private static void setTitle1(DocumentBuilder builder,String title1){try {builder.insertHtml("<h1 style='text-align:left;font-family:Simsun;'>"+ title1 +"</h1>");} catch (Exception e) {("************制作⼀级标题"+title1+"出现异常***********");e.printStackTrace();}}/*** 制作⼆级标题* @param builder* @param title*/private static void setTitle2(DocumentBuilder builder,String title2){try {builder.insertHtml("<h2 style='text-align:left;font-family:Simsun;'>"+ title2 +"</h2>");} catch (Exception e) {("************制作⼆级标题"+title2+"出现异常***********");e.printStackTrace();}}/*** 制作三级标题* @param builder* @param title*/private static void setTitle3(DocumentBuilder builder,String title3){try {builder.insertHtml("<h3 style='text-align:left;font-family:Simsun;'>"+ title3 +"</h3>");} catch (Exception e) {("************制作三级标题"+title3+"出现异常***********");e.printStackTrace();}}/*** 区别各级标题* @param builder* @param title* @param level*/public static void setTitleS(DocumentBuilder builder,String title,String level){switch (level) {case "1":setTitle1(builder, title);break;case "2":setTitle2(builder, title);break;case "3":setTitle3(builder, title);break;default:break;}}/*** 制作报表段落* @param builder* @param pragraph*/public static void setParagraph(DocumentBuilder builder,String pragraph){try {//设置字体格式builder.insertHtml("<p><font face='宋体'> "+ pragraph +"</font></p>"); } catch (Exception e) {("************制作段落"+pragraph+"出现异常***********");e.printStackTrace();}}/*** 制作⼀个单元格并追加数据,单元格不合并* @param builder* @param width 设置单元格宽度* @param text*/public static void setCell(DocumentBuilder builder,Double width,String text){builder.insertCell();if(width==null) width = 3d;builder.getCellFormat().setWidth(width);builder.getCellFormat().setVerticalMerge(CellMerge.NONE);builder.write(text);}/*** 插⼊单元格,不设置宽度,单元格不合并* @param builder* @param text*/public static void setCell(DocumentBuilder builder,String text){builder.insertCell();builder.getCellFormat().setVerticalMerge(CellMerge.NONE);builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);builder.write(text);}public static void setCell(DocumentBuilder builder,Long text){builder.insertCell();builder.getCellFormat().setVerticalMerge(CellMerge.NONE);builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);if(text == null){builder.write("");}else{builder.write(text.toString());}}public static void setCell(DocumentBuilder builder,Double text){builder.insertCell();builder.getCellFormat().setVerticalMerge(CellMerge.NONE);builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);if(text == null){builder.write("");}else{builder.write(text.toString());}}/*** 垂直合并单元格的第⼀格* @param builder* @param text*/public static void setStartVerticalMerge(DocumentBuilder builder,String text){builder.insertCell();builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);builder.write(text);}/*** 垂直合并单元格的后⾯格* @param builder* @param text*/public static void setThenVerticalMerge(DocumentBuilder builder){builder.insertCell();// This cell is vertically merged to the cell above and should be empty.builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); }/*** ⽔平合并单元格的第⼀格* @param builder* @param text*/public static void setStartHorizontalMerge(DocumentBuilder builder,String text){ builder.insertCell();builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);builder.write(text);}/*** ⽔平合并单元格的后⾯格* @param builder* @param text*/public static void setThenHorizontalMerge(DocumentBuilder builder){builder.insertCell();// This cell is vertically merged to the cell above and should be empty.builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);}/*** 制作表格数据⾏* @param builder*/public static void setRow(DocumentBuilder builder){try {builder.getRowFormat().setHeadingFormat(true);builder.getRowFormat().getBorders().setLineStyle(LineStyle.SINGLE);builder.getRowFormat().setHeightRule(HeightRule.AUTO);builder.getRowFormat().setAllowBreakAcrossPages(true);} catch (Exception e) {("************制作表格数据⾏出现异常***********");e.printStackTrace();}}/*** 制作表格* @param builder* @throws Exception*/public static Table setTable(DocumentBuilder builder){builder.moveToDocumentEnd();Table table = builder.startTable();builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);return table;}}。
jacob操作word(转载)

jacob操作word自从有了JACOB后,事情变得简单多了。
但是要实现Java灵活的控制Word还是一件非常麻烦的事情。
下面介绍几个WORD常见的对象以及一些典型的处理过程,希望对大家有帮助。
(请注意:JDK1.3.2运行 Jacob比较正常,JDK1.4有问题)private ActiveXComponent word = null;private Dispatch documents = null;private Dispatch vSelection = null;private Dispatch wordfile = null;1,初始化word = new ActiveXComponent("Word.Application");documents = word.getProperty("Documents").toDispatch();(将JACOB 放在 WINNT\system32\ 下比较简单省事)2,打开文件wordfile = Dispatch.invoke(documents,"Open",Dispatch.Method,new Object[] {strFileName,new Variant(true),//是否进行转换 ConfirmConversionsnew Variant(false)//是否只读}, new int[1]).toDispatch();vSelection = word.getProperty("Selection").toDispatch();在WORD中,选定内容进行转换时,不用象Java对象一样来回的重新取,这个对象一直有效。
在WORD中3,显示WORDword.setProperty("Visible", new Variant(visible));4,设置WORD的位置Dispatch activeWindow = Dispatch.get(word, "Application").toDispatch();Dispatch.put(activeWindow, "WindowState", new Variant(0));Dispatch.put(activeWindow, "Top", new Variant(0));Dispatch.put(activeWindow, "Left", new Variant(0));Dispatch.put(activeWindow, "Height", new Variant(600));Dispatch.put(activeWindow, "width", new Variant(800));进行将JAVA内的数据和WORD交换,常用的做法是,在WORD上作一些特殊的标记,利用 FIND 和 Replace的方法进行,这个方法不是太好。
Java解析word文档

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文件是一种常见的操作,可以通过读取并修改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文档在线预览,读取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文本样式(字体、字号、颜色、背景、行距等)

Java 读取Word文本/段落格式属性本文介绍通过Java后端程序代码来读取Word文本和段落格式的方法。
本次测试环境如下:●Word版本:2013●编译环境:IntelliJ IDEA2018●Work库:free spire.doc.jar 3.9.0●JDK版本:1.8.0通过textrange.getCharacterFormat()方法读取文本字符串格式,通过paragraph.getFormat()读取段落格式,读取具体文字及段落属性时,可支持读取字体、字号、文字颜色、文字背景、文字是否加粗或倾斜、文字下划线、大小写、边框、上标下标、行距、段落缩进、对齐方式、段落边框、背景等等,下表中罗列了所有可支持读取的样式属性,供参考:读取文本格式getCharacterFormat():读取段落格式:getFormat()用于测试的Word文档:Java示例代码import com.spire.doc.*;import com.spire.doc.documents.Paragraph;import com.spire.doc.documents.TextSelection;import com.spire.doc.fields.TextRange;import java.awt.*;public class GetTextFormat {public static void main(String[] args) {//加载Word源文档Document doc = new Document();doc.loadFromFile("test.docx");//获取段落数量int count = doc.getSections().get(0).getParagraphs().getCount();System.out.println("总共含有段落数:" + count);//查找指定文本TextSelection textSelections = doc.findString("东野圭吾", false, true);//获取字体名称String fontname =textSelections.getAsOneRange().getCharacterFormat().getFontName();//获取字体大小float fontsize =textSelections.getAsOneRange().getCharacterFormat().getFontSize();System.out.println("字体名称:" + fontname +"\n"+"字体大小:"+fontsize);//获取第二段Paragraph paragraph2 = doc.getSections().get(0).getParagraphs().get(1);//获取段落行距float linespage = paragraph2.getFormat().getLineSpacing();System.out.println("段落行距:" + linespage);//遍历段落中的子对象for (int z = 0; z < paragraph2.getChildObjects().getCount(); z++){Object obj2 = paragraph2.getChildObjects().get(z);//判定是否为文本if (obj2 instanceof TextRange){TextRange textRange2 = (TextRange) obj2;//获取文本颜色Color textcolor = textRange2.getCharacterFormat().getTextColor();if (!(textcolor.getRGB() == 0)){System.out.println("文本颜色:" + textRange2.getText() + textcolor.toString());}//获取字体加粗效果boolean isbold = textRange2.getCharacterFormat().getBold();if (isbold == true){System.out.println("加粗文本:" + textRange2.getText());}//获取字体倾斜效果boolean isitalic = textRange2.getCharacterFormat().getItalic();if (isitalic == true){System.out.println("倾斜文本:" + textRange2.getText());}//获取文本背景String text = textRange2.getText();Color highlightcolor =textRange2.getCharacterFormat().getHighlightColor();//获取文本的高亮颜色(即突出显示颜色)if (!(highlightcolor.getRGB() == 0 )){System.out.println("文本高亮:" + text +highlightcolor.toString());//输出高亮的文本和颜色}Color textbackgroundcolor =textRange2.getCharacterFormat().getTextBackgroundColor();//获取文字背景(底纹)if (!(textbackgroundcolor.getRGB()==0)){System.out.println("文本背景:" + text + textbackgroundcolor.toString());//输出有背景的文本和颜色}}}}}运行程序,输入获取结果:。
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 ⽂档,只是没有页眉和页脚。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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 的工具。
package com.test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;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", newVariant(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 < 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 < 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 < 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 < 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", new Variant(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", newVariant(tableIndex)).toDispatch();Dispatch fstCell = Dispatch.call(table, "Cell",new Variant(fstCellRowIdx), new Variant(fstCellColIdx)).toDispatch();Dispatch secCell = Dispatch.call(table, "Cell",new Variant(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", newVariant(tableIndex)).toDispatch();Dispatch cell = Dispatch.call(table, "Cell", newVariant(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", newVariant(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, intshapeIndex,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 createT able(int numCols, int numRows){//(String pos, int numCols, int numRows) {// if (!find(pos)) {Dispatch tables = Dispatch.get(doc,"T ables").toDispatch();Dispatch range = Dispatch.get(selection, "Range").toDispatch();Dispatch newT able = 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 addT ableRow(int tableIndex, int rowIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "T ables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", newVariant(tableIndex)).toDispatch();// 表格的所有行Dispatch rows = Dispatch.get(table, "Rows").toDispatch();Dispatch row = Dispatch.call(rows, "Item", newVariant(rowIndex)).toDispatch();Dispatch.call(rows, "Add", new Variant(row));}/** *//*** 在第1行前增加一行** @param tableIndex word文档中的第N张表(从1开始)*/public void addFirstTableRow(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "T ables").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", new Variant(row));}/** *//*** 在最后1行前增加一行** @param tableIndex* word文档中的第N张表(从1开始)*/public void addLastTableRow(int tableIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "T ables").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", new Variant(row));}/** *//*** 增加一行** @param tableIndex word文档中的第N张表(从1开始)*/public void addRow(int tableIndex) {Dispatch tables = Dispatch.get(doc, "T ables").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, "T ables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", newVariant(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 addT ableCol(int tableIndex, int colIndex) {// 所有表格Dispatch tables = Dispatch.get(doc, "T ables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", newVariant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();System.out.println(Dispatch.get(cols, "Count"));Dispatch col = Dispatch.call(cols, "Item", newVariant(colIndex)).toDispatch();// Dispatch col = Dispatch.get(cols, "First").toDispatch();Dispatch.call(cols, "Add", col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在第1列前增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addFirstTableCol(int tableIndex) {Dispatch tables = Dispatch.get(doc, "T ables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", newVariant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.get(cols, "First").toDispatch();Dispatch.call(cols, "Add", col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 在最后一列前增加一列** @param tableIndex word文档中的第N张表(从1开始)*/public void addLastTableCol(int tableIndex) {Dispatch tables = Dispatch.get(doc, "T ables").toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item", newVariant(tableIndex)).toDispatch();// 表格的所有行Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch col = Dispatch.get(cols, "Last").toDispatch();Dispatch.call(cols, "Add", col).toDispatch();Dispatch.call(cols, "AutoFit");}/** *//*** 自动调整表格**/public void autoFitTable() {Dispatch tables = Dispatch.get(doc, "T ables").toDispatch();int count = Dispatch.get(tables, "Count").toInt();for (int i = 0; i < count; i++) {Dispatch table = Dispatch.call(tables,"Item", new Variant(i + 1)).toDispat ch();Dispatch cols = Dispatch.get(table, "Columns").toDispatch();Dispatch.call(cols, "AutoFit");}}/** *//*** 调用word里的宏以调整表格的宽度,其中宏保存在document下**/public void callWordMacro() {Dispatch tables = Dispatch.get(doc, "T ables").toDispatch();int count = Dispatch.get(tables, "Count").toInt();Variant vMacroName = newVariant("Normal.NewMacros.tableFit");Variant vParam = new Variant("param1");Variant para[] = new Variant[] { vMacroName };for (int i = 0; i < para.length; i++) {Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1)).toDispat ch();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", new Variant(name));Dispatch.put(font, "Bold", new Variant(bold));Dispatch.put(font, "Italic", new Variant(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();}}。