分享

poi3.9之读写2010 word/excel/ppt

 流曲频阳 2016-12-06

     poi是java的api用来操作微软的文档

poi的jar包和功能映射如下:

  

 

本文是以poi3.9读写2010word、2010excel、2010ppt,记录学习的脚步

相应的功能在代码都有注释,就不解释了 详情可以参看poi3.9的文档

 主测试函数 TestMain.java

 

  1. /** 
  2.  *  
  3.  */  
  4. package com.undergrowth.poi.test;  
  5.   
  6. import com.undergrowth.poi.ExcelUtils;  
  7. import com.undergrowth.poi.PptUtils;  
  8. import com.undergrowth.poi.WordUtils;  
  9.   
  10. /** 
  11.  * @author u1 
  12.  * 
  13.  */  
  14. public class TestMain {  
  15.   
  16.     /** 
  17.      * 1.对于word,使用XWPFDocument操作07以上的doc或者docx都没有问题,并且必须是07或者以上的电脑上生成的word 
  18.      * 如果是WordExtractor或者HWPFDocument只能操作03以下的word,并且只能是03以下电脑生成的word 
  19.      *  
  20.      * @param args 
  21.      */  
  22.     public static void main(String[] args) {  
  23.         // TODO Auto-generated method stub  
  24.         String path="e:\\poi\\";  
  25.         String fileName="poi.docx";  
  26.         String filePath=path+fileName;  
  27.         //创建word  
  28.         //WordUtils.createWord(path,fileName);  
  29.         //写入数据  
  30.         String data="两国元首在亲切友好、相互信任的气氛中,就中乌关系现状和发展前景,以及共同关心的国际和地区问题深入交换了意见,达成广泛共识。两国元首高度评价中乌关系发展成果,指出建立和发展战略伙伴关系是正确的历史选择,拓展和深化双方各领域合作具有广阔前景和巨大潜力,符合两国和两国人民的根本利益。";  
  31.           
  32.         WordUtils.writeDataDocx(filePath,data);  
  33.         //WordUtils.writeDataDoc(filePath,data);  
  34.           
  35.         //读取数据  
  36.         //String contentWord=WordUtils.readDataDoc(filePath);  
  37.         String contentWord=WordUtils.readDataDocx(filePath);  
  38.         System.out.println("word的内容为:\n"+contentWord);  
  39.           
  40.         //创建excel  
  41.         fileName="poi.xlsx";  
  42.         filePath=path+fileName;  
  43.         String[] unitTitle={"google","baidu","oracle","合计"};  
  44.         String[] itemTitle={"单位","总收入","盈利","亏损"};  
  45.         String[] dataExcel={"10","20","30"};  
  46.         String title="各大公司收入情况";  
  47.         ExcelUtils.writeDataExcelx(filePath,dataExcel,title,unitTitle,itemTitle);  
  48.           
  49.         //读取数据  
  50.         String contentExcel=ExcelUtils.readDataExcelx(filePath);  
  51.         System.out.println("\nexcel的内容为:\n"+contentExcel);  
  52.           
  53.         //创建ppt  
  54.         fileName="poi.pptx";  
  55.         filePath=path+fileName;  
  56.         String titlePptx="华尔街纪录片";  
  57.         String imagePath="images/hej.jpg";  
  58.         PptUtils.writeDataPptx(filePath,titlePptx,imagePath);  
  59.           
  60.         //读取pptx的数据  
  61.         String contentPptx=PptUtils.readDataPptx(filePath);  
  62.         System.out.println("\nppt的内容为:\n"+contentPptx);  
  63.     }  
  64.   
  65. }  


 

