POI操作PPT文档1

注意ppt模板不能使用${user}--这样的作为替换标识,在读取PPT模板时会解析成三段文本1.${ 2.user  3.},而一般在控件中使用%1$S这样的方式做为替换标识。

%n$ms:代表输出的是字符串,n代表是第几个参数,设置m的值可以在输出之前放置空格 如下所示:
String s = "我的名字叫%1$s,我来自%2$s";
String formatstr = String.format(s, "李四","首都北京");

1)如果是创建新的PPT文档,直接使用SlideShow和Slide类就可以,其中SlideShow表示PPT文

档,Slide表示某一张幻灯片
如下代码创建空的PPT文档:

SlideShow ppt = new SlideShow();
Slide[] slides = ppt.getSlides();
assertTrue(slides.length == 0);
savePPTFile(ppt);

private void savePPTFile(SlideShow ppt) throws Exception{
        FileOutputStream out = new FileOutputStream(\"ppt测试.ppt\");
        ppt.write(out);
         out.close();
}

2)设置母版,这样后续的新建幻灯片都将使用母版的字体,背景等设置

SlideShow ppt = new SlideShow();
//设置幻灯片大小
ppt.setPageSize(new Dimension(760,600));
SlideMaster master = ppt.getSlidesMasters()[0];      
//设置母板背景,支持多种图片格式
int picIndex = ppt.addPicture(new File(\"background.png\"),
Picture.PNG);Picture background = new Picture(picIndex);
//设置图片位置
background.setAnchor(new java.awt.Rectangle(0, 0, ppt.getPageSize().width

, ppt.getPageSize().height));
master.addShape(background);

3)创建幻灯片并插入文本

