poi3.9之读写2010 word/excel/ppt
poi是java的api用来操作微软的文档
poi的jar包和功能映射如下:
本文是以poi3.9读写2010word、2010excel、2010ppt,记录学习的脚步
相应的功能在代码都有注释,就不解释了 详情可以参看poi3.9的文档
主测试函数 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();
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的内容为: 华尔街纪录片 华尔街纪录片 华尔街是纽约市曼哈顿区南部从百老汇路延伸到东河的一条大街道的名字 “华尔街”一词现已超越这条街道本身,成为附近区域的代称,亦可指对整个美国经济具有影响力的金融市场和金融机构。
posted on 2013-12-10 21:13 liangxinzhi 阅读(622) 评论(0) 收藏 举报
浙公网安备 33010602011771号