word操作工具  WordUtils.java

  1. package com.undergrowth.poi;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10.   
  11. import org.apache.poi.hwpf.HWPFDocument;  
  12. import org.apache.poi.hwpf.extractor.WordExtractor;  
  13. import org.apache.poi.xwpf.usermodel.ParagraphAlignment;  
  14. import org.apache.poi.xwpf.usermodel.XWPFDocument;  
  15. import org.apache.poi.xwpf.usermodel.XWPFParagraph;  
  16. import org.apache.poi.xwpf.usermodel.XWPFRun;  
  17.   
  18. /** 
  19.  * @author u1 
  20.  * 
  21.  */  
  22.   
  23. public class WordUtils {  
  24.   
  25.     //创建.doc后缀的word  
  26.     public static void createWord(String path,String fileName) {  
  27.         // TODO Auto-generated method stub  
  28.         //判断目录是否存在  
  29.         File file=new File(path);  
  30.         if (!file.exists()) file.mkdirs();  
  31.         //因为HWPFDocument并没有提供公共的构造方法 所以没有办法构造word  
  32.         //这里使用word2007及以上的XWPFDocument来进行构造word  
  33.         XWPFDocument document=new XWPFDocument();  
  34.         OutputStream stream=null;  
  35.         try {  
  36.             stream = new FileOutputStream(new File(file, fileName));  
  37.             document.write(stream);  
  38.         } catch (Exception e) {  
  39.             // TODO Auto-generated catch block  
  40.             e.printStackTrace();  
  41.         }finally{  
  42.             if(stream!=null)  
  43.                 try {  
  44.                     stream.close();  
  45.                 } catch (IOException e) {  
  46.                     // TODO Auto-generated catch block  
  47.                     e.printStackTrace();  
  48.                 }  
  49.         }  
  50.           
  51.           
  52.     }  
  53.   
  54.     //向word中写入数据  
  55.     public static void writeDataDocx(String path,String data) {  
  56.         // TODO Auto-generated method stub  
  57.         InputStream istream=null;  
  58.         OutputStream ostream=null;  
  59.         try {  
  60.             //istream = new FileInputStream(path);  
  61.             ostream = new FileOutputStream(path);  
  62.             XWPFDocument document=new XWPFDocument();  
  63.             //添加一个段落  
  64.             XWPFParagraph p1=document.createParagraph();  
  65.             p1.setAlignment(ParagraphAlignment.CENTER);  
  66.             XWPFRun r1=p1.createRun();  
  67.             r1.setText(data);  
  68.             r1.setStrike(true);  
  69.             document.write(ostream);  
  70.             System.out.println("创建word成功");  
  71.         } catch (Exception e) {  
  72.             // TODO Auto-generated catch block  
  73.             e.printStackTrace();  
  74.         }finally{  
  75.             if(istream!=null)  
  76.                 try {  
  77.                     istream.close();  
  78.                 } catch (IOException e) {  
  79.                     // TODO Auto-generated catch block  
  80.                     e.printStackTrace();  
  81.                 }  
  82.             if(ostream!=null)  
  83.                 try {  
  84.                     ostream.close();  
  85.                 } catch (IOException e) {  
  86.                     // TODO Auto-generated catch block  
  87.                     e.printStackTrace();  
  88.                 }  
  89.         }  
  90.           
  91.     }  
  92.   
  93.     //向word中写入数据  
  94.     public static void writeDataDoc(String path,String data) {  
  95.         // TODO Auto-generated method stub  
  96.         OutputStream ostream=null;  
  97.         try {  
  98.             ostream = new FileOutputStream(path);  
  99.             ostream.write(data.getBytes());  
  100.         } catch (Exception e) {  
  101.             // TODO Auto-generated catch block  
  102.             e.printStackTrace();  
  103.         }finally{  
  104.             if(ostream!=null)  
  105.                 try {  
  106.                     ostream.close();  
  107.                 } catch (IOException e) {  
  108.                     // TODO Auto-generated catch block  
  109.                     e.printStackTrace();  
  110.                 }  
  111.         }  
  112.     }  
  113.   
  114.     //读取数据  97-03word  
  115.     public static String readDataDoc(String filePath) {  
  116.         // TODO Auto-generated method stub  
  117.         String content="";  
  118.         InputStream istream=null;  
  119.         try {  
  120.             istream = new FileInputStream(filePath);  
  121.             WordExtractor wordExtractor=new WordExtractor(istream);  
  122.             String[] para=wordExtractor.getParagraphText();  
  123.             for (String string : para) {  
  124.                 content+=string;  
  125.             }  
  126.         } catch (Exception e) {  
  127.             // TODO Auto-generated catch block  
  128.             e.printStackTrace();  
  129.         }finally{  
  130.             if(istream!=null)  
  131.                 try {  
  132.                     istream.close();  
  133.                 } catch (IOException e) {  
  134.                     // TODO Auto-generated catch block  
  135.                     e.printStackTrace();  
  136.                 }  
  137.         }  
  138.           
  139.         return content;  
  140.     }  
  141.   
  142.       
  143.     //读取数据 docx  
  144.     public static String readDataDocx(String filePath) {  
  145.         // TODO Auto-generated method stub  
  146.         String content="";  
  147.         InputStream istream=null;  
  148.         try {  
  149.             istream = new FileInputStream(filePath);  
  150.              XWPFDocument document=new XWPFDocument(istream);  
  151.              content=document.getLastParagraph().getText();  
  152.         } catch (Exception e) {  
  153.             // TODO Auto-generated catch block  
  154.             e.printStackTrace();  
  155.         }finally{  
  156.             if(istream!=null)  
  157.                 try {  
  158.                     istream.close();  
  159.                 } catch (IOException e) {  
  160.                     // TODO Auto-generated catch block  
  161.                     e.printStackTrace();  
  162.                 }  
  163.         }       
  164.         return content;  
  165.     }  
  166.   
  167. }  


 