SlideShow ppt = new SlideShow();
Slide newSlide = ppt.createSlide();
//添加幻灯片标题
TextBox title = newSlide.addTitle();
RichTextRun titleRun = title.getTextRun().getRichTextRuns()[0];
titleRun.setFontColor(Color.RED);
title.setText(\"ppt测试\");
//添加文本框
TextBox txt = new TextBox();
RichTextRun richTextRun = txt.getTextRun().getRichTextRuns()[0];
richTextRun.setFontColor(Color.BLUE); 
//setText参数字符串可以包含回车、换行符,但是最后一行不能以\\r\\n结尾,否则设置的格式没

有效果(v3.5)
richTextRun.setText(\"这里可以换行\\r\\n第二行文本\");   
txt.setAnchor(new java.awt.Rectangle(50,150,400,400));
newSlide.addShape(txt); savePPTFile(ppt);

4)插入图片,支持多种格式

SlideShow ppt = new SlideShow();
Slide newSlide = ppt.createSlide();
int picIndex = ppt.addPicture(new File(\"图片.jpg\"),
Picture.JPEG);Picture jpg = new Picture(picIndex);
//set image position in the slide
jpg.setAnchor(new java.awt.Rectangle(360, 200, 280, 260));
 newSlide.addShape(jpg);
savePPTFile(ppt);

5)插入表格(v3.5)

SlideShow ppt = new SlideShow();
Slide slide = ppt.createSlide();
String[][] datas = {   
{\"序号\", \"姓名\",\"年龄\"},   
{\"1\", \"张三\",\"30\"},  
{\"2\", \"李四\",\"27\"},
};
//create a table of 3 rows and 3 columns
Table table = new Table(3, 3);
for (int i = 0; i < datas.length; i++) {
    for (int j = 0; j < datas[i].length; j++) {
        TableCell cell = table.getCell(i, j);
         RichTextRun rt = cell.getTextRun().getRichTextRuns()[0];
        rt.setFontName(\"宋体\");
        rt.setFontSize(12);
         cell.setVerticalAlignment(TextBox.AnchorMiddle);
        cell.setHorizontalAlignment(TextBox.AlignCenter);
        cell.setText(datas[i][j]);
         if(i == 0){
             //首行背景设置为灰色
             cell.setFillColor(Color.GRAY);
        }
    }
}

Line border = table.createBorder();
border.setLineColor(Color.black);
border.setLineWidth(2.0);
table.setAllBorders(border); 
slide.addShape(table);
table.moveTo(160,260);
savePPTFile(ppt);

6)如果是读取已存在的PPT文档则还要用到HSLFSlideShow,下面代码将PPT文件导出为图片

(png)格式,如果幻灯片上有中文字符则这些字符的字体需要修改为支持中文的字体(宋体等),否

则导出的图片的中文字符不能正常显示

SlideShow ppt = new SlideShow(new HSLFSlideShow(\"PPT测试.ppt\"));
Dimension pgsize = ppt.getPageSize();
Slide[] slide = ppt.getSlides();
for (int i = 0; i < slide.length; i++) {
    BufferedImage img = new BufferedImage(pgsize.width, pgsize.height

, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = img.createGraphics();
    //clear the drawing area
    graphics.setPaint(Color.white);
    graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
     //render    slide[i].draw(graphics);
     FileOutputStream out = new FileOutputStream(\"slide-\"  + (i+1) + \".png\");

javax.imageio.ImageIO.write(img, \"png\", out);
    out.close();
}

7)提取PPT文档信息

SlideShow ppt = new SlideShow(new HSLFSlideShow(\"PPT测试.ppt\"));
Slide[] slides = ppt.getSlides();
//提取文本信息  
for (Slide each : slides) {
    System.out.println(each.getTitle()) ;
    TextRun[] textRuns = each.getTextRuns();
    for (int i=0 ;i< textRuns.length; i++ ) {
        System.out.println(textRuns[i].getText());
        RichTextRun[] richTextRuns = textRuns[i].getRichTextRuns();
        for (int j = 0; j < richTextRuns.length; j++) {
            System.out.println(richTextRuns[j].getText());
        }
    }
}

//提取所有JPEG图片
PictureData[] picDatas = ppt.getPictureData();
for (int i=0;i<picDatas.length;i++) {
    if(picDatas[i].getType() == Picture.JPEG){
        FileOutputStream out = new FileOutputStream(\"jpg_\" + i + \".jpg\");
        ppt.write(out);
        out.close();
    }
}

8)设置PPT文档摘要信息(文档点击鼠标右键查看属性)

HSLFSlideShow hslf = HSLFSlideShow.create();
DocumentSummaryInformation dsi= hslf.getDocumentSummaryInformation();

SummaryInformation si= hslf.getSummaryInformation();   
dsi.setCompany(\"yourCompany\"); 
dsi.setCategory(\"ppt测试\");  
si.setAuthor(\"yourName\");  
si.setTitle(\"标题\");  
SlideShow ppt = new SlideShow(hslf);
savePPTFile(ppt);

POI操作PPT文档2

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.AutoShape;
import org.apache.poi.hslf.model.Fill;
import org.apache.poi.hslf.model.Freeform;
import org.apache.poi.hslf.model.HeadersFooters;
import org.apache.poi.hslf.model.Hyperlink;
import org.apache.poi.hslf.model.Line;
import org.apache.poi.hslf.model.Picture;
import org.apache.poi.hslf.model.Shape;
import org.apache.poi.hslf.model.ShapeTypes;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.SlideMaster;
import org.apache.poi.hslf.model.Table;
import org.apache.poi.hslf.model.TableCell;
import org.apache.poi.hslf.model.TextBox;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.PictureData;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.hslf.usermodel.SoundData;

public class PPTParseUtil {
 public static void main(String[] args) throws IOException {
  SlideShow ppt = new SlideShow();

// 设置标题,底部信息
  // presentation-scope headers / footers
  HeadersFooters hdd = ppt.getSlideHeadersFooters();
  hdd.setSlideNumberVisible(true);
  hdd.setFootersText("Created by POI-HSLF");

// add first slide
  Slide s1 = ppt.createSlide();

// add second slide
  Slide s2 = ppt.createSlide();
  // retrieve page size. Coordinates are expressed in points (72 dpi)
  java.awt.Dimension pgsize = ppt.getPageSize();
  int pgx = pgsize.width; // slide width
  int pgy = pgsize.height; // slide height

// set new page size
  ppt.setPageSize(new java.awt.Dimension(1024, 768));
  // save changes
  FileOutputStream out = new FileOutputStream

("E:\\logs\\slideshow.ppt");

// get slides
  Slide[] slide = ppt.getSlides();
  for (int i = 0; i < slide.length; i++) {
   Shape[] sh = slide[i].getShapes();
   for (int j = 0; j < sh.length; j++) {
    // name of the shape
    String name = sh[j].getShapeName();

// shapes's anchor which defines the position of this

shape in
    // the slide
    java.awt.Rectangle anchor = sh[j].getAnchor();

if (sh[j] instanceof Line) {
     Line line = (Line) sh[j];
     // work with Line
    } else if (sh[j] instanceof AutoShape) {
     AutoShape shape = (AutoShape) sh[j];
     // work with AutoShape
    } else if (sh[j] instanceof TextBox) {
     TextBox shape = (TextBox) sh[j];
     // work with TextBox
    } else if (sh[j] instanceof Picture) {
     Picture shape = (Picture) sh[j];
     // work with Picture
    }
   }
  }

// Drawing a shape on a slide
  Slide slide2 = ppt.createSlide();

// set slide title
  TextBox title = slide2.addTitle();
  title.setText("Hello, World!");
  // Line shape
  Line line = new Line();
  line.setAnchor(new java.awt.Rectangle(50, 50, 100, 20));
  line.setLineColor(new Color(0, 128, 0));
  line.setLineStyle(Line.LINE_DOUBLE);
  slide2.addShape(line);

// TextBox
  TextBox txt = new TextBox();
  txt.setText("Hello, World!");
  txt.setAnchor(new java.awt.Rectangle(300, 100, 300, 50));

// use RichTextRun to work with the text format
  RichTextRun rt = txt.getTextRun().getRichTextRuns()[0];
  rt.setFontSize(32);
  rt.setFontName("Arial");
  rt.setBold(true);
  rt.setItalic(true);
  rt.setUnderlined(true);
  rt.setFontColor(Color.red);
  rt.setAlignment(TextBox.AlignRight);

slide2.addShape(txt);

// create shapes of arbitrary geometry
  java.awt.geom.GeneralPath path = new java.awt.geom.GeneralPath();
  path.moveTo(100, 100);
  path.lineTo(200, 100);
  path.curveTo(50, 45, 134, 22, 78, 133);
  path.curveTo(10, 45, 134, 56, 78, 100);
  path.lineTo(100, 200);
  path.closePath();

Freeform shape = new Freeform();
  shape.setPath(path);
  slide2.addShape(shape);

// Autoshape
  // 32-point star
  AutoShape sh1 = new AutoShape(ShapeTypes.Star32);
  sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200));
  sh1.setFillColor(Color.red);
  slide2.addShape(sh1);

// Trapezoid
  AutoShape sh2 = new AutoShape(ShapeTypes.Trapezoid);
  sh2.setAnchor(new java.awt.Rectangle(150, 150, 100, 200));
  sh2.setFillColor(Color.blue);
  slide2.addShape(sh2);

// work with pictures
  // extract all pictures contained in the presentation
  PictureData[] pdata = ppt.getPictureData();
  for (int ii = 0; ii < pdata.length; ii++) {
   PictureData pict = pdata[ii];

// picture data
   byte[] data = pict.getData();

int type = pict.getType();
   String ext;
   switch (type) {
   case Picture.JPEG:
    ext = ".jpg";
    break;
   case Picture.PNG:
    ext = ".png";
    break;
   case Picture.WMF:
    ext = ".wmf";
    break;
   case Picture.EMF:
    ext = ".emf";
    break;
   case Picture.PICT:
    ext = ".pict";
    break;
   default:
    continue;
   }
   FileOutputStream out2 = new FileOutputStream("pict_" + ii +

ext);
   out2.write(data);
   out2.close();

}

// add a new picture to this slideshow and insert it in a new slide
  int idx = ppt.addPicture(new File("E:\\logs\\clock.png"), Picture.PNG);

Picture pict = new Picture(idx);

// set image position in the slide
  pict.setAnchor(new java.awt.Rectangle(100, 100, 300, 200));

Slide slide3 = ppt.createSlide();
  slide3.addShape(pict);

// This slide has its own background.
  // Without this line it will use master's background.
  slide3.setFollowMasterBackground(false);
  Fill fill = slide3.getBackground().getFill();
  int idx1 = ppt.addPicture(new File("E:\\logs\\clock.png"), Picture.PNG);
  fill.setFillType(Fill.FILL_PATTERN);
  fill.setPictureData(idx1);

// create bulleted lists

TextBox shape1 = new TextBox();
  RichTextRun rt1 = shape1.getTextRun().getRichTextRuns()[0];
  shape1.setText("January\r" + "February\r" + "March\r" + "April");
  rt1.setFontSize(42);
  rt1.setBullet(true);
  rt1.setBulletOffset(0); // bullet offset
  rt1.setTextOffset(50); // text offset (should be greater than bullet
        // offset)
  rt1.setBulletChar('\u263A'); // bullet character
  slide3.addShape(shape1);

shape1.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); // position

// of the

// text box

// in the

// slide
  slide3.addShape(shape1);

// now retrieve pictures containes in the first slide and save them on
  // disk
  slide3 = ppt.getSlides()[0];
  Shape[] sh3 = slide3.getShapes();
  for (int i2 = 0; i2 < sh3.length; i2++) {
   if (sh3[i2] instanceof Picture) {
    Picture pict1 = (Picture) sh3[i2];
    PictureData pictData = pict1.getPictureData();
    byte[] data = pictData.getData();
    int type = pictData.getType();
    if (type == Picture.JPEG) {
     FileOutputStream out3 = new

FileOutputStream("slide0_" + i2
       + ".jpg");
     out3.write(data);
     out3.close();
    } else if (type == Picture.PNG) {
     FileOutputStream out4 = new

FileOutputStream("slide0_" + i2
       + ".png");
     out4.write(data);
     out4.close();
    }
   }
  }

// modify background of a slide master
  SlideMaster master = ppt.getSlidesMasters()[0];

Fill fill1 = master.getBackground().getFill();
  int idx11 = ppt
    .addPicture(new File("E:\\logs\\clock.png"),

Picture.PNG);
  fill1.setFillType(Fill.FILL_PICTURE);
  fill1.setPictureData(idx11);

// read hyperlinks from a slide show
  Slide[] slide1 = ppt.getSlides();
  for (int j = 0; j < slide1.length; j++) {

// read hyperlinks from the text runs
   TextRun[] txt1 = slide1[j].getTextRuns();
   if (txt1 == null || txt1.length == 0) {
    continue;
   }
   for (int k = 0; k < txt1.length; k++) {
    String text = txt1[k].getText();
    Hyperlink[] links = txt1[k].getHyperlinks();
    if (links != null)
     for (int l = 0; l < links.length; l++) {
      Hyperlink link = links[l];
      String title1 = link.getTitle();
      String address = link.getAddress

();
      String substring = text.substring

(link.getStartIndex(),

link.getEndIndex() - 1); // in ppt end index is

// inclusive
      System.out.println(title1 +

address + substring);
     }
   }

// in PowerPoint you can assign a hyperlink to a shape without

text,
   // for example to a Line object. The code below demonstrates

how to
   // read such hyperlinks
   Shape[] sh = slide1[j].getShapes();
   for (int k = 0; k < sh.length; k++) {
    Hyperlink link = sh[k].getHyperlink();
    if (link != null) {
     String title1 = link.getTitle();
     String address = link.getAddress();
     System.out.println(title1 + address);
    }
   }
  }

// table data
  String[][] data = { { "INPUT FILE", "NUMBER OF RECORDS" },
    { "Item File", "11,559" }, { "Vendor File", "300" },
    { "Purchase History File", "10,000" },
    { "Total # of requisitions", "10,200,038" } };

// 创建表格
  Slide slide11 = ppt.createSlide();
  // create a table of 5 rows and 2 columns
  Table table = new Table(5, 2);
  for (int i = 0; i < data.length; i++) {
   for (int j = 0; j < data[i].length; j++) {
    TableCell cell = table.getCell(i, j);
    cell.setText(data[i][j]);

RichTextRun rt11 = cell.getTextRun

().getRichTextRuns()[0];
    rt11.setFontName("Arial");
    rt11.setFontSize(10);

cell.setVerticalAlignment(TextBox.AnchorMiddle);
    cell.setHorizontalAlignment(TextBox.AlignCenter);
   }
  }

// set table borders
  Line border = table.createBorder();
  border.setLineColor(Color.black);
  border.setLineWidth(1.0);
  table.setAllBorders(border);

// set width of the 1st column
  table.setColumnWidth(0, 300);
  // set width of the 2nd column
  table.setColumnWidth(1, 150);

slide11.addShape(table);
  table.moveTo(100, 100);

// retrieve embedded sounds 获取语音信息
  SoundData[] sound = ppt.getSoundData();
  for (int i = 0; i < sound.length; i++) {
   // save *WAV sounds on disk
   if (sound[i].getSoundType().equals(".WAV")) {
    FileOutputStream out1 = new FileOutputStream(
      sound[i].getSoundName());
    out1.write(sound[i].getData());
    out1.close();
   }
  }

ppt.write(out);
  out.close();
 }
}

poi3.9读写2007word、excel、ppt示例

主测试函数 TestMain.java
/**
 *
 */
package com.undergrowth.poi.test;

import com.undergrowth.poi.ExcelUtils;
import com.undergrowth.poi.PptUtils;
import com.undergrowth.poi.WordUtils;

/**
 * @author u1
 *
 */
public class TestMain {

/**
  * 1.对于word,使用XWPFDocument操作07以上的doc或者docx都没有问题,并且必须

是07或者以上的电脑上生成的word
  * 如果是WordExtractor或者HWPFDocument只能操作03以下的word,并且只能是03

以下电脑生成的word
  *
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String path="e:\\poi\\";
  String fileName="poi.docx";
  String filePath=path+fileName;
  //创建word
  //WordUtils.createWord(path,fileName);
  //写入数据
  String data="两国元首在亲切友好、相互信任的气氛中,就中乌关系现状

和发展前景,以及共同关心的国际和地区问题深入交换了意见,达成广泛共识。两国元首高度

评价中乌关系发展成果,指出建立和发展战略伙伴关系是正确的历史选择,拓展和深化双方各

领域合作具有广阔前景和巨大潜力,符合两国和两国人民的根本利益。";
  
  WordUtils.writeDataDocx(filePath,data);
  //WordUtils.writeDataDoc(filePath,data);
  
  //读取数据
  //String contentWord=WordUtils.readDataDoc(filePath);
  String contentWord=WordUtils.readDataDocx(filePath);
  System.out.println("word的内容为:\n"+contentWord);
  
  //创建excel
  fileName="poi.xlsx";
  filePath=path+fileName;
  String[] unitTitle={"google","baidu","oracle","合计"};
  String[] itemTitle={"单位","总收入","盈利","亏损"};
  String[] dataExcel={"10","20","30"};
  String title="各大公司收入情况";
  ExcelUtils.writeDataExcelx(filePath,dataExcel,title,unitTitle,itemTitle);
  
  //读取数据
  String contentExcel=ExcelUtils.readDataExcelx(filePath);
  System.out.println("\nexcel的内容为:\n"+contentExcel);
  
  //创建ppt
  fileName="poi.pptx";
  filePath=path+fileName;
  String titlePptx="华尔街纪录片";
  String imagePath="images/hej.jpg";
  PptUtils.writeDataPptx(filePath,titlePptx,imagePath);
  
  //读取pptx的数据
  String contentPptx=PptUtils.readDataPptx(filePath);
  System.out.println("\nppt的内容为:\n"+contentPptx);
 }

}

word操作工具  WordUtils.java
package com.undergrowth.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 * @author u1
 *
 */

public class WordUtils {

//创建.doc后缀的word
 public static void createWord(String path,String fileName) {
  // TODO Auto-generated method stub
  //判断目录是否存在
  File file=new File(path);
  if (!file.exists()) file.mkdirs();
  //因为HWPFDocument并没有提供公共的构造方法 所以没有办法构造word
  //这里使用word2007及以上的XWPFDocument来进行构造word
  XWPFDocument document=new XWPFDocument();
  OutputStream stream=null;
  try {
   stream = new FileOutputStream(new File(file, fileName));
   document.write(stream);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(stream!=null)
    try {
     stream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
  
  
 }

//向word中写入数据
 public static void writeDataDocx(String path,String data) {
  // TODO Auto-generated method stub
  InputStream istream=null;
  OutputStream ostream=null;
  try {
   //istream = new FileInputStream(path);
   ostream = new FileOutputStream(path);
   XWPFDocument document=new XWPFDocument();
   //添加一个段落
   XWPFParagraph p1=document.createParagraph();
   p1.setAlignment(ParagraphAlignment.CENTER);
   XWPFRun r1=p1.createRun();
   r1.setText(data);
   r1.setStrike(true);
   document.write(ostream);
   System.out.println("创建word成功");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(istream!=null)
    try {
     istream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   if(ostream!=null)
    try {
     ostream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
  
 }

//向word中写入数据
 public static void writeDataDoc(String path,String data) {
  // TODO Auto-generated method stub
  OutputStream ostream=null;
  try {
   ostream = new FileOutputStream(path);
   ostream.write(data.getBytes());
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(ostream!=null)
    try {
     ostream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
 }

//读取数据  97-03word
 public static String readDataDoc(String filePath) {
  // TODO Auto-generated method stub
  String content="";
  InputStream istream=null;
  try {
   istream = new FileInputStream(filePath);
   WordExtractor wordExtractor=new WordExtractor(istream);
   String[] para=wordExtractor.getParagraphText();
   for (String string : para) {
    content+=string;
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(istream!=null)
    try {
     istream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
  
  return content;
 }

//读取数据 docx
 public static String readDataDocx(String filePath) {
  // TODO Auto-generated method stub
  String content="";
  InputStream istream=null;
  try {
   istream = new FileInputStream(filePath);
       XWPFDocument document=new XWPFDocument(istream);
       content=document.getLastParagraph().getText();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(istream!=null)
    try {
     istream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }    
  return content;
 }

}

excel工具 ExcelUtils.java
package com.undergrowth.poi;

import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 * @author u1
 *
 */

public class ExcelUtils {

//创建xlsx
 public static void writeDataExcelx(String filePath, String[] dataExcel,
   String title,String[] unitTitle, String[] itemTitle) {
  // TODO Auto-generated method stub
  OutputStream ostream=null;
  try {
   ostream = new FileOutputStream(filePath);
   XSSFWorkbook excel=new XSSFWorkbook();
   XSSFSheet sheet0=excel.createSheet(title);
   //excel中第一行  poi中行、列开始都是以0开始计数
   //合并第一行 显示总标题  占据第一行的第一列到第15列
   sheet0.addMergedRegion(new CellRangeAddress(0, 0, 0, 15));
   XSSFRow row=sheet0.createRow(0);
   XSSFCell cell=row.createCell(0);
   cell.setCellValue(title);
   //设置样式
   XSSFCellStyle cellStyle=excel.createCellStyle();
   //居中对齐
   cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
   //字体
   XSSFFont font=excel.createFont();
   font.setFontHeightInPoints((short) 16);
   font.setColor(new XSSFColor(Color.RED));
   cellStyle.setFont(font);
   //设置第一行的样式
   cell.setCellStyle(cellStyle);
   
   //显示第二行 表头 各项标题
   row=sheet0.createRow(1);
   for (int i = 0; i < itemTitle.length; i++) {
    cell=row.createCell(i);
    cell.setCellValue(itemTitle[i]);
    cell.setCellStyle(cellStyle);
   }
   
   //从第三行开始显示 各大公司的数据
   int start=2;
   for (String unit : unitTitle) {
    row=sheet0.createRow(start);
    //第一列显示单位名称
    cell=row.createCell(0);
    cell.setCellValue(unit);
    //添加合计行
    if("合计".equals(unit)){
     for (int i = 0; i < dataExcel.length; i++) {
      cell=row.createCell(i+1);
      cell.setCellType

(XSSFCell.CELL_TYPE_FORMULA);
      char charaColumn=(char)('b'+i);
      String formula="sum

("+charaColumn+2+":"+charaColumn+start+")";
      cell.setCellFormula(formula);
     }
    }else { //添加数据行
     for (int i = 0; i < dataExcel.length; i++) {
      cell=row.createCell(i+1);
      cell.setCellType

(XSSFCell.CELL_TYPE_NUMERIC);
      cell.setCellValue(Double.valueOf

(dataExcel[i]));
     }
    }
    start++;
   }
   
   
   
   
   excel.write(ostream);
   System.out.println("创建excel成功");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(ostream!=null)
    try {
     ostream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
  
 }

//读取xlsx的数据
 public static String readDataExcelx(String filePath) {
  // TODO Auto-generated method stub
  String content="";
  try {
   OPCPackage pkg=OPCPackage.open(filePath);
   XSSFWorkbook excel=new XSSFWorkbook(pkg);
   //获取第一个sheet
   XSSFSheet 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()

==XSSFCell.CELL_TYPE_STRING) content+=cell.getStringCellValue()+"\t";
     else if(cell.getCellType()

==XSSFCell.CELL_TYPE_NUMERIC) content+=cell.getNumericCellValue()+"\t";
     else if(cell.getCellType()

==XSSFCell.CELL_TYPE_FORMULA) content+=cell.getCellFormula()+"\t";
    }
    content+="\n";
   }
    
   
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return content;
 }

}

ppt的工具 PptUtils.java
/**
 *
 */
package com.undergrowth.poi;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.XSLFSlideShow;
import org.apache.poi.xslf.usermodel.Placeholder;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.TextAlign;
import org.apache.poi.xslf.usermodel.TextDirection;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFGroupShape;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextBox;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

/**
 * @author u1
 *
 */
public class PptUtils {

//创建pptx
 public static void writeDataPptx(String filePath, String titlePptx,
   String imagePath) {
  // TODO Auto-generated method stub
  OutputStream ostream=null;
  try {
   ostream = new FileOutputStream(filePath);
   XMLSlideShow ppt=new XMLSlideShow();
   //ppt.setPageSize(new Dimension(500,400));
   //创建第一块ppt 放置图片
   XSLFSlide slide=ppt.createSlide();

/*
*如果PPTX没能显示出来,则可能是没有设置setAnchor
*如果不需要组合,可以直接用slide创建组件
*ppt.setSlideOrder(slide, newIndex)--这个方法可以指定PPT页放到*某个位置
*/
   XSLFGroupShape shape=slide.createGroup();
   
   //添加图片
   byte[] picData=IOUtils.toByteArray(new FileInputStream(imagePath));
   int pictureIndex=ppt.addPicture(picData, XSLFPictureData.PICTURE_TYPE_JPEG);
   shape.createPicture(pictureIndex);
   
   //第二张ppt 放置文本
   //创建文本框
   slide=ppt.createSlide();
   XSLFTextShape textShapeOnly=slide.createTextBox();
   textShapeOnly.setAnchor(new Rectangle(100, 100, 302, 302));
   textShapeOnly.setPlaceholder(Placeholder.TITLE);
   textShapeOnly.setText(titlePptx);
     
   //第三张ppt  放置标题和文本
   XSLFSlideMaster master=ppt.getSlideMasters()[0];
   XSLFSlideLayout layout=master.getLayout

(SlideLayout.TITLE_AND_CONTENT);
   slide=ppt.createSlide(layout);
   XSLFTextShape[] textShape=slide.getPlaceholders();
   XSLFTextShape textShape2=textShape[0];
   textShape2.setText(titlePptx);
   textShape2=textShape[1];
   //清除掉母版文本
   textShape2.clearText();
   XSLFTextParagraph

paragraph=textShape2.addNewTextParagraph();
   XSLFTextRun run=paragraph.addNewTextRun();
   run.setText("华尔街是纽约市曼哈顿区南部从百老汇路延伸到东

河的一条大街道的名字");
   run.setFontColor(Color.RED);
   run.setFontSize(20);
   paragraph=textShape2.addNewTextParagraph();
   run=paragraph.addNewTextRun();
   run.setText("“华尔街”一词现已超越这条街道本身,成为附近区

域的代称,亦可指对整个美国经济具有影响力的金融市场和金融机构。");
   run.setFontColor(Color.RED);
   run.setFontSize(20);
   
   ppt.write(ostream);
   
   System.out.println("创建pptx成功");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(ostream!=null)
    try {
     ostream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
 }

//读取pptx的内容
  public static String readDataPptx(String filePath) {
   // TODO Auto-generated method stub
   String content="";
   InputStream istream=null;
   try {
    istream = new FileInputStream(filePath);
    XMLSlideShow ppt=new XMLSlideShow(istream);
       for(XSLFSlide slide:ppt.getSlides()){ //遍历每一页ppt
        //content+=slide.getTitle()+"\t";
        for(XSLFShape shape:slide.getShapes()){
         if(shape instanceof XSLFTextShape){ //获取

到ppt的文本信息
          for(Iterator iterator=

((XSLFTextShape) shape).iterator();iterator.hasNext();){
          //获取到每一段的文本信息
           XSLFTextParagraph

paragraph=(XSLFTextParagraph) iterator.next();
           for (XSLFTextRun

xslfTextRun : paragraph) {

content+=xslfTextRun.getText()+"\t";
        }
          }
         }
        }
        //获取一张ppt的内容后 换行
        content+="\n";
       }
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }finally{
    if(istream!=null)
     try {
      istream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch

block
      e.printStackTrace();
     }
   }    
   return content;
  }
}

项目结构图:

效果图:

控制台输出:

创建word成功
word的内容为:
两国元首在亲切友好、相互信任的气氛中,就中乌关系现状和发展前景,以及共同关心的国际和地区问题深入交换了意见,达成广泛共识。两国元首高度评价中乌关系发展成果,指出建立和发展战略伙伴关系是正确的历史选择,拓展和深化双方各领域合作具有广阔前景和巨大潜力,符合两国和两国人民的根本利益。
创建excel成功

excel的内容为:
各大公司收入情况 
单位 总收入 盈利 亏损 
google 10.0 20.0 30.0 
baidu 10.0 20.0 30.0 
oracle 10.0 20.0 30.0 
合计 sum(b2:b5) sum(c2:c5) sum(d2:d5)

创建pptx成功

ppt的内容为:

华尔街纪录片 
华尔街纪录片 华尔街是纽约市曼哈顿区南部从百老汇路延伸到东河的一条大街道的名字 “华尔街”一词现已超越这条街道本身,成为附近区域的代称,亦可指对整个美国经济具有影响力的金融市场和金融机构。

poi操作PPT文档总结相关推荐

  1. 使用poi操作word文档实现套打功能

    使用poi操作word文档实现套打功能 本文目的是为了分享一个实现套打功能,但是不同于简单的word的文本替换而是采用poi对word的文本框就行操作实现的功能: poi中各种jar的说明 套打的实现 ...

  2. poi操作word文档总结

    POI分段落生成纯Word动态模板并导入数据 导出数据,可以用word另存为xml格式的ftl文件,变量用${变量名}表示,然后在类中通过 freemarker去替换变量. 但是怎么导入word数据. ...

  3. POI操作Word文档工具

    POI操作Word文档工具 1.POI简单介绍 2.POI操作Word文档基本方法 3.POI操作Word文档基本方法应用 4.POI操作Word文档工具类 1.POI简单介绍 POIFS(可疑混淆执 ...

  4. Poi 操作Word文档设置页边距 解决CTPageMar类找不到

    Poi操作Word文档设置页边距 CTPageMar类找不到 已解决 在百度上搜了一顿,找到了相关的解决方案,但是缺失了一个类,在百度怎么也找不到! 给大家一个参考数据 1厘米≈567 CTSectP ...

  5. Java实战—POI操作Excel文档、读取、写入、合并单元格

    一.POI项目简介 POI全称 Poor Obfuscation Implementation,利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能.官网:http: ...

  6. 史上最全的Python操作 “PPT” 文档大全,以后写“数据分析报告”靠她了!

    ↑↑↑关注后"星标"简说Python 人人都可以简单入门Python.爬虫.数据分析 简说Python严选 来源:数据分析与统计学之美    作者:黄伟呢 One old watc ...

  7. java poi预览word文档_apache poi操作office文档----java在线预览txt、word、ppt、execel,pdf代码...

    在页面上显示各种文档中的内容.在servlet中的逻辑 word: BufferedInputStream bis = null; URL url = null; HttpURLConnection ...

  8. poi处理word内容的公式_利用poi操作word文档

    关键字:POI JAVA 批注 总页数 总字符数 一:认识POI Apache POI是一个开源的利用Java读写Excel.WORD等微软OLE2组件文档的项目.最新的3.5版本有很多改进,加入了对 ...

  9. 利用poi操作word文档(针对docx格式)

    一:认识POI  Apache POI是一个开源的利用Java读写Excel.WORD等微软OLE2组件文档的项目.最新的3.5版本有很多改进,加入了对采用OOXML格式的Office 2007支持, ...

最新文章

  1. OLAP和OLTP的区别(基础知识)
  2. python爬虫 发送定时气象预报
  3. 网站内链为什么要做上下文链接?对网站优化有什么帮助?
  4. 一些关于流量和带宽的知识
  5. ASP.NET2.0 - ASP.net MVC和ASP.net Web Forms
  6. JAVA 的读取Excel方法_纯Java的方式读取excel2007
  7. html css js调用dll,js调用Activex的dll
  8. SAP UI5 js file will be executed immediately after downloaded successfully
  9. 继承BaseAdapter自定义ListView
  10. c/c++中的引用变量
  11. 在WPF里面实现以鼠标位置为中心缩放移动图片
  12. 怎样用计算机进入手机驱动,电脑没有手机驱动_怎么安装手机驱动_好特教程
  13. spring注解@Lazy
  14. gcc 中-O1 -O2 -O3 优化的原理
  15. (三)基础网络演进、分类与定位的权衡
  16. catch小说内容-从gui到爬虫(2)
  17. 优化 | 浅谈旅行商(TSP)的七种整数规划模型
  18. 一年节省费用100万,AI导航误差不到1米,杭州奥体“大小莲花”智慧场馆大揭秘...
  19. 基于人性的量化交易:期货的反向跟单交易软件系统
  20. EAP通讯基础之SECS/GEM/GEM300mm

热门文章

  1. 软件测试工程师必备技能:谈谈软件项目中的评审
  2. vim java开发环境配置_搭建vim作为java开发环境(-)
  3. 【学习】IXP:Internet Exchange Point
  4. 什么是spring以及为什么要使用 spring?
  5. Android发展简介
  6. python asyncio.sleep_Python asyncio 模块
  7. 公路施工过程中作业重点和技术完善
  8. js----SVG转PNG
  9. 数据库 函数依赖集闭包的算法
  10. 程序员生存定律[八] 借势的价值和力量