JAVA使用POI读取PPT文件和POI读取EXCEL WORD示例

合集下载

java使用POI读取excel数据

java使用POI读取excel数据

java使⽤POI读取excel数据⼀、定义 Apache POI是Apache软件基⾦会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

⼆、所需jar包:三、简单的⼀个读取excel的demo1、读取⽂件⽅法/*** 读取出filePath中的所有数据信息* @param filePath excel⽂件的绝对路径**/public static void getDataFromExcel(String filePath){//String filePath = "E:\\123.xlsx";//判断是否为excel类型⽂件if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx")){System.out.println("⽂件不是excel类型");}FileInputStream fis =null;Workbook wookbook = null;try{//获取⼀个绝对地址的流fis = new FileInputStream(filePath);}catch(Exception e){e.printStackTrace();}try{//2003版本的excel,⽤.xls结尾wookbook = new HSSFWorkbook(fis);//得到⼯作簿}catch (Exception ex){//ex.printStackTrace();try{//2007版本的excel,⽤.xlsx结尾wookbook = new XSSFWorkbook(fis);//得到⼯作簿} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}//得到⼀个⼯作表Sheet sheet = wookbook.getSheetAt(0);//获得表头Row rowHead = sheet.getRow(0);//判断表头是否正确if(rowHead.getPhysicalNumberOfCells() != 3){System.out.println("表头的数量不对!");}//获得数据的总⾏数int totalRowNum = sheet.getLastRowNum();//要获得属性String name = "";int latitude = 0;//获得所有数据for(int i = 1 ; i <= totalRowNum ; i++){//获得第i⾏对象Row row = sheet.getRow(i);//获得获得第i⾏第0列的 String类型对象Cell cell = row.getCell((short)0);name = cell.getStringCellValue().toString();//获得⼀个数字类型的数据cell = row.getCell((short)1);latitude = (int) cell.getNumericCellValue();System.out.println("名字:"+name+",经纬度:"+latitude); }}2、测试public static void main(String[] args){getDataFromExcel("E:"+ File.separator +"123.xlsx");}3、原始数据4、结果名字:A1,经纬度:1名字:A2,经纬度:2名字:A3,经纬度:3名字:A4,经纬度:4名字:A5,经纬度:5名字:A6,经纬度:6名字:A7,经纬度:7名字:A8,经纬度:8名字:A9,经纬度:9名字:A10,经纬度:10名字:A11,经纬度:11。

poi教程

poi教程

poi教程Poi教程概述:Poi是一款Java库,用于处理Microsoft Office格式文件,如Excel、Word和PowerPoint。

它提供了丰富的API,使开发人员能够读取、写入和修改这些文件。

Poi教程内容:1. 安装Poi库:首先,你需要下载并安装Poi库。

你可以从Apache的官方网站上找到最新版本的Poi库。

安装过程包括将Poi库添加到你的Java项目的构建路径中。

2. 创建Excel文档:使用Poi,你可以创建一个新的Excel文档。

你可以定义工作表、行和单元格,并在单元格中添加数据。

你还可以设置单元格的格式,如字体、颜色和边框。

3. 读取Excel文件:Poi可以读取现有的Excel文件。

你可以打开一个文件并读取工作表、行和单元格中的数据。

你还可以根据需要筛选和处理数据。

4. 写入Excel文件:除了读取数据,Poi还可以将数据写入现有的Excel文件。

你可以创建新的工作表、行和单元格,并在其中插入数据。

你可以使用Poi的API来设置单元格的格式和其他属性。

5. 处理Word和PowerPoint文件:除了处理Excel文件,Poi还可以读取和写入Word和PowerPoint文件。

你可以打开Word文档并访问其中的段落、表格和其他元素。

你还可以修改PowerPoint演示文稿中的幻灯片、文本和图像。

6. 添加图表和图像:Poi提供了创建和修改图表的功能。

你可以使用Poi的API创建各种类型的图表,并在其中添加数据。

此外,你还可以在Excel文件中添加图像,并设置其大小、位置和其他属性。

7. 导出数据:一旦你完成了对Excel、Word或PowerPoint文件的处理,你可以使用Poi将其导出为其他格式,如PDF或HTML。

这使得你可以轻松地共享和打印处理过的文件。

8. 错误处理和异常处理:在使用Poi时,可能会遇到各种错误和异常。

你需要学会如何正确处理这些错误,以确保你的代码能够顺利运行。

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-实现-利用POI读取word文档实例

JAVA-实现-利用POI读取word文档实例

JAVA-实现-利⽤POI读取word⽂档实例package read.document;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.util.ArrayList;import java.util.List;import org.apache.poi.hwpf.HWPFDocument;import ermodel.CharacterRun;import ermodel.Range;import pers.mysql.DBUtil;import pers.mysql.MysqlDao;import pers.mysql.MysqlDaoImp;public class WordReading {public static void main(String[] args) {String filePath = "*****.doc";readOnWord(filePath);}public static void readOnWord(String filePath) {if (filePath.endsWith(".doc")) {// 输⼊流-基类InputStream is = null;try {is = new FileInputStream(filePath);} catch (FileNotFoundException e) {e.printStackTrace();System.out.println("⽂件打开失败。

");}// 加载doc⽂档try {HWPFDocument doc = new HWPFDocument(is);Range text = doc.getRange();// 整个⽂档/** 分解word:⽂本 ->⼩节 ->段落 ->characterRun(理解为⼩单元)* section -⼩节; paragraph - 段落*///1分出内容节点Range hotWord = text.getSection(2);// 0-封⾯,1-⽬录,2-⽂本;第3⼩节//2段落处理/** 维护两个变量** 热词和解释区别:⼤⼩-word:26,explaining:18**/String word = "";String explaining = "";int wordOK = 0;int explainOK = 0;// 判断当前word&explain是否可以填⼊数据库int count = 24;// 读取⼏条数据到数据库int begin = 2;// 段落读取位置for (int i = 0; i < count;) {Range para = hotWord.getParagraph(begin);CharacterRun field = para.getCharacterRun(0);int fontSize = field.getFontSize();if (fontSize == 26) {word = para.text();wordOK = 1;begin++;} else {while (fontSize < 26) {explaining += para.text();begin++;para = hotWord.getParagraph(begin); field = para.getCharacterRun(0);fontSize = field.getFontSize();}explainOK = 1;}// 判断word&explain是否可以填⼊数据库if (wordOK == 1 && explainOK == 1) {MysqlDaoImp.addData(word, explaining); i++;//填⼊数据库后,⼀切归"0"wordOK = 0;explainOK = 0;word="";explaining="";}}// 输出测试// System.out.println("读取:" + "head:");} catch (IOException e) {e.printStackTrace();System.out.println("IO错误。

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

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

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

java使用poi读取ppt文件和poi读取excel、word示例

java使用poi读取ppt文件和poi读取excel、word示例

java使用poi读取ppt文件和poi读取excel、word示例Apache的POI项目可以用来处理MS Office文档,codeplex上还有一个它的.net版本。

POI项目可创建和维护操作各种基于OOXML和OLE2文件格式的Java API。

大多数MS Office都是OLE2格式的。

POI通HSMF子项目来支持Outlook,通过HDGF子项目来支持Visio,通过HPBF子项目来支持Publisher。

使用POI抽取Word简单示例:要引入poi-3.7.jat和poi-scratchpad-3.7.ajr这两个包。

复制代码代码如下:packagemsoffice;importjava.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;importorg.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.extractor.WordExtractor;import ermodel.CharacterRun;import ermodel.Paragraph;import ermodel.Range;import ermodel.Section;public class Word {// 直接抽取全部内容public static String readDoc1(InputStream is) throws IOException {WordExtractor extractor = new WordExtractor(is);return extractor.getText();}//分章节Section、段落Paragraph、字符串CharacterRun抽取 public static void readDoc2(InputStream is) throws IOException { HWPFDocument doc=new HWPFDocument(is);Range r=doc.getRange();for(int x=0;x<r.numSections();x++){Section s=r.getSection(x);for(int y=0;y<s.numParagraphs();y++){Paragraph p=s.getParagraph(y);for(int z=0;z<p.numCharacterRuns();z++){CharacterRun run=p.getCharacterRun(z);String text=run.text();System.out.print(text);}}}}public static void main(String[] args) {File file = new File("/home/orisun/1.doc");try {FileInputStream fin = new FileInputStream(file);String cont = readDoc1(fin);System.out.println(cont);fin.close();fin = new FileInputStream(file);readDoc2(fin);fin.close();} catch (IOException e) {e.printStackTrace();}}}POI抽取PPT示例:复制代码代码如下:packagemsoffice;importjava.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;importorg.apache.poi.hslf.HSLFSlideShow;import org.apache.poi.hslf.extractor.PowerPointExtractor;import org.apache.poi.hslf.model.Slide;import org.apache.poi.hslf.model.TextRun;import ermodel.SlideShow;public class PPT {//直接抽取幻灯片的全部内容public static String readDoc1(InputStream is) throws IOException{ PowerPointExtractor extractor=new PowerPointExtractor(is);return extractor.getText();}//一张幻灯片一张幻灯片地读取public static void readDoc2(InputStream is) throws IOException{ SlideShowss=new SlideShow(new HSLFSlideShow(is));Slide[] slides=ss.getSlides();for(inti=0;i<slides.length;i++){//读取一张幻灯片的标题String title=slides[i].getTitle();System.out.println("标题:"+title);//读取一张幻灯片的内容(包括标题)TextRun[] runs=slides[i].getTextRuns();for(int j=0;j<runs.length;j++){System.out.println(runs[j].getText());}}}public static void main(String[] args){File file = new File("/home/orisun/2.ppt");try{FileInputStream fin=new FileInputStream(file);String cont=readDoc1(fin);System.out.println(cont);fin.close();fin=new FileInputStream(file);readDoc2(fin);fin.close();}catch(IOException e){e.printStackTrace();}}}Excel文件由多个Workbook组成,一个Workbook由多个Sheet组成。

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">请上传要处理的⽂件,过程可能需要⼏分钟,请稍候⽚刻。

poi数据使用

poi数据使用

poi数据使用POI(Apache POI)是一个用于操作Microsoft Office格式文件(如doc、xls、ppt等)的Java API。

它提供了一组类和方法,使开发人员可以轻松地读取、写入和操作Office文档中的数据。

本文将介绍如何使用POI来处理poi数据。

二、POI数据读取1. 导入POI库首先,我们需要在项目中导入POI库。

可以下载POI的jar文件,然后将其添加到项目的classpath中。

2. 创建工作簿和工作表使用POI来读取poi数据之前,我们需要创建一个工作簿和一个工作表对象。

可以使用HSSFWorkbook和HSSFSheet类来分别代表工作簿和工作表。

3. 读取数据使用POI的API方法,我们可以逐行或逐列读取poi数据。

可以使用HSSFRow和HSSFCell类来分别代表行和单元格。

通过遍历行和列的方式,可以获取到相应的数据。

三、POI数据写入1. 创建工作簿和工作表与数据读取类似,我们首先需要创建一个工作簿和一个工作表对象。

可以使用HSSFWorkbook和HSSFSheet类来分别代表工作簿和工作表。

2. 写入数据使用POI的API方法,我们可以将数据写入到指定的单元格中。

可以使用HSSFRow和HSSFCell类来分别代表行和单元格。

可以通过设置单元格的值来进行数据的写入操作。

四、POI数据操作注意事项1. 数据格式转换在进行POI数据读取或写入操作时,需要注意数据的格式转换。

例如,将数字类型的数据转换为字符串,或将字符串类型的数据转换为日期类型。

2. 数据校验在写入数据之前,我们需要进行数据校验,确保所写入的数据符合需求。

例如,对于字符串类型的数据,可以进行长度、格式等校验。

3. 数据样式设置为了使POIpoi数据的呈现更加美观,我们可以设置数据的样式。

可以使用HSSFCellStyle类来设置单元格的字体、背景色、边框等样式。

本文介绍了如何使用POI对poi数据进行读取和写入操作。

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

} }
POI 抽取 PPT 示例:
复制代码 代码如下:
package msoffice;
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream;
public static void main(String[] args){ File file = new File("/home/orisun/3.xls"); try{ FileInputStream fin=new FileInputStream(file); String cont=readDoc1(fin); System.out.println(cont); fin.close(); fin=new FileInputStream(file); System.out.println("加权平均分"+getAvg(fin)); fin.close();
//读取一张幻灯片的标题
String title=slides[i].getTitle(); System.out.println("标题:"+title); //读取一张幻灯片的内容(包括标题) TextRun[] runs=slides[i].getTextRuns(); for(int j=0;j<runs.length;j++){
//读取时细化到 Sheet、行甚至单元格 public static double getAvg(InputStream is)throws IOException{
HSSFWorkbook wb=new HSSFWorkbook(new POIFSFileSystem(is)); //获取第一张 sheet HSSFSheet sheet=wb.getSheetAt(0);
} }
Excel 文件由多个 Workbook 组成,一个 Workbook 由多个 Sheet 组成。
POI 抽取 Excel 简单示例:
复制代码 代码如下:
package msБайду номын сангаасffice;
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator;
public class PPT {
//直接抽取幻灯片的全部内容 public static String readDoc1(InputStream is) throws IOException{
PowerPointExtractor extractor=new PowerPointExtractor(is); return extractor.getText(); }
public static void main(String[] args) { File file = new File("/home/orisun/1.doc"); try { FileInputStream fin = new FileInputStream(file); String cont = readDoc1(fin); System.out.println(cont); fin.close(); fin = new FileInputStream(file); readDoc2(fin); fin.close(); } catch (IOException e) { e.printStackTrace(); }
System.err.println("数字类型错误!"); System.exit(-2); } if(cell2.getCellType()!=HSSFCell.CELL_TYPE_NUMERIC){ System.err.println("数字类型错误!"); System.exit(-2); } denominator+=Double.parseDouble(cell2.toString().trim()); molecule+=Double.parseDouble(cell2.toString().trim())*Float.parseFloat(cell1.toString().trim()); } return molecule/denominator; }
import org.apache.poi.hslf.HSLFSlideShow; import org.apache.poi.hslf.extractor.PowerPointExtractor; import org.apache.poi.hslf.model.Slide; import org.apache.poi.hslf.model.TextRun; import ermodel.SlideShow;
}catch(IOException e){ e.printStackTrace();
} } }
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.extractor.WordExtractor; import ermodel.CharacterRun; import ermodel.Paragraph; import ermodel.Range; import ermodel.Section;
double molecule=0.0; double denominator=0.0; //按行遍历 sheet Iterator<Row> riter=sheet.rowIterator(); while(riter.hasNext()){
HSSFRow row=(HSSFRow)riter.next(); HSSFCell cell1=row.getCell(4); HSSFCell cell2=row.getCell(4); if(cell1.getCellType()!=HSSFCell.CELL_TYPE_NUMERIC){
使用 POI 抽取 Word 简单示例:
要引入 poi-3.7.jat 和 poi-scratchpad-3.7.ajr 这两个包。
复制代码 代码如下:
package msoffice;
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream;
public class Word {
// 直接抽取全部内容 public static String readDoc1(InputStream is) throws IOException {
WordExtractor extractor = new WordExtractor(is); return extractor.getText(); }
import ermodel.HSSFCell; import ermodel.HSSFRow; import ermodel.HSSFSheet; import ermodel.HSSFWorkbook; import org.apache.poi.hssf.extractor.ExcelExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import ermodel.Row;
Section s=r.getSection(x); for(int y=0;y<s.numParagraphs();y++){
Paragraph p=s.getParagraph(y); for(int z=0;z<p.numCharacterRuns();z++){
CharacterRun run=p.getCharacterRun(z); String text=run.text(); System.out.print(text); } } } }
System.out.println(runs[j].getText()); } } }
public static void main(String[] args){ File file = new File("/home/orisun/2.ppt"); try{ FileInputStream fin=new FileInputStream(file); String cont=readDoc1(fin); System.out.println(cont); fin.close(); fin=new FileInputStream(file); readDoc2(fin); fin.close(); }catch(IOException e){ e.printStackTrace(); }
//分章节 Section、段落 Paragraph、字符串 CharacterRun 抽取 public static void readDoc2(InputStream is) throws IOException {
HWPFDocument doc=new HWPFDocument(is); Range r=doc.getRange(); for(int x=0;x<r.numSections();x++){
//一张幻灯片一张幻灯片地读取 public static void readDoc2(InputStream is) throws IOException{
相关文档
最新文档