excel工具 ExcelUtils.java

  1. package com.undergrowth.poi;  
  2.   
  3. import java.awt.Color;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.util.Iterator;  
  10.   
  11. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  12. import org.apache.poi.openxml4j.opc.OPCPackage;  
  13. import org.apache.poi.ss.util.CellRangeAddress;  
  14. import org.apache.poi.xssf.usermodel.XSSFCell;  
  15. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  16. import org.apache.poi.xssf.usermodel.XSSFColor;  
  17. import org.apache.poi.xssf.usermodel.XSSFFont;  
  18. import org.apache.poi.xssf.usermodel.XSSFRow;  
  19. import org.apache.poi.xssf.usermodel.XSSFSheet;  
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  21. import org.apache.poi.xwpf.usermodel.ParagraphAlignment;  
  22. import org.apache.poi.xwpf.usermodel.XWPFDocument;  
  23. import org.apache.poi.xwpf.usermodel.XWPFParagraph;  
  24. import org.apache.poi.xwpf.usermodel.XWPFRun;  
  25.   
  26.   
  27. /** 
  28.  * @author u1 
  29.  * 
  30.  */  
  31.   
  32. public class ExcelUtils {  
  33.   
  34.     //创建xlsx  
  35.     public static void writeDataExcelx(String filePath, String[] dataExcel,  
  36.             String title,String[] unitTitle, String[] itemTitle) {  
  37.         // TODO Auto-generated method stub  
  38.         OutputStream ostream=null;  
  39.         try {  
  40.             ostream = new FileOutputStream(filePath);  
  41.             XSSFWorkbook excel=new XSSFWorkbook();  
  42.             XSSFSheet sheet0=excel.createSheet(title);  
  43.             //excel中第一行  poi中行、列开始都是以0开始计数  
  44.             //合并第一行 显示总标题  占据第一行的第一列到第15列  
  45.             sheet0.addMergedRegion(new CellRangeAddress(00015));  
  46.             XSSFRow row=sheet0.createRow(0);  
  47.             XSSFCell cell=row.createCell(0);  
  48.             cell.setCellValue(title);  
  49.             //设置样式  
  50.             XSSFCellStyle cellStyle=excel.createCellStyle();  
  51.             //居中对齐  
  52.             cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);  
  53.             //字体  
  54.             XSSFFont font=excel.createFont();  
  55.             font.setFontHeightInPoints((short16);  
  56.             font.setColor(new XSSFColor(Color.RED));  
  57.             cellStyle.setFont(font);  
  58.             //设置第一行的样式  
  59.             cell.setCellStyle(cellStyle);  
  60.               
  61.             //显示第二行 表头 各项标题  
  62.             row=sheet0.createRow(1);  
  63.             for (int i = 0; i < itemTitle.length; i++) {  
  64.                 cell=row.createCell(i);  
  65.                 cell.setCellValue(itemTitle[i]);  
  66.                 cell.setCellStyle(cellStyle);  
  67.             }  
  68.               
  69.             //从第三行开始显示 各大公司的数据  
  70.             int start=2;  
  71.             for (String unit : unitTitle) {  
  72.                 row=sheet0.createRow(start);  
  73.                 //第一列显示单位名称  
  74.                 cell=row.createCell(0);  
  75.                 cell.setCellValue(unit);  
  76.                 //添加合计行  
  77.                 if("合计".equals(unit)){  
  78.                     for (int i = 0; i < dataExcel.length; i++) {  
  79.                         cell=row.createCell(i+1);  
  80.                         cell.setCellType(XSSFCell.CELL_TYPE_FORMULA);  
  81.                         char charaColumn=(char)('b'+i);  
  82.                         String formula="sum("+charaColumn+2+":"+charaColumn+start+")";  
  83.                         cell.setCellFormula(formula);  
  84.                     }  
  85.                 }else { //添加数据行  
  86.                     for (int i = 0; i < dataExcel.length; i++) {  
  87.                         cell=row.createCell(i+1);  
  88.                         cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);  
  89.                         cell.setCellValue(Double.valueOf(dataExcel[i]));  
  90.                     }  
  91.                 }  
  92.                 start++;  
  93.             }  
  94.               
  95.               
  96.               
  97.               
  98.             excel.write(ostream);  
  99.             System.out.println("创建excel成功");  
  100.         } catch (Exception e) {  
  101.             // TODO Auto-generated catch block  
  102.             e.printStackTrace();  
  103.         }finally{  
  104.             if(ostream!=null)  
  105.                 try {  
  106.                     ostream.close();  
  107.                 } catch (IOException e) {  
  108.                     // TODO Auto-generated catch block  
  109.                     e.printStackTrace();  
  110.                 }  
  111.         }  
  112.           
  113.     }  
  114.   
  115.     //读取xlsx的数据  
  116.     public static String readDataExcelx(String filePath) {  
  117.         // TODO Auto-generated method stub  
  118.         String content="";  
  119.         try {  
  120.             OPCPackage pkg=OPCPackage.open(filePath);  
  121.             XSSFWorkbook excel=new XSSFWorkbook(pkg);  
  122.             //获取第一个sheet  
  123.             XSSFSheet sheet0=excel.getSheetAt(0);  
  124.             for (Iterator rowIterator=sheet0.iterator();rowIterator.hasNext();) {  
  125.                 XSSFRow row=(XSSFRow) rowIterator.next();  
  126.                 for (Iterator iterator=row.cellIterator();iterator.hasNext();) {  
  127.                     XSSFCell cell=(XSSFCell) iterator.next();  
  128.                     //根据单元的的类型 读取相应的结果  
  129.                     if(cell.getCellType()==XSSFCell.CELL_TYPE_STRING) content+=cell.getStringCellValue()+"\t";  
  130.                     else if(cell.getCellType()==XSSFCell.CELL_TYPE_NUMERIC) content+=cell.getNumericCellValue()+"\t";  
  131.                     else if(cell.getCellType()==XSSFCell.CELL_TYPE_FORMULA) content+=cell.getCellFormula()+"\t";  
  132.                 }  
  133.                 content+="\n";  
  134.             }  
  135.                   
  136.               
  137.               
  138.         } catch (Exception e) {  
  139.             // TODO Auto-generated catch block  
  140.             e.printStackTrace();  
  141.         }  
  142.           
  143.         return content;  
  144.     }  
  145.   
  146.       
  147.       
  148.   
  149. }  


 

