JAVA使用POI读取PPT文件和POI读取EXCEL WORD示例
- 格式:pdf
- 大小:127.28 KB
- 文档页数:7
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是一款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⽂档内容、表格⼀、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⽂档实例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包可参考⽂档:下载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示例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)⽂件想要实现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(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数据进行读取和写入操作。
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控制台打印。
java 的POI 操作Excel 文件(1)微软在桌面系统上的成功,令我们不得不大量使用它的办公产品,如:Word ,Excel 。
时至今日,它的源代码仍然不公开已封锁了我们的进一步应用和开发。
然而在要求更高的服务器领域,微软本身的产品移植性不好,领域,微软本身的产品移植性不好,性能不佳。
在我们实际的开发中,表现层的解决方案虽然有多样,但是Ie 浏览器已成为最多人使用的浏览器,因为大家都用Windows 。
在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel 打开。
或者是:我们已经习惯用Excel 打印。
这样子如果用.net 开发是没有问题的,开发是没有问题的,但是有但是有j2ee 这个比.net 更有前途的开放式的开发环境,更有前途的开放式的开发环境,难道我为了解决难道我为了解决打印的要求去另写客户端的控件?或者在服务器端使用本地代码?第一种方案的问题是关键数据的处理有时候不能在客户端做,第2种方案的问题是牺牲了代码的可移植性和稳定性。
如果让客户端只负责处理生成好的报表,那将是一种诱人的选择。
性。
如果让客户端只负责处理生成好的报表,那将是一种诱人的选择。
Apache 的Jakata 项目的POI 子项目,目标是处理ole2对象。
目前比较成熟的是HSSF 接口,处理MS MS ExcelExcel (97-2002)对象。
它不象我们仅仅是用csv 生成的没有格式的可以由Excel 转换的东西,转换的东西,而是真正的而是真正的Excel 对象,你可以控制一些属性如sheet,cell 等等。
这是一个年轻的项目,所以象HDF 这样直接支持W ord 对象的好东西仍然在设计中。
其它支持word 格式的纯java 方案还有itext ,不过也是仍在奋斗中。
但是HSSF 已经成熟到能够和足够我们使用了。
另外,无锡永中Office 的实现方案也是纯java 的解决方案,不过那也是完全商业的产品,并不是公开代码项目。
利⽤POI读取word、Excel⽂件的最佳实践教程前⾔是 Apache 旗下⼀款读写微软家⽂档声名显赫的类库。
应该很多⼈在做报表的导出,或者创建 word ⽂档以及读取之类的都是⽤过 POI。
POI 也的确对于这些操作带来很⼤的便利性。
我最近做的⼀个⼯具就是读取计算机中的 word 以及 excel ⽂件。
POI结构说明包名称说明HSSF提供读写Microsoft Excel XLS格式档案的功能。
XSSF提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF提供读写Microsoft Word DOC格式档案的功能。
HSLF提供读写Microsoft PowerPoint格式档案的功能。
HDGF提供读Microsoft Visio格式档案的功能。
HPBF提供读Microsoft Publisher格式档案的功能。
HSMF提供读Microsoft Outlook格式档案的功能。
下⾯就word和excel两⽅⾯讲解以下遇到的⼀些坑:word 篇对于 word ⽂件,我需要的就是提取⽂件中正⽂的⽂字。
所以可以创建⼀个⽅法来读取 doc 或者 docx ⽂件:private static String readDoc(String filePath, InputStream is) {String text= "";try {if (filePath.endsWith("doc")) {WordExtractor ex = new WordExtractor(is);text = ex.getText();ex.close();is.close();} else if(filePath.endsWith("docx")) {XWPFDocument doc = new XWPFDocument(is);XWPFWordExtractor extractor = new XWPFWordExtractor(doc);text = extractor.getText();extractor.close();is.close();}} catch (Exception e) {logger.error(filePath, e);} finally {if (is != null) {is.close();}}return text;}理论上来说,这段代码应该对于读取⼤多数 doc 或者 docx ⽂件都是有效的。
Java读取doc、docx、xls、xlsx、ppt、pptx、pdf⽂件内容读取⽂件信息所需依赖<!-- 读取Excel XLS --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><!-- 读取PPT、DOC、Visio --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><!-- 读取Excel XLSX、PPTX、DOCX、--><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><!--读取pdf信息--><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.12</version></dependency><!-- https:///artifact/org.apache.pdfbox/fontbox --><dependency><groupId>org.apache.pdfbox</groupId><artifactId>fontbox</artifactId><version>2.0.12</version></dependency>读取doc⽂件内容public static String readWord(String name){FileInputStream in;String text = null;try{in = new FileInputStream(name);WordExtractor extractor = new WordExtractor(in);text = extractor.getText();}catch (FileNotFoundException e){// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return text;}读取docx⽂件内容public static String readDoc(MultipartFile file) {if (file.isEmpty())return "";WordExtractor wordExtractor = null;try {InputStream inputStream = file.getInputStream();wordExtractor = new WordExtractor(inputStream);} catch (IOException e) {log.warn(e.toString());e.printStackTrace();}return wordExtractor.getText();}读取xls⽂件内容public static String readXls(MultipartFile file) {if (file.isEmpty()) return "";StringBuilder content = new StringBuilder();try {HSSFWorkbook excel = new HSSFWorkbook(file.getInputStream());//获取第⼀个sheetHSSFSheet sheet0 = excel.getSheetAt(0);for (Iterator rowIterator = sheet0.iterator(); rowIterator.hasNext(); ) {HSSFRow row = (HSSFRow) rowIterator.next();for (Iterator iterator = row.cellIterator(); iterator.hasNext(); ) {HSSFCell cell = (HSSFCell) iterator.next();//根据单元的的类型读取相应的结果if (cell.getCellType() == CellType.STRING)content.append(cell.getStringCellValue() + "\t");else if (cell.getCellType() == CellType.NUMERIC|| cell.getCellType() == CellType.FORMULA)content.append(cell.getNumericCellValue() + "\t");elsecontent.append("" + "\t");}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();log.warn(e.toString());}return content.toString();}读取xlsx⽂件内容public static String readXlsx(MultipartFile file) {if (file.isEmpty()) return "";StringBuilder content = new StringBuilder();try {XSSFWorkbook excel = new XSSFWorkbook(file.getInputStream()); //获取第⼀个sheetXSSFSheet sheet0 = excel.getSheetAt(0);for (Iterator rowIterator = sheet0.iterator(); rowIterator.hasNext(); ) { XSSFRow row = (XSSFRow) rowIterator.next();for (Iterator iterator = row.cellIterator(); iterator.hasNext(); ) {XSSFCell cell = (XSSFCell) iterator.next();//根据单元格的类型读取相应的结果if (cell.getCellType() == CellType.STRING)content.append(cell.getStringCellValue() + "\t");else if (cell.getCellType() == CellType.NUMERIC|| cell.getCellType() == CellType.FORMULA)content.append(cell.getNumericCellValue() + "\t");elsecontent.append("" + "\t");}}} catch (Exception e) {e.printStackTrace();log.warn(e.toString());}return content.toString();}读取pdf⽂件内容/*** 读取 PDF⽂本内容** @Param: MultipartFile* @return: pdf⽂本内容*/public static String readPdf(MultipartFile file) {StringBuilder content = new StringBuilder();try {InputStream is = file.getInputStream();PDFParser parser = new PDFParser(new RandomAccessBuffer(is)); parser.parse();// 读取⽂本内容PDDocument document = parser.getPDDocument();// 获取页码int pages = document.getNumberOfPages();PDFTextStripper stripper = new PDFTextStripper();// 设置按顺序输出stripper.setSortByPosition(true);stripper.setStartPage(1);stripper.setEndPage(pages);content.append(stripper.getText(document));} catch (Exception e) {e.printStackTrace();log.warn(e.toString());}return content.toString();}PDF⽂件加载有两种⽅式,⽆明显差异,⽅式⼆代码较简洁:// ⽅式⼀:InputStream input = null;input = new FileInputStream( pdfFile );//加载 pdf ⽂档PDFParser parser = new PDFParser(new RandomAccessBuffer(input));parser.parse();document = parser.getPDDocument();// ⽅式⼆:document=PDDocument.load(pdfFile);读取ppt⽂件内容public static String readPPT(MultipartFile file) {if (file.isEmpty()) return "";StringBuilder content = new StringBuilder();try {InputStream is = file.getInputStream();HSLFSlideShow hslfSlideShow = new HSLFSlideShow(is);List<HSLFSlide> slides = hslfSlideShow.getSlides();SlideShowExtractor slideShowExtractor = new SlideShowExtractor(hslfSlideShow); for (HSLFSlide slide : slides) {content.append(slideShowExtractor.getText(slide));}slideShowExtractor.close();} catch (IOException e) {log.warn(e.toString());e.printStackTrace();}return content.toString();}读取pptx⽂件内容public static String readPPTX(MultipartFile file) {if (file.isEmpty()) return "";StringBuffer content = new StringBuffer();try {InputStream is = file.getInputStream();XMLSlideShow xmlSlideShow = new XMLSlideShow(is);List<XSLFSlide> slides = xmlSlideShow.getSlides(); //获得每⼀张幻灯⽚for (XSLFSlide slide : slides) {CTSlide rawSlide = slide.getXmlObject();CTGroupShape spTree = rawSlide.getCSld().getSpTree();List<CTShape> spList = spTree.getSpList();for (CTShape shape : spList) {CTTextBody txBody = shape.getTxBody();if (null == txBody) {continue;}List<CTTextParagraph> pList = txBody.getPList();for (CTTextParagraph textParagraph : pList) {List<CTRegularTextRun> textRuns = textParagraph.getRList();for (CTRegularTextRun textRun : textRuns) {content.append(textRun.getT());}}}}xmlSlideShow.close();} catch (Exception e) {e.printStackTrace();}return content.toString();}。
apachepoi操作office⽂档----java在线预览txt、word、ppt、e。
在页⾯上显⽰各种⽂档中的内容。
在servlet中的逻辑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实现poi方式读取word文件内容(不带格式)声明:文章为原创,代码也是经过网上查询整理的,如有雷同,合情合理,博主很诚实。
1.此技术分享实现Java程序从word文档中读取文本内容保存为字符串,很简单。
2.准备工作:poi的jar包,我用的是3.16版本,官网上下载就可以,找不到的可以留言联系我。
3.直接上代码[java] view plain copy print?1. package com.poi.test;2.3. import java.io.File;4. import java.io.FileInputStream;5. import java.io.InputStream;6.7. import org.apache.poi.POIXMLDocument;8. import org.apache.poi.POIXMLTextExtractor;9. import org.apache.poi.hwpf.extractor.WordExtractor;10. import org.apache.poi.openxml4j.opc.OPCPackage;11. import org.apache.poi.xwpf.extractor.XWPFWordExtractor;12.13. public class testPoi {14. /**15. * 读取word文件内容16. *17. * @param path18. * @return buffer19. */20.21. public String readWord(String path) {22. String buffer = "";23. try {24. if (path.endsWith(".doc")) {25. InputStream is = new FileInputStream(new File(path));26. WordExtractor ex = new WordExtractor(is);27. buffer = ex.getText();28. ex.close();29. } else if (path.endsWith("docx")) {30. OPCPackage opcPackage = POIXMLDocument.openPackage(path);31. POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);32. buffer = extractor.getText();33. extractor.close();34. } else {35. System.out.println("此文件不是word文件!");36. }37.38. } catch (Exception e) {39. e.printStackTrace();40. }41.42. return buffer;43. }44.45. public static void main(String[] args) {46. // TODO Auto-generated method stub47. testPoi tp = new testPoi();48. String content = tp.readWord("D:\\test01.doc");49. System.out.println("content===="+content);50. }51.52. }4.测试4.1源文件内容(源文件位置:D:\test01.doc)4.2测试结果需要word文档中的任何内容,解析就可以了。
javapoi读取excel操作⽰例(2个代码)项⽬中要求读取excel⽂件内容,并将其转化为xml格式。
常见读取excel⽂档⼀般使⽤POI和JExcelAPI这两个⼯具。
这⾥我们介绍使⽤POI实现读取excel⽂档。
复制代码代码如下:/** 使⽤POI读取EXCEL⽂件*/import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import ermodel.HSSFCell;import ermodel.HSSFRow;import ermodel.HSSFSheet;import ermodel.HSSFWorkbook;/**** @author Hanbin*/public class ReadExcel {/*** @param args the command line arguments*/public static void main(String[] args)throws Exception {read("d:\\demo.xls");}public static ArrayList read(String fileName){ArrayList list = new ArrayList();String sql = "";try{File f = new File(fileName);FileInputStream fis = new FileInputStream(f);HSSFWorkbook wbs = new HSSFWorkbook(fis);HSSFSheet childSheet = wbs.getSheetAt(0);System.out.println("⾏数:" + childSheet.getLastRowNum());for(int i = 4;i<childSheet.getLastRowNum();i++){HSSFRow row = childSheet.getRow(i);System.out.println("列数:" + row.getPhysicalNumberOfCells());if(null != row){for(int k=1;k<row.getPhysicalNumberOfCells();k++){HSSFCell cell;cell = row.getCell((short)k);// System.out.print(getStringCellValue(cell) + "\t");list.add(getStringCellValue(cell) + "\t");}}}}catch(Exception e){e.printStackTrace();}return list;}* @return String 单元格数据内容*/private static String getStringCellValue(HSSFCell cell) { String strCell = "";switch (cell.getCellType()) {case HSSFCell.CELL_TYPE_STRING:strCell = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_NUMERIC:strCell = String.valueOf(cell.getNumericCellValue()); break;case HSSFCell.CELL_TYPE_BOOLEAN:strCell = String.valueOf(cell.getBooleanCellValue()); break;case HSSFCell.CELL_TYPE_BLANK:strCell = "";break;default:strCell = "";break;}if (strCell.equals("") || strCell == null) {return "";}if (cell == null) {return "";}return strCell;}}再来⼀个例⼦复制代码代码如下:package edu.sjtu.erplab.poi;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import ermodel.HSSFCell;import ermodel.HSSFDateUtil; import ermodel.HSSFRow;import ermodel.HSSFSheet; import ermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /*** 操作Excel表格的功能类*/public class ExcelReader {private POIFSFileSystem fs;private HSSFWorkbook wb;private HSSFSheet sheet;* 读取Excel表格表头的内容* @param InputStream* @return String 表头内容的数组*/public String[] readExcelTitle(InputStream is) {try {fs = new POIFSFileSystem(is);wb = new HSSFWorkbook(fs);} catch (IOException e) {e.printStackTrace();}sheet = wb.getSheetAt(0);row = sheet.getRow(0);// 标题总列数int colNum = row.getPhysicalNumberOfCells();System.out.println("colNum:" + colNum);String[] title = new String[colNum];for (int i = 0; i < colNum; i++) {//title[i] = getStringCellValue(row.getCell((short) i));title[i] = getCellFormatValue(row.getCell((short) i));}return title;}/*** 读取Excel数据内容* @param InputStream* @return Map 包含单元格数据内容的Map对象*/public Map<Integer, String> readExcelContent(InputStream is) {Map<Integer, String> content = new HashMap<Integer, String>();String str = "";try {fs = new POIFSFileSystem(is);wb = new HSSFWorkbook(fs);} catch (IOException e) {e.printStackTrace();}sheet = wb.getSheetAt(0);// 得到总⾏数int rowNum = sheet.getLastRowNum();row = sheet.getRow(0);int colNum = row.getPhysicalNumberOfCells();// 正⽂内容应该从第⼆⾏开始,第⼀⾏为表头的标题for (int i = 1; i <= rowNum; i++) {row = sheet.getRow(i);int j = 0;while (j < colNum) {// 每个单元格的数据内容⽤"-"分割开,以后需要时⽤String类的replace()⽅法还原数据// 也可以将每个单元格的数据设置到⼀个javabean的属性中,此时需要新建⼀个javabean // str += getStringCellValue(row.getCell((short) j)).trim() +// "-";str += getCellFormatValue(row.getCell((short) j)).trim() + " ";j++;}content.put(i, str);str = "";}return content;* 获取单元格数据内容为字符串类型的数据** @param cell Excel单元格* @return String 单元格数据内容*/private String getStringCellValue(HSSFCell cell) {String strCell = "";switch (cell.getCellType()) {case HSSFCell.CELL_TYPE_STRING:strCell = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_NUMERIC:strCell = String.valueOf(cell.getNumericCellValue());break;case HSSFCell.CELL_TYPE_BOOLEAN:strCell = String.valueOf(cell.getBooleanCellValue());break;case HSSFCell.CELL_TYPE_BLANK:strCell = "";break;default:strCell = "";break;}if (strCell.equals("") || strCell == null) {return "";}if (cell == null) {return "";}return strCell;}/*** 获取单元格数据内容为⽇期类型的数据** @param cell* Excel单元格* @return String 单元格数据内容*/private String getDateCellValue(HSSFCell cell) {String result = "";try {int cellType = cell.getCellType();if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {Date date = cell.getDateCellValue();result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate();} else if (cellType == HSSFCell.CELL_TYPE_STRING) {String date = getStringCellValue(cell);result = date.replaceAll("[年⽉]", "-").replace("⽇", "").trim(); } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {result = "";}} catch (Exception e) {System.out.println("⽇期格式不正确!");e.printStackTrace();}return result;* 根据HSSFCell类型设置数据* @param cell* @return*/private String getCellFormatValue(HSSFCell cell) {String cellvalue = "";if (cell != null) {// 判断当前Cell的Typeswitch (cell.getCellType()) {// 如果当前Cell的Type为NUMERICcase HSSFCell.CELL_TYPE_NUMERIC:case HSSFCell.CELL_TYPE_FORMULA: {// 判断当前的cell是否为Dateif (HSSFDateUtil.isCellDateFormatted(cell)) {// 如果是Date类型则,转化为Data格式//⽅法1:这样⼦的data格式是带时分秒的:2011-10-12 0:00:00 //cellvalue = cell.getDateCellValue().toLocaleString();//⽅法2:这样⼦的data格式是不带带时分秒的:2011-10-12Date date = cell.getDateCellValue();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); cellvalue = sdf.format(date);}// 如果是纯数字else {// 取得当前Cell的数值cellvalue = String.valueOf(cell.getNumericCellValue());}break;}// 如果当前Cell的Type为STRINcase HSSFCell.CELL_TYPE_STRING:// 取得当前的Cell字符串cellvalue = cell.getRichStringCellValue().getString();break;// 默认的Cell值default:cellvalue = " ";}} else {cellvalue = "";}return cellvalue;}public static void main(String[] args) {try {// 对读取Excel表格标题测试InputStream is = new FileInputStream("d:\\test2.xls");ExcelReader excelReader = new ExcelReader();String[] title = excelReader.readExcelTitle(is);System.out.println("获得Excel表格的标题:");for (String s : title) {System.out.print(s + " ");}for (int i = 1; i <= map.size(); i++) {System.out.println(map.get(i));}} catch (FileNotFoundException e) {System.out.println("未找到指定路径的⽂件!");e.printStackTrace();}}}。
POI 与Microsoft Office1. POI 简介POI 是Apache 下的Jakata 项目的一个子项目,主要用于提供java 操作MicrosoftOffice 办公套件如Excel,Word,Powerpoint 等文件的API.微软的Office 办公软件在企业的日常办公中占据着重要的地位,人们已经非常熟悉Office 的使用。
在我们开发的应用系统中,常常需要将数据导出到Excel 文件中,或者Word 文件中进行打印。
比如移动的话费查询系统中就提供了将话费清单导入到excel 表格中的功能。
这样在web 应用中,我们在浏览器中看到的数据可以被导出到Excel 中了。
∙Excel 文件: xls 格式文件对应POI API 为HSSF 。
xlsx 格式为office 2007 的文件格式,POI 中对应的API 为XSSF∙Word 文件:doc 格式文件对应的POI API 为HWPF。
docx 格式为XWPF ∙powerPoint 文件:ppt 格式对应的POI API 为HSLF。
pptx 格式为XSLF ∙outlook :对应的API 为HSMF∙Visio: 对应的API 为HDGF∙Publisher : 对应的API 为HPBF下面主要介绍如何操作Excel。
回到顶部2. 下载POI到apache 官方网站下载POI 的jar 包回到顶部3. Excel 文件的结构一个Excel 文档称为工作簿(worksheet),一个工作簿包含多个工作表(sheet),每个工作表看起来像一张二维表格,由很多行(row)组成,每行由多个单元格组成(cell).下面是POI HSSF API 中的类与Excel 结构的对应关系:回到顶部4. 创建空的Excel 文件新建java项目,导入jar文件4.1 创建空的xls 文件创建的xls 文件用excel 打开的时候报错,因为这个Excel 文件结构不完整。
Java的POI(Poor Obfuscation Implementation)是一个用于处理Microsoft Office文档的Java库,主要包括对Excel、Word和PowerPoint等文件的读写操作。
以下是一个简单的Java POI用法示例:1. 首先,需要在项目中引入Apache POI依赖。
如果使用Maven,可以在pom.xml文件中添加以下依赖:```xml<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.0</version></dependency>```2. 创建一个Java类,实现读取Excel文件的功能:```javaimport ermodel.*;import ermodel.XSSFWorkbook;import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class ReadExcel {public static void main(String[] args) {try {FileInputStream excelFile = new FileInputStream(new File("example.xlsx"));Workbook workbook = new XSSFWorkbook(excelFile);Sheet sheet = workbook.getSheetAt(0);for (Row row : sheet) {for (Cell cell : row) {switch (cell.getCellType()) {case STRING:System.out.print(cell.getStringCellValue() + "\t");break;case NUMERIC:System.out.print(cell.getNumericCellValue() + "\t");break;case BOOLEAN:System.out.print(cell.getBooleanCellValue() + "\t");break;default:System.out.print("N/A\t");break;}}System.out.println();}workbook.close();} catch (IOException e) {e.printStackTrace();}}}```这个示例中,我们首先创建了一个`FileInputStream`对象来读取名为"example.xlsx"的Excel文件。