1. 程式人生 > >poi3.9之讀寫2010 word/excel/ppt

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的內容為:

華爾街紀錄片	
華爾街紀錄片	華爾街是紐約市曼哈頓區南部從百老匯路延伸到東河的一條大街道的名字	“華爾街”一詞現已超越這條街道本身,成為附近區域的代稱,亦可指對整個美國經濟具有影響力的金融市場和金融機構。