ppt的工具 PptUtils.java

  1. /** 
  2.  *  
  3.  */  
  4. package com.undergrowth.poi;  
  5.   
  6. import java.awt.Color;  
  7. import java.awt.Dimension;  
  8. import java.awt.Rectangle;  
  9. import java.io.FileInputStream;  
  10. import java.io.FileOutputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13. import java.io.OutputStream;  
  14. import java.util.Iterator;  
  15.   
  16. import org.apache.poi.util.IOUtils;  
  17. import org.apache.poi.xslf.XSLFSlideShow;  
  18. import org.apache.poi.xslf.usermodel.Placeholder;  
  19. import org.apache.poi.xslf.usermodel.SlideLayout;  
  20. import org.apache.poi.xslf.usermodel.TextAlign;  
  21. import org.apache.poi.xslf.usermodel.TextDirection;  
  22. import org.apache.poi.xslf.usermodel.XMLSlideShow;  
  23. import org.apache.poi.xslf.usermodel.XSLFGroupShape;  
  24. import org.apache.poi.xslf.usermodel.XSLFPictureData;  
  25. import org.apache.poi.xslf.usermodel.XSLFShape;  
  26. import org.apache.poi.xslf.usermodel.XSLFSlide;  
  27. import org.apache.poi.xslf.usermodel.XSLFSlideLayout;  
  28. import org.apache.poi.xslf.usermodel.XSLFSlideMaster;  
  29. import org.apache.poi.xslf.usermodel.XSLFTextBox;  
  30. import org.apache.poi.xslf.usermodel.XSLFTextParagraph;  
  31. import org.apache.poi.xslf.usermodel.XSLFTextRun;  
  32. import org.apache.poi.xslf.usermodel.XSLFTextShape;  
  33. import org.apache.poi.xwpf.usermodel.XWPFDocument;  
  34.   
  35. /** 
  36.  * @author u1 
  37.  * 
  38.  */  
  39. public class PptUtils {  
  40.   
  41.     //创建pptx  
  42.     public static void writeDataPptx(String filePath, String titlePptx,  
  43.             String imagePath) {  
  44.         // TODO Auto-generated method stub  
  45.         OutputStream ostream=null;  
  46.         try {  
  47.             ostream = new FileOutputStream(filePath);  
  48.             XMLSlideShow ppt=new XMLSlideShow();  
  49.             //ppt.setPageSize(new Dimension(500,400));  
  50.             //创建第一块ppt 放置图片  
  51.             XSLFSlide slide=ppt.createSlide();  
  52.               
  53.             XSLFGroupShape shape=slide.createGroup();  
  54.               
  55.             //添加图片  
  56.             byte[] picData=IOUtils.toByteArray(new FileInputStream(imagePath));  
  57.             int pictureIndex=ppt.addPicture(picData, XSLFPictureData.PICTURE_TYPE_JPEG);  
  58.             shape.createPicture(pictureIndex);  
  59.               
  60.             //第二张ppt 放置文本  
  61.             //创建文本框  
  62.             slide=ppt.createSlide();  
  63.             XSLFTextShape textShapeOnly=slide.createTextBox();  
  64.             textShapeOnly.setAnchor(new Rectangle(100100302302));  
  65.             textShapeOnly.setPlaceholder(Placeholder.TITLE);  
  66.             textShapeOnly.setText(titlePptx);  
  67.               
  68.             //第三张ppt  放置标题和文本  
  69.             XSLFSlideMaster master=ppt.getSlideMasters()[0];  
  70.             XSLFSlideLayout layout=master.getLayout(SlideLayout.TITLE_AND_CONTENT);  
  71.             slide=ppt.createSlide(layout);  
  72.             XSLFTextShape[] textShape=slide.getPlaceholders();  
  73.             XSLFTextShape textShape2=textShape[0];  
  74.             textShape2.setText(titlePptx);  
  75.             textShape2=textShape[1];  
  76.             //清除掉母版文本  
  77.             textShape2.clearText();  
  78.             XSLFTextParagraph paragraph=textShape2.addNewTextParagraph();  
  79.             XSLFTextRun run=paragraph.addNewTextRun();  
  80.             run.setText("华尔街是纽约市曼哈顿区南部从百老汇路延伸到东河的一条大街道的名字");  
  81.             run.setFontColor(Color.RED);  
  82.             run.setFontSize(20);  
  83.             paragraph=textShape2.addNewTextParagraph();  
  84.             run=paragraph.addNewTextRun();  
  85.             run.setText("“华尔街”一词现已超越这条街道本身,成为附近区域的代称,亦可指对整个美国经济具有影响力的金融市场和金融机构。");  
  86.             run.setFontColor(Color.RED);  
  87.             run.setFontSize(20);  
  88.               
  89.             ppt.write(ostream);  
  90.               
  91.             System.out.println("创建pptx成功");  
  92.         } catch (Exception e) {  
  93.             // TODO Auto-generated catch block  
  94.             e.printStackTrace();  
  95.         }finally{  
  96.             if(ostream!=null)  
  97.                 try {  
  98.                     ostream.close();  
  99.                 } catch (IOException e) {  
  100.                     // TODO Auto-generated catch block  
  101.                     e.printStackTrace();  
  102.                 }  
  103.         }  
  104.     }  
  105.   
  106.       
  107.     //读取pptx的内容  
  108.         public static String readDataPptx(String filePath) {  
  109.             // TODO Auto-generated method stub  
  110.             String content="";  
  111.             InputStream istream=null;  
  112.             try {  
  113.                 istream = new FileInputStream(filePath);  
  114.                 XMLSlideShow ppt=new XMLSlideShow(istream);  
  115.                 for(XSLFSlide slide:ppt.getSlides()){ //遍历每一页ppt  
  116.                     //content+=slide.getTitle()+"\t";  
  117.                     for(XSLFShape shape:slide.getShapes()){  
  118.                         if(shape instanceof XSLFTextShape){ //获取到ppt的文本信息  
  119.                             for(Iterator iterator=((XSLFTextShape) shape).iterator();iterator.hasNext();){  
  120.                             //获取到每一段的文本信息  
  121.                                 XSLFTextParagraph paragraph=(XSLFTextParagraph) iterator.next();   
  122.                                 for (XSLFTextRun xslfTextRun : paragraph) {  
  123.                                     content+=xslfTextRun.getText()+"\t";  
  124.                                 }  
  125.                             }  
  126.                         }  
  127.                     }  
  128.                     //获取一张ppt的内容后 换行  
  129.                     content+="\n";  
  130.                 }  
  131.             } catch (Exception e) {  
  132.                 // TODO Auto-generated catch block  
  133.                 e.printStackTrace();  
  134.             }finally{  
  135.                 if(istream!=null)  
  136.                     try {  
  137.                         istream.close();  
  138.                     } catch (IOException e) {  
  139.                         // TODO Auto-generated catch block  
  140.                         e.printStackTrace();  
  141.                     }  
  142.             }       
  143.             return content;  
  144.         }  
  145. }  


 

