java操作word的表格

合集下载

Java 创建Word嵌套表格

Java 创建Word嵌套表格

Java 在Word中创建嵌套表格嵌套表格,即在一个大的表格单元格中再嵌进去一个或几个小的表格,使表格内容布局合理。

本文将通过java程序来演示如何在Word中创建嵌套表格。

使用工具:Free Spire.Doc for Java (免费版)Jar文件获取及导入:方法1:通过官网下载文件包。

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

方法2:通过maven仓库安装导入,可参考导入方法。

Java代码示例import com.spire.doc.*;import com.spire.doc.documents.*;import com.spire.doc.fields.TextRange;public class NestedTable {public static void main(String[]args){//加载测试文档Document doc = new Document("sample.docx");//获取指定表格中的单元格,并设置行高、列宽Section sec = doc.getSections().get(0);Table table = sec.getTables().get(0);table.getRows().get(0).setHeight(120f);table.getRows().get(0).getCells().get(0).setWidth(380);//添加嵌套表格到指定单元格Table nestedtable = table.get(0,0).addTable(true);nestedtable.getTableFormat().setHorizontalAlignment(RowAlignment.Center);//设置嵌套表格在单元格中的对齐方式nestedtable.resetCells(4,4);//指定嵌套表格行数、列数nestedtable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);//设置嵌套表格内容自适应方法//声明表格数组内容String[][] data ={new String[]{"编号","产区","最新型号","生产日期",},new String[]{"1","A","V2.2.0","2019-06-21"},new String[]{"2","B","V2.6.1","2019-06-18"},new String[]{"3","C","V2.6.2","2019-06-14"},};//填充数组内容到嵌套表格for (int i = 0; i < data.length; i++) {TableRow dataRow = nestedtable.getRows().get(i);dataRow.getCells().get(i).setWidth(160);dataRow.setHeight(25);dataRow.setHeightType(TableRowHeightType.Exactly);for (int j = 0; j < data[i].length; j++) {dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); TextRange range =dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);range.getCharacterFormat().setFontName("楷体");range.getCharacterFormat().setFontSize(11f);range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); }}//保存文档doc.saveToFile("nesedtable1.docx",FileFormat.Docx_2010);}}嵌套表格添加效果:(本文完)。

如何通过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如何将表格数据导入word文档中

Java如何将表格数据导入word文档中

Java如何将表格数据导⼊word⽂档中Java 表格数据导⼊word⽂档中个⼈觉得这个功能实在搞笑,没什么意义,没办法提了需求就要实现,(太好说话了把我)我的实现是再word中⽣成⼀个与 excel⾏,列⼀样的⼀个表格,然后把从excel拿到的数据(exList参数)依次放到word表格中public static void createFile(HttpServletResponse response, String fileName, List<List<String>> exList) {try {setResponseHeader(response, fileName);//⽣成⼀个word模版⽂件XWPFDocument document = new XWPFDocument();XWPFTable table = document.createTable(exList.size(), exList.get(0).size());XWPFTableRow row;for (int i = 0; i < exList.size(); i++) {List<String> sdf = exList.get(i);row = table.getRow(i);for (int j = 0; j < exList.get(i).size(); j++) {String s =sdf.get(j);row.getCell(j).setText(s);row.getCell(j).setWidthType(TableWidthType.AUTO);}//将数据插⼊表格中 pos:0 表⽰第⼀个表格document.setTable(0,table);}ServletOutputStream outputStream = response.getOutputStream();BufferedOutputStream bufferStream = new BufferedOutputStream(outputStream, 1024);document.write(bufferStream);document.close();bufferStream.close();;} catch (IOException e) {e.printStackTrace();}}public static void setResponseHeader(HttpServletResponse response, String name) {try {name = new String(name.getBytes(), "ISO8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setContentType("multipart/form-data");//要保存的⽂件名response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");}Java poi导⼊word表格数据的经过⼀、过程及遇到的问题和解决思路需要导⼊的是⼀个word⽂档,内容是以表格的形式保存在word中1、poi对word表格的空格处可以⾃动识别出来并赋值为 " ",这⼀点⽐poi导⼊excel⼈性化(excel默认是跳过这个空格)2、对于某些情况下,⾁眼⽆法看出表格格式问题,但是程序可以识别出来,怀疑是表格后期⼈⼯修改过,导致表格外观没问题但是⾏列属性不⼀致,导致读取时遇到这些地⽅报错,解决思路:可以在读取每⼀⾏之前先判断列数是否正确,poi中可以获取每⾏的列数,不正确的证明此列有问题,舍弃跳过。

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

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

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

word模板内容的替换和生成word表格(使用poi)

word模板内容的替换和生成word表格(使用poi)

word模板内容的替换和⽣成word表格(使⽤poi)1. maven 相关依赖和模板<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15-beta2</version></dependency><!-- https:///artifact/org.apache.poi/ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency>2. ⼯具类中的⽅法// 给⽣成的表格设置样式public static void setCellWitchAndAlign(XWPFTableCell cell,String width,STVerticalJc.Enum typeEnum,STJc.Enum align){CTTc cttc = cell.getCTTc();CTTcPr ctPr = cttc.addNewTcPr();ctPr.addNewVAlign().setVal(typeEnum);cttc.getPList().get(0).addNewPPr().addNewJc().setVal(align);CTTblWidth ctTblWidth = (ctPr != null && ctPr.isSetTcW() && ctPr.getTcW()!=null &&ctPr.getTcW().getW()!=null) ? ctPr.getTcW(): ctPr.addNewTcW();if(StringUtils.isNotBlank(width)){ctTblWidth.setW(new BigInteger(width));ctTblWidth.setType(STTblWidth.DXA);}}/*** ⽣成word⽂档下载*/public static void DownloadWord(HttpServletResponse response,List<DisUser> list, Map<String, Object> map,String file){XWPFDocument document = null;ServletOutputStream servletOS = null;ByteArrayOutputStream ostream = null;//添加表格try {servletOS = response.getOutputStream();ostream = new ByteArrayOutputStream();document = new XWPFDocument(POIXMLDocument.openPackage(file));// ⽣成word⽂档并读取模板/* ***********************⽐赛报名表基本信息******************************begin */Iterator<XWPFTable> it = document.getTablesIterator();//表格内容替换添加while(it.hasNext()){XWPFTable table = it.next();int rcount = table.getNumberOfRows();for(int i =0 ;i < rcount;i++){XWPFTableRow row = table.getRow(i);List<XWPFTableCell> cells = row.getTableCells();for (XWPFTableCell cell : cells){for(Entry<String, Object> e : map.entrySet()){if (cell.getText().equals(e.getKey())){//删除原来内容cell.removeParagraph(0);//写⼊新内容cell.setText((String) e.getValue());}}}}}//换⾏XWPFParagraph paragraph2 = document.createParagraph();XWPFRun paragraphRun2 = paragraph2.createRun();paragraphRun2.setText("\r");/* ***********************⽐赛报名表基本信息******************************end *///添加标题XWPFParagraph titleParagraph2 = document.createParagraph();//设置段落靠左titleParagraph2.setAlignment(ParagraphAlignment.LEFT);XWPFRun titleParagraphRun2 = titleParagraph2.createRun();titleParagraphRun2.setText("附:作品清单");titleParagraphRun2.setColor("000000");titleParagraphRun2.setFontSize(10);//附表格XWPFTable ComTable = document.createTable();//列宽⾃动分割/*CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();comTableWidth.setType(STTblWidth.DXA);comTableWidth.setW(BigInteger.valueOf(9072));*///表格第⼀⾏XWPFTableRow comTableRowOne = ComTable.getRow(0);// 表格标题内容的填充// 因为document.createTable() 创建表格后默认是⼀⾏⼀列,所以第⼀⾏第⼀列是直接comTableRowOne.getCell(0).setText("序号"); 赋值的。

[转载]Java给word中的table赋值

[转载]Java给word中的table赋值

[转载]Java给word中的table赋值⼀、准备⼯作:⼆、实现⽅法: 要调⽤PageOffice操作Word中的table,必须借助数据区域(DataRegion)实现的(原因是word中的表格只有index,没有name),要求数据区域完整的包含了整个Table的内容,这样才可以通过数据区域控制和操作table。

⽽table的插⼊,既可以在Word模版中书签处⼿动插⼊:⼯具栏“插⼊”→“表格”,亦可以在程序中通过数据区域动态添加。

1. 编辑word模板。

例如:word⽂档中有这样⼀个⼈员信息表,想要在这个⼈员信息表中填充数据,则必须先将整个成绩表的table插⼊到⼀个“书签”中:PO_regTable。

插⼊书签的时候⼀定要选择整个table。

2. 编写代码填充tablePageOfficeCtrl poCtrl1 = new PageOfficeCtrl(request);poCtrl1.setServerPage(request.getContextPath()+"/poserver.zz");//操作tableWordDocument doc = new WordDocument();DataRegion dataRegion = doc.openDataRegion("PO_regTable");//打开table,openTable(index)⽅法中的index代表当前书签中table位置的索引,从1开始Table table = dataRegion.openTable(1);//给table中的单元格赋值, openCellRC(int,int)中的参数分别代表第⼏⾏、第⼏列,从1开始table.openCellRC(3, 1).setValue("A公司");table.openCellRC(3, 2).setValue("开发部");table.openCellRC(3, 3).setValue("李清");//插⼊⼀⾏,insertRowAfter⽅法中的参数代表在哪个单元格下⾯插⼊⼀个空⾏table.insertRowAfter(table.openCellRC(3, 3));table.openCellRC(4, 1).setValue("B公司");table.openCellRC(4, 2).setValue("销售部");table.openCellRC(4, 3).setValue("张三");poCtrl1.setWriter(doc);//打开⽂件poCtrl1.webOpen("doc/test.doc", OpenModeType.docNormalEdit, "⽤户名"); 3. ⽣成⽂件的效果三、⽰例代码 参考Samples4中的:⼀、17、给Word⽂档中Table赋值的简单⽰例(WordSetTable)。

Java 设置Word表格自适应的3种情况

Java 设置Word表格自适应的3种情况

Java 设置Word中的表格自适应的3种方式概述在Word创建表格时,可设置表格“自动调整”,有3种情况,通过Java程序设置可调用相应的方法来实现,即:①. 根据内容调整表格AutoFitBehaviorType.Auto_Fit_To_Contents②. 根据窗口调整表格AutoFitBehaviorType.Auto_Fit_To_Window③. 固定列宽AutoFitBehaviorType.Fixed_Column_Widths程序中需要使用Word类库工具(Free Spire.Doc for Java 免费版)导入方法:方法1.可下载导入jar文件方法2.创建Maven程序在pom.xml配置Maven仓库路径并指定Free Spire.Doc for Java 的Maven依赖。

完成配置后,如果使用的是IDEA,点击“Import Changes”导入;如果使用的是Eclipse,点击“保存”即可自动下载导入。

<repositories><repository><id>com.e-iceblue</id><url>/repository/maven-public/</url></repository></repositories><dependencies><dependency><groupId> e-iceblue </groupId><artifactId>spire.doc.free</artifactId><version>2.7.3</version></dependency></dependencies>Java示例import com.spire.doc.*;public class TableAutoFit {public static void main(String[] args) {//加载Word文档Document doc = new Document();doc.loadFromFile("test.docx");//获取sectionSection section = doc.getSections().get(0);//获取表格Table table = section.getTables().get(0);//设置表格列宽适应内容table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);//设置表格列宽适应窗体//table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);//设置表格固定列宽//table.autoFit(AutoFitBehaviorType.Fixed_Column_Widths);//保存文档doc.saveToFile("TableAutoFit2.docx",FileFormat.Docx_2013); doc.dispose();}}设置效果:1.适应内容2.适应窗体3.固定列宽。

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,Excel,Ppt文档

Java实现在线预览Word,Excel,Ppt文档

Java实现在线预览Word,Excel,Ppt⽂档效果图:word:BufferedInputStream bis = null;URL url = null;HttpURLConnection httpUrl = null; // 建⽴链接url = new URL(urlReal);httpUrl = (HttpURLConnection) url.openConnection();// 连接指定的资源httpUrl.connect();// 获取⽹络输⼊流bis = new BufferedInputStream(httpUrl.getInputStream());String bodyText = null;WordExtractor ex = new WordExtractor(bis);bodyText = ex.getText();response.getWriter().write(bodyText);excel:BufferedInputStream bis = null;URL url = null;HttpURLConnection httpUrl = null; // 建⽴链接url = new URL(urlReal);httpUrl = (HttpURLConnection) url.openConnection();// 连接指定的资源httpUrl.connect();// 获取⽹络输⼊流bis = new BufferedInputStream(httpUrl.getInputStream());content = new StringBuffer();HSSFWorkbook workbook = new HSSFWorkbook(bis);for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得⼀个sheetcontent.append("/n");if (null == aSheet) {continue;}for (int rowNum = 0; rowNum <= aSheet.getLastRowNum(); rowNum++) {content.append("/n");HSSFRow aRow = aSheet.getRow(rowNum);if (null == aRow) {continue;}for (short cellNum = 0; cellNum <= aRow.getLastCellNum(); cellNum++) {HSSFCell aCell = aRow.getCell(cellNum);if (null == aCell) {continue;}if (aCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {content.append(aCell.getRichStringCellValue().getString());} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {boolean b = HSSFDateUtil.isCellDateFormatted(aCell);if (b) {Date date = aCell.getDateCellValue();SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");content.append(df.format(date));}}}}}response.getWriter().write(content.toString());ppt:BufferedInputStream bis = null;URL url = null;HttpURLConnection httpUrl = null; // 建⽴链接url = new URL(urlReal);httpUrl = (HttpURLConnection) url.openConnection();// 连接指定的资源httpUrl.connect();// 获取⽹络输⼊流bis = new BufferedInputStream(httpUrl.getInputStream());StringBuffer content = new StringBuffer("");SlideShow ss = new SlideShow(new HSLFSlideShow(bis));Slide[] slides = ss.getSlides();for (int i = 0; i < slides.length; i++) {TextRun[] t = slides[i].getTextRuns();for (int j = 0; j < t.length; j++) {content.append(t[j].getText());}content.append(slides[i].getTitle());}response.getWriter().write(content.toString());pdf:BufferedInputStream bis = null;URL url = null;HttpURLConnection httpUrl = null; // 建⽴链接url = new URL(urlReal);httpUrl = (HttpURLConnection) url.openConnection();// 连接指定的资源httpUrl.connect();// 获取⽹络输⼊流bis = new BufferedInputStream(httpUrl.getInputStream());PDDocument pdfdocument = null;PDFParser parser = new PDFParser(bis);parser.parse();pdfdocument = parser.getPDDocument();ByteArrayOutputStream out = new ByteArrayOutputStream();OutputStreamWriter writer = new OutputStreamWriter(out);PDFTextStripper stripper = new PDFTextStripper();stripper.writeText(pdfdocument.getDocument(), writer);writer.close();byte[] contents = out.toByteArray();String ts = new String(contents);response.getWriter().write(ts);txt:BufferedReader bis = null;URL url = null;HttpURLConnection httpUrl = null; // 建⽴链接url = new URL(urlReal);httpUrl = (HttpURLConnection) url.openConnection();// 连接指定的资源httpUrl.connect();// 获取⽹络输⼊流bis = new BufferedReader( new InputStreamReader(httpUrl.getInputStream())); StringBuffer buf=new StringBuffer();String temp;while ((temp = bis.readLine()) != null) {buf.append(temp);response.getWriter().write(temp);if(buf.length()>=1000){break;}}bis.close();。

Java操作word文档

Java操作word文档

Java操作Word文档操作微软word办公软件的开发工具:1.Apache基金会提供的POI2.通过freemarker去解析xml3.Java2word4.iText5.Jacob通过对以上工具的对比,本人发现还是Itext比较简单易用,很容易上手,能够很轻松的处理word的样式、表格等。

贴上代码,供大家参考:Jar包准备:itext-2.0.1.jar -------------------核心包iTextAsian.jar--------------------解决word样式、编码问题扩展包1、设置标题样式public static Paragraph setParagraphTitle(String content,Font contentFont){Paragraph p = new Paragraph(content, contentFont);p.setAlignment(Table.ALIGN_CENTER);p.setIndentationLeft(60);p.setIndentationRight(60);p.setSpacingBefore(20);return p;}2、设置内容样式:public static Paragraph setParagraphStyle(String content,Font contentFont){Paragraph p = new Paragraph(content, contentFont);p.setFirstLineIndent(40);// 首行缩进p.setAlignment(Paragraph.ALIGN_JUSTIFIED);// 对齐方式p.setLeading(30);// 行间距p.setIndentationLeft(60);// 左边距,右边距p.setIndentationRight(60);return p;}3、设置文档末尾时间:public static Paragraph setParagraphTime(Font contentFont){ Paragraph p = new Paragraph(FormatUtil.getCurrentDate(), contentFont);p.setIndentationLeft(250);p.setIndentationRight(60);p.setLeading(30);p.setFirstLineIndent(40);return p;}4、开始写word文档咯:public static void WriteDoc(String path,Map<String,String> map){Document document = null;try {File file = new File(path);if (!file.exists()) {file.createNewFile();}document = new Document(PageSize.A4);RtfWriter2.getInstance(document, newFileOutputStream(file));document.open();// 设置title body 中文字体及样式BaseFont cnFont =BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font titleFont = new Font(cnFont,22, Font.NORMAL, newColor(0,0, 0));Font contentFont = new Font(cnFont, 16, Font.NORMAL, new Color(0,0, 0));// 设置文本标题String titleInfo = “标题”;// 设置文本内容String contentFirst ="啊啊啊啊啊啊啊啊啊啊";String contentSecond="啊啊啊啊啊啊啊啊啊啊啊啊";String contentThird="啊啊啊啊啊啊啊啊啊啊啊啊啊";String contentFourth="啊啊啊啊啊啊啊啊啊啊";document.add(setParagraphTitle(titleInfo,titleFont));document.add(setParagraphStyle(contentFirst,contentFont));document.add(setParagraphStyle(contentSecond,contentFont));document.add(setParagraphStyle(contentThird,contentFont));document.add(setParagraphStyle(contentFourth,contentFont));document.add(setParagraphTime(contentFont));} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {if (document != null) {document.close();}} catch (Exception e2) {e2.printStackTrace();}}}5、上传下载大家就自个动手了。

Java使用POI读取Word中的表格

Java使用POI读取Word中的表格

Java使⽤POI读取Word中的表格代码package live.autu.word;import java.io.FileInputStream;import org.apache.poi.hwpf.HWPFDocument;import ermodel.Paragraph;import ermodel.Range;import ermodel.Table;import ermodel.TableCell;import ermodel.TableIterator;import ermodel.TableRow;import org.apache.poi.poifs.filesystem.POIFSFileSystem;/*** Hello world!**/public class App {public static void main(String[] args) {//doc⽂档路径String filePath = "C:\\Users\\autu\\Desktop\\test.doc";//test.print(filePath,"第⼀个表");System.out.println(App.read(filePath,"第⼀个表"));;}/*** 读取⽂档中表格* @param filePath doc路径* @param set 第⼏个表格*/public static String read(String filePath,String tableName) {StringBuilder sb=new StringBuilder();try (FileInputStream in = new FileInputStream(filePath); // 载⼊⽂档POIFSFileSystem pfs = new POIFSFileSystem(in);HWPFDocument hwpf = new HWPFDocument(pfs);) {Range range = hwpf.getRange();// 得到⽂档的读取范围TableIterator it = new TableIterator(range);// 迭代⽂档中的表格while (it.hasNext()) {Table tb = (Table) it.next();// 迭代⾏,默认从0开始,可以依据需要设置i的值,改变起始⾏数,也可设置读取到那⾏,只需修改循环的判断条件即可outer:for (int i = 0; i < tb.numRows(); i++) {TableRow tr = tb.getRow(i);// 迭代列,默认从0开始for (int j = 0; j < tr.numCells(); j++) {TableCell td = tr.getCell(j);// 取得单元格// 取得单元格的内容for (int k = 0; k < td.numParagraphs(); k++) {Paragraph para = td.getParagraph(k);String s = para.text();// 去除后⾯的特殊符号if (null != s && !"".equals(s)) {s = s.substring(0, s.length() - 1);}s=s.trim();if(tableName.trim().equals(s)||i!=0) {sb.append(s + "\t");} else {break outer;}}}sb.append( "\n");}}} catch (Exception e) {e.printStackTrace();}return sb.toString();}}依赖<dependency><groupId>org.apache.poi</groupId> <artifactId>poi</artifactId><version>4.0.1</version></dependency><dependency><groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.0.1</version></dependency>效果图test.doc控制台打印。

xwpfdocument操作表格

xwpfdocument操作表格

xwpfdocument是Apache POI中用于操作Word文档的类,它提供了一些方法来操作Word文档中的表格。

在本文中,将介绍如何使用xwpfdocument来操作表格,包括插入表格、删除表格、修改表格内容等操作。

一、插入表格在Word文档中插入表格,可以使用xwpfdocument类的createTable方法。

该方法接受两个参数,分别表示表格的行数和列数。

下面的代码将在Word文档中插入一个3行4列的表格:```javaXWPFDocument doc = new XWPFDocument();XWPFTable table = doc.createTable(3, 4);```二、删除表格如果希望在Word文档中删除特定的表格,可以使用xwpfdocument 类的removeTable方法。

该方法接受一个参数,表示要删除的表格的索引。

表格的索引从0开始计数。

下面的代码将删除第二个表格:```javadoc.removeTable(1);```三、修改表格内容操作Word文档中的表格时,通常需要修改表格中的内容。

可以通过xwpftablerow和xwpfparagraph类来实现。

下面的代码将修改表格第二行第三列的内容:```javaXWPFTable table = doc.getTableArray(0);XWPFTableRow row = table.getRow(1);XWPFTableCell cell = row.getCell(2);cell.setText("新内容");```四、保存文档完成对表格的操作后,需要将修改后的文档保存到文件中。

可以使用xwpfdocument类的write方法实现。

下面的代码将文档保存为“output.docx”:```javaFileOutputStream out = new FileOutputStream("output.docx"); doc.write(out);out.close();```总结本文介绍了如何使用xwpfdocument类来操作Word文档中的表格,包括插入表格、删除表格、修改表格内容等操作。

POIXWPF操作word并操作表格

POIXWPF操作word并操作表格

POIXWPF操作word并操作表格POIXWPF是一种用于操作Microsoft Word文档的Java库。

它提供了丰富的API,方便开发人员对Word文档进行创建、读取、修改和保存等操作。

本文将介绍如何使用POIXWPF来操作Word文档以及表格的相关操作。

一、创建Word文档在使用POIXWPF创建Word文档之前,首先需要添加POIXWPF 的依赖。

在项目中引入相关的jar包后,我们可以使用以下代码来创建一个新的Word文档:```java// 创建一个新的文档XWPFDocument document = new XWPFDocument();// 创建段落XWPFParagraph paragraph = document.createParagraph();// 在段落中添加文本XWPFRun run = paragraph.createRun();run.setText("这是一个POIXWPF创建的Word文档");// 保存文档FileOutputStream out = newFileOutputStream("path/to/document.docx");document.write(out);out.close();```以上代码首先创建了一个新的`XWPFDocument`对象,然后创建了一个段落`XWPFParagraph`,并在段落中添加了文本内容。

最后,通过`FileOutputStream`将文档保存到指定的路径下。

二、操作表格POIXWPF还提供了丰富的API来操作Word文档中的表格。

下面的示例代码演示了如何使用POIXWPF来创建一个简单的表格并填充内容:```java// 创建一个新的文档XWPFDocument document = new XWPFDocument();// 创建表格XWPFTable table = document.createTable(3, 3);// 设置表格样式CTTblPr tablePr = table.getCTTbl().getTblPr();CTTblBorders borders = tablePr.addNewTblBorders();borders.addNewTop().setVal(STBorder.SINGLE);borders.addNewBottom().setVal(STBorder.SINGLE);borders.addNewLeft().setVal(STBorder.SINGLE);borders.addNewRight().setVal(STBorder.SINGLE);// 填充表格内容for (int row = 0; row < 3; row++) {for (int col = 0; col < 3; col++) {XWPFTableCell cell = table.getRow(row).getCell(col);cell.setText("第" + (row + 1) + "行" + "第" + (col + 1) + "列");}}// 保存文档FileOutputStream out = newFileOutputStream("path/to/document.docx");document.write(out);out.close();```以上代码创建了一个3行3列的表格,并在每个单元格中填充了内容。

Java 在Word中添加多级项目符号列表和编号列表

Java 在Word中添加多级项目符号列表和编号列表

Java 在Word中创建多级项目符号列表和编号列表本文分享通过Java程序代码在Word中创建多级项目符号列表和编号列表的方法。

程序运行环境如下:IntelliJ IDEA 2018(JDK 1.8.0)Word 2013Word Jar包:Free Spire.Doc for Java关于如何导入jar包:在Java程序中导入jar包。

如下方式为下载jar包到本地后,解压,手动将本地该jar包lib 文件夹下的Spire.doc.jar导入java程序的方法jar包导入结果如图:完成jar导入后,在程序中键入如下Java代码:import com.spire.doc.*;import com.spire.doc.documents.*;public class MultiLevelList {public static void main(String[] args) {//创建一个Document类的实例Document document = new Document();//添加SectionSection sec = document.addSection();//添加段落Paragraph paragraph = sec.addParagraph();paragraph.appendText("Lists");paragraph.applyStyle(BuiltinStyle.Title);paragraph = sec.addParagraph();paragraph.appendText("Numbered List:").getCharacterFormat().setBold(true);//创建编号列表样式ListStyle numberList = new ListStyle(document, ListType.Numbered);//编号列表numberList.setName("numberList");numberList.getLevels().get(1).setNumberPrefix("\u0000.");numberList.getLevels().get(1).setPatternType(ListPatternType.Arabic);numberList.getLevels().get(2).setNumberPrefix("\u0000.\u0001.");numberList.getLevels().get(2).setPatternType(ListPatternType.Arabic);//创建符号列表样式ListStyle bulletList= new ListStyle(document, ListType.Bulleted);//符号列表bulletList.setName("bulletList");//添加列表样式document.getListStyles().add(numberList);document.getListStyles().add(bulletList);//添加段落并应用列表样式paragraph = sec.addParagraph();paragraph.appendText("List Item 1");paragraph.getListFormat().applyStyle(numberList.getName());paragraph = sec.addParagraph();paragraph.appendText("List Item 2");paragraph.getListFormat().applyStyle(numberList.getName());paragraph = sec.addParagraph();paragraph.appendText("List Item 2.1");paragraph.getListFormat().applyStyle(numberList.getName());paragraph.getListFormat().setListLevelNumber(1);paragraph = sec.addParagraph();paragraph.appendText("List Item 2.2");paragraph.getListFormat().applyStyle(numberList.getName());paragraph.getListFormat().setListLevelNumber(1);paragraph = sec.addParagraph();paragraph.appendText("List Item 2.2.1");paragraph.getListFormat().applyStyle(numberList.getName());paragraph.getListFormat().setListLevelNumber(2);paragraph = sec.addParagraph();paragraph.appendText("List Item 2.2.2");paragraph.getListFormat().applyStyle(numberList.getName());paragraph.getListFormat().setListLevelNumber(2);paragraph = sec.addParagraph();paragraph.appendText("List Item 2.2.3");paragraph.getListFormat().applyStyle(numberList.getName());paragraph.getListFormat().setListLevelNumber(2);paragraph = sec.addParagraph();paragraph.appendText("List Item 2.3");paragraph.getListFormat().applyStyle(numberList.getName());paragraph.getListFormat().setListLevelNumber(1);paragraph = sec.addParagraph();paragraph.appendText("List Item 3");paragraph.getListFormat().applyStyle(numberList.getName());paragraph = sec.addParagraph();paragraph.appendText("Bulleted List:").getCharacterFormat().setBold(true);paragraph = sec.addParagraph();paragraph.appendText("List Item 1");paragraph.getListFormat().applyStyle(bulletList.getName());paragraph = sec.addParagraph();paragraph.appendText("List Item 2");paragraph.getListFormat().applyStyle(bulletList.getName());paragraph = sec.addParagraph();paragraph.appendText("List Item 2.1");paragraph.getListFormat().applyStyle(bulletList.getName());paragraph.getListFormat().setListLevelNumber(1);paragraph = sec.addParagraph();paragraph.appendText("List Item 2.2");paragraph.getListFormat().applyStyle(bulletList.getName());paragraph.getListFormat().setListLevelNumber(1);paragraph = sec.addParagraph();paragraph.appendText("List Item 3");paragraph.getListFormat().applyStyle(bulletList.getName());//保存文档document.saveToFile("MultiLevelList.docx", FileFormat.Docx);document.dispose();}}执行程序,生成Word结果文档。

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

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

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

Java 提取、删除Word文本框中的表格

Java 提取、删除Word文本框中的表格

Java 获取、删除Word文本框中的表格本文介绍如何来获取Word文本框中包含的表格,以及删除表格。

程序测试环境包括:IDEAJDK 1.8.0Spire.Doc.jar注:jar导入,可通过创建Maven程序项目,并在pom.xml中配置Maven仓库路径,并指定Free Spire.Doc for Java的Maven依赖,点击“Import Changes”即可导入JAR包。

(如果使用的Eclipse,点击保存按钮导入),配置如下:<repositories><repository><id>com.e-iceblue</id><url>/repository/maven-public/</url></repository></repositories><dependencies><dependency><groupId>e-iceblue</groupId><artifactId>spire.doc.free</artifactId><version>2.7.3</version></dependency></dependencies>导入效果:另外,也可通过下载jar包,手动导入Spire.Doc.jar到Java程序。

Word测试文档如下,包含一个表格:Java代码1. 获取Word文本框中的表格import com.spire.doc.*;import com.spire.doc.documents.Paragraph;import com.spire.doc.fields.TextBox;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;public class ExtractTable {public static void main(String[]args) throws IOException { //加载Word测试文档Document doc = new Document();doc.loadFromFile("test.docx");//获取第一个文本框TextBox textbox = doc.getTextBoxes().get(0);//获取文本框中第一个表格Table table = textbox.getBody().getTables().get(0);//保存文本String output = "EtractTableFromTextbox.txt";File file = new File(output);if (!file.exists()) {file.delete();}file.createNewFile();FileWriter fw = new FileWriter(file, true);BufferedWriter bw = new BufferedWriter(fw);//遍历表格中的段落并提取文本for (int i = 0; i < table.getRows().getCount(); i++) {TableRow row = table.getRows().get(i);for (int j = 0; j < row.getCells().getCount(); j++) {TableCell cell = row.getCells().get(j);for (int k = 0; k < cell.getParagraphs().getCount(); k++) { Paragraph paragraph = cell.getParagraphs().get(k);bw.write(paragraph.getText() + "\t");}}bw.write("\r\n");}bw.flush();bw.close();fw.close();}}表格内容获取结果:2. 删除Word文本框中的表格import com.spire.doc.*;import com.spire.doc.fields.TextBox;public class DeleteTableInTextbox {public static void main(String[] args) {//加载Word测试文档Document doc = new Document();doc.loadFromFile("test.docx");//获取第一个文本框TextBox textbox = doc.getTextBoxes().get(0);//获取文本框中第一个表格textbox.getBody().getTables().get(0);//删除第一个表格textbox.getBody().getTables().removeAt(0);//保存文档doc.saveToFile("DeleteTableInTextbox.docx", FileFormat.Docx_2013); doc.dispose();}}表格删除结果:。

javapoi实现word导出(包括word模板的使用、复制表格、复制行、插入图片的使用)

javapoi实现word导出(包括word模板的使用、复制表格、复制行、插入图片的使用)
1 2 3 4 5 6 7 8 9 10 11 12 13 4.导出的工具类 /** * 功能描述:word工具类 * * @author jynn *ห้องสมุดไป่ตู้@created 2019年8月15日 * @version 1.0.0 */ public class WordUtil {
/** * 功能描述:word下载 * * @param response * @param patientMap * @param list * @param itemList * @param file * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static final void DownloadWord(HttpServletResponse response, Map<String, Object> patientMap, List<Map<String, Object>> list, List<List<String>> itemList, String file) {
博客园 用户登录 代码改变世界 密码登录 短信登录 忘记登录用户名 忘记密码 记住我 登录 第三方登录/注册 没有账户, 立即注册
javapoi实现 word导出(包括 word模板的使用、复制表格、复制 行、插入图片的使用)
java poi实现数据的word导出(包括word模板的使用、复制表格、复制行、插入图片的使用) 1.实现的效果 实现病人基本信息、多条病历数据、多项检查项图片的动态插入(网络图片)
/** * 功能描述:复制段落,从source到target * * @param target * @param source * @param index * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static void copyParagraph(XWPFParagraph target, XWPFParagraph source, Integer index) { // 设置段落样式 target.getCTP().setPPr(source.getCTP().getPPr()); // 移除所有的run for (int pos = target.getRuns().size() - 1; pos >= 0; pos--) { target.removeRun(pos); } // copy 新的run for (XWPFRun s : source.getRuns()) { XWPFRun targetrun = target.createRun(); copyRun(targetrun, s, index); } }

JAVA读取WORD文档解决方案

JAVA读取WORD文档解决方案

JAVA读取WORD文档解决方案在Java中,可以使用Apache POI库来读取和操作Word文档。

Apache POI库提供了一组Java API,用于读取、写入和操作Microsoft Office格式的文件,包括Word文档。

以下是使用Apache POI库来读取Word文档的解决方案:1. 添加依赖:首先,需要在项目中添加Apache POI库的依赖。

可以在maven或gradle构建文件中添加以下依赖:```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>```2. 创建文档对象:使用POIXMLDocument类来创建一个XWPFDocument对象,它代表Word文档。

```javaFile file = new File("path/to/word/document.docx");XWPFDocument document = new XWPFDocument(new FileInputStream(file));```3.读取文档内容:通过遍历文档中的段落和表格来读取文档的内容。

```java//遍历段落List<XWPFParagraph> paragraphs = document.getParagraphs(;for (XWPFParagraph paragraph : paragraphs)String text = paragraph.getText(;System.out.println(text);//遍历表格List<XWPFTable> tables = document.getTables(;for (XWPFTable table : tables)List<XWPFTableRow> rows = table.getRows(;for (XWPFTableRow row : rows)List<XWPFTableCell> cells = row.getTableCells(;for (XWPFTableCell cell : cells)String text = cell.getText(;System.out.println(text);}}```4. 关闭文档:在读取完成后,需要关闭XWPFDocument对象来释放资源。

javaPOI往word文档中指定位置插入表格

javaPOI往word文档中指定位置插入表格

javaPOI往word⽂档中指定位置插⼊表格1.Service demoimport java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.math.BigInteger;import java.text.DecimalFormat;import java.text.NumberFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.poi.POIXMLDocument;import org.apache.poi.util.IOUtils;import ermodel.XWPFDocument;import ermodel.XWPFParagraph;import ermodel.XWPFRun;import ermodel.XWPFTable;import ermodel.XWPFTableCell;import ermodel.XWPFTableRow;import org.apache.xmlbeans.XmlCursor;import org.docx4j.TraversalUtil;import org.docx4j.dml.wordprocessingDrawing.Inline;import org.docx4j.finders.RangeFinder;import org.docx4j.openpackaging.packages.WordprocessingMLPackage;import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;import org.docx4j.wml.Body;import org.docx4j.wml.CTBookmark;import org.docx4j.wml.Document;import org.docx4j.wml.Drawing;import org.docx4j.wml.ObjectFactory;import org.docx4j.wml.P;import org.docx4j.wml.R;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import bels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot;import org.jfree.data.general.DefaultPieDataset;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;import org.springframework.stereotype.Service;import mon.collect.Lists;import mon.collect.Maps;public class ExportBgServiceImpl {private static final String bookmark = "tpBookmark";// 报告图⽚位置的书签名public void exportBg(OutputStream out) {String srcPath = "D:/tp/fx.docx";String targetPath = "D:/tp/fx2.docx";String key = "$key";// 在⽂档中需要替换插⼊表格的位置XWPFDocument doc = null;File targetFile = null;try {doc = new XWPFDocument(POIXMLDocument.openPackage(srcPath));List<XWPFParagraph> paragraphList = doc.getParagraphs();if (paragraphList != null && paragraphList.size() > 0) {for (XWPFParagraph paragraph : paragraphList) {List<XWPFRun> runs = paragraph.getRuns();for (int i = 0; i < runs.size(); i++) {String text = runs.get(i).getText(0).trim();if (text != null) {if (text.indexOf(key) >= 0) {runs.get(i).setText(text.replace(key, ""), 0);XmlCursor cursor = paragraph.getCTP().newCursor();// 在指定游标位置插⼊表格XWPFTable table = doc.insertNewTbl(cursor);CTTblPr tablePr = table.getCTTbl().getTblPr();CTTblWidth width = tablePr.addNewTblW();width.setW(BigInteger.valueOf(8500));this.inserInfo(table);break;}}}}}doc.write(out);out.flush();out.close();} catch (Exception e) {throw new SysException(MON_SYSTEM_ERROR, e);}}/*** 把信息插⼊表格* @param table* @param data*/private void inserInfo(XWPFTable table) {List<DTO> data = mapper.getInfo();//需要插⼊的数据XWPFTableRow row = table.getRow(0);XWPFTableCell cell = null;for (int col = 1; col < 6; col++) {//默认会创建⼀列,即从第2列开始// 第⼀⾏创建了多少列,后续增加的⾏⾃动增加列CTTcPr cPr =row.createCell().getCTTc().addNewTcPr();CTTblWidth width = cPr.addNewTcW();if(col==1||col==2||col==4){width.setW(BigInteger.valueOf(2000));}}row.getCell(0).setText("指标");row.getCell(1).setText("指标说明");row.getCell(2).setText("公式");row.getCell(3).setText("参考值");row.getCell(4).setText("说明");row.getCell(5).setText("计算值");for(DTO item : data){row = table.createRow();row.getCell(0).setText(item.getZbmc());cell = row.getCell(1);cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));cell.setText(item.getZbsm());cell = row.getCell(2);cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));cell.setText(item.getJsgs());if(item.getCkz()!=null&&!item.getCkz().contains("$")){row.getCell(3).setText(item.getCkz());}cell = row.getCell(4);cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));cell.setText(item.getSm());row.getCell(5).setText(item.getJsjg()==null?"⽆法计算":item.getJsjg());}}}2.Controllerpublic void exportBg(HttpServletResponse response) {try {response.setContentType("application/octet-stream");String name = "报告";response.addHeader("Content-Disposition", "attachment;filename="+new String(name.getBytes(),"iso-8859-1") +".docx"); OutputStream out = response.getOutputStream();export.exportBg(out,sblsh);} catch (Exception e) {}}3.maven<dependency><groupId>org.apache.poi</groupId><artifactId>poi-excelant</artifactId><version>3.12</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.12</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.8</version></dependency><!-- ⽣成图⽚--><dependency><groupId>org.jfree</groupId><artifactId>jfreechart</artifactId><version>1.0.19</version></dependency><dependency><!--⽀持插⼊图⽚--><groupId>org.docx4j</groupId><artifactId>docx4j</artifactId><version>3.3.1</version></dependency>在⽂档中指定位置设置好关键字如 demo 中的 “$key”结果图如下:。

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

java操作word的表格最近项目中需要把提交的页面表单的数据动态写在word模板中,简单的写了个工具类。

里面有怎眼操作word 中表格的内容,可以在word中已有的表格后面添加行并且可以增加内容。

/*** @title WordBean.java* @package com.sinosoft.bjppb_print.utils.word* @description文件描述* @author lijf* @update 2012-7-26 下午04:17:10* @version V1.0*/package com.sinosoft.bjppb_print.utils.word;import java.util.Map;import com.jacob.activeX.ActiveXComponent;import .Dispatch;import .Variant;public class WordBean {// word文档static Dispatch doc;// word运行程序对象private ActiveXComponent word;// 所有word文档集合private Dispatch documents;// 选定的范围或插入点private Dispatch selection;private boolean saveOnExit = true;public WordBean() throws Exception {if (word == null) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(false)); // 不可见打开wordword.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏}if (documents == null)documents = word.getProperty("Documents").toDispatch();}* 重载,制定文档用户名称,主要用于痕迹保留时候显示对应的用户* @param username* @throws Exception*/public WordBean(String username) throws Exception {if (word == null) {word = new ActiveXComponent("Word.Application");word.setProperty("UserName", new Variant(username));word.setProperty("Visible", new Variant(true)); // 不可见打开word word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏}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();Dispatch.put(doc, "TrackRevisions", new Variant(true));Dispatch.put(doc, "PrintRevisions", new Variant(true));Dispatch.put(doc, "ShowRevisions", new Variant(false));selection = Dispatch.get(word, "Selection").toDispatch();}/**** 只读打开一个保护文档,* @param docPath-文件全名 ** @param pwd-密码**/public void openDocumentOnlyRead(String docPath, String pwd)throws Exception {closeDocument();doc = Dispatch.callN(documents, "Open", new Object[] { docPath, new Variant(false),new Variant(true), new Variant(true), pwd, "",new Variant(false) }).toDispatch(); selection = Dispatch.get(word, "Selection").toDispatch();}public void openDocument(String docPath, String pwd) throws Exception {closeDocument();doc = Dispatch.callN(documents,"Open",new Object[] { docPath, new Variant(false), new Variant(false),new Variant(true), pwd }).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** * 把选定的内容或者插入点向右移动 * *** @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));}/*** * 从选定内容或插入点开始查找文本 * *** @param toFindText ** 要查找的文本 ** @return boolean true-查找到并选中该文本,false-未查找到文本**/@SuppressWarnings("static-access")public boolean find(String toFindText) {Dispatch selection = Dispatch.get(word, "Selection").toDispatch(); // 输入内容需要的对象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();}/**246. * * 把选定选定内容设定为替换文本 * *247. *248. * @param toFindText *249. * 查找字符串 *250. * @param newText *251. * 要替换的内容 *252. * @return253. *254. */public boolean replaceText(String toFindText, String newText,Dispatch selection) {if (!find(toFindText))return false;Dispatch.put(selection, "Text", newText);return true;}/**269. * * 全局替换文本 * *270. *271. * @param toFindText *272. * 查找字符串 *273. * @param newText *274. * 要替换的内容275. *276. */public void replaceAllText(String toFindText, String newText) {while (find(toFindText)) {Dispatch selection = Dispatch.get(word, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", newText);Dispatch.call(selection, "MoveRight");}}/**** @param tableIndex* @param cellRowIdx* @param cellColIdx* @return* @author lijf* @description获取表格的某个单元格内容* @update 2012-7-27 下午04:22:15*/public String getTxtFromCell(int tableIndex, int cellRowIdx, int cellColIdx) { // 所有表格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),new Variant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");String ret = "";ret = Dispatch.get(selection, "Text").toString();ret = ret.substring(0, ret.length() - 1); // 去掉最后的回车符;return ret;}/*** @author lijf* @description关闭打开的word* @update 2012-7-27 下午04:21:10*/public void closeDocument() {if (doc != null) {// Dispatch.call(doc, "ShowRevisions", new Variant(saveOnExit));Dispatch.call(doc, "Save");Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}/*** 增加一行** @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" ).toDispatch();System.out.println("添加一行");}/**** @param tableIndex 第N个表格* @return* @author lijf* @description获取第N个表格的总行数* @update 2012-7-27 下午04:05:47*/public int getRowCount(int tableIndex){int count=0;Dispatch tables = Dispatch.get(doc, "Tables" ).toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item" , newVariant(tableIndex)).toDispatch();Dispatch rows = Dispatch.get(table, "Rows" ).toDispatch();count=Dispatch.get(rows, "Count").getInt();return count;}/**** @param tableIndex 第N个表格* @param cell 一行的单元格数量* @param object 填充内容的对象* @author lijf* @description向第N个表格中添加一行数据* @update 2012-7-27 下午03:25:45*/public void addRowData(int tableIndex,int cell ,Object object,String[] strs){ addRow(tableIndex);//添加一行int rowIndex=getRowCount(tableIndex);Dispatch tables = Dispatch.get(doc, "Tables" ).toDispatch();// 要填充的表格Dispatch table = Dispatch.call(tables, "Item" , newVariant(tableIndex)).toDispatch();//为当前行添加内容for(int i=1;i<=cell;i++){putTxtToCell(table,rowIndex,i,strs[i-1]);}}// 打开一个存在的word文档,并用document 引用引用它public void openFile(String wordFilePath) {Dispatch documents = Dispatch.get(word, "Documents").toDispatch();doc = Dispatch.call(documents, "Open", wordFilePath,new Variant(true)/* 是否进行转换ConfirmConversions */,new Variant(false)/* 是否只读 */).toDispatch();}/**** @param tableTitle* @param row* @param column* @author lijf* @description创建一个table* @update 2012-7-27 下午03:07:53*/public void insertTable(String tableTitle, int row, int column) {Dispatch selection = Dispatch.get(word, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.call(selection, "TypeText", tableTitle); // 写入标题内容 // 标题格行Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "TypeParagraph"); // 空一行段落Dispatch.call(selection, "MoveDown"); // 游标往下一行// 建立表格Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();// int count = Dispatch.get(tables,// "Count").changeType(Variant.VariantInt).getInt(); // document中的表格数量// Dispatch table = Dispatch.call(tables, "Item", new Variant(// 1)).toDispatch();//文档中第一个表格Dispatch range = Dispatch.get(selection, "Range").toDispatch();// /当前光标位置或者选中的区域Dispatch newTable = Dispatch.call(tables, "Add", range,new Variant(row), new Variant(column), new Variant(1)).toDispatch(); // 设置row,column,表格外框宽度Dispatch cols = Dispatch.get(newTable, "Columns").toDispatch(); // 此表的所有列,int colCount = Dispatch.get(cols,"Count").getInt();//.changeType(Variant.VariantInt).getInt();// 一共有多少列实际上这个数==column System.out.println(colCount + "列");for (int i = 1; i <= colCount; i++) { // 循环取出每一列Dispatch col = Dispatch.call(cols, "Item", new Variant(i)).toDispatch();Dispatch cells = Dispatch.get(col, "Cells").toDispatch();// 当前列中单元格int cellCount = Dispatch.get(cells, "Count").getInt();// 当前列中单元格数实际上这个数等于rowfor (int j = 1; j <= cellCount; j++) {// 每一列中的单元格数// Dispatch cell = Dispatch.call(cells, "Item", new// Variant(j)).toDispatch(); //当前单元格// Dispatch cell = Dispatch.call(newTable, "Cell", new// Variant(j) , new Variant(i) ).toDispatch(); //取单元格的另一种方法// Dispatch.call(cell, "Select");//选中当前单元格// Dispatch.put(selection, "Text",// "第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值putTxtToCell(newTable, j, i, "第" + j + "行,第" + i + "列");// 与上面四句的作用相同 }}}/*** 在指定的单元格里填写数据** @param tableIndex* @param cellRowIdx* @param cellColIdx* @param txt*/public void putTxtToCell(Dispatch table, int cellRowIdx, int cellColIdx,String txt) {Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),new Variant(cellColIdx)).toDispatch();Dispatch.call(cell, "Select");Dispatch selection = Dispatch.get(word, "Selection").toDispatch(); // 输入内容需要的对象Dispatch.put(selection, "Text", txt);}public static void main(String[] args) {try {WordBean wordutil=new WordBean();//wordutil.openDocumentOnlyRead("c:/a.docx", "123");//wordutil.openDocument("c:/a.docx");wordutil.openFile("d:/b.docx");/*Dispatch selection = Dispatch.get(wordutil.word, "Selection").toDispatch(); // 输入内容需要的对象wordutil.replaceText("453", "2",selection); wordutil.replaceText("44", "e",selection); wordutil.replaceText("ee", "1",selection);*/ //wordutil.addRow(6);String[] strs={"1","2","中华","2","3","3"}; wordutil.addRowData(6, 6, null, strs);//wordutil.replaceAllText("1234", " 你好");//wordutil.createTable();//wordutil.putTxtToCell(6,2,1,"sss");//wordutil.copyRow(6, 2);wordutil.closeDocument();} catch (Exception e) {e.printStackTrace();}}。

相关文档
最新文档