项目结构图:

 

 

效果图:

 

 

 

控制台输出:

  1. 创建word成功  
  2. word的内容为:  
  3. 两国元首在亲切友好、相互信任的气氛中,就中乌关系现状和发展前景,以及共同关心的国际和地区问题深入交换了意见,达成广泛共识。两国元首高度评价中乌关系发展成果,指出建立和发展战略伙伴关系是正确的历史选择,拓展和深化双方各领域合作具有广阔前景和巨大潜力,符合两国和两国人民的根本利益。  
  4. 创建excel成功  
  5.   
  6. excel的内容为:  
  7. 各大公司收入情况      
  8. 单位  总收入 盈利  亏损    
  9. google  10.0    20.0    30.0      
  10. baidu   10.0    20.0    30.0      
  11. oracle  10.0    20.0    30.0      
  12. 合计  sum(b2:b5)  sum(c2:c5)  sum(d2:d5)    
  13.   
  14. 创建pptx成功  
  15.   
  16. ppt的内容为:  
  17.   
  18. 华尔街纪录片    
  19. 华尔街纪录片  华尔街是纽约市曼哈顿区南部从百老汇路延伸到东河的一条大街道的名字    “华尔街”一词现已超越这条街道本身,成为附近区域的代称,亦可指对整个美国经济具有影响力的金融市场和金融机构。    


 

 

 

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多