1. 程式人生 > >Java 操作 Excel (讀取Excel2003 2007,Poi實現)

Java 操作 Excel (讀取Excel2003 2007,Poi實現)

一. Apache POI 簡介( http://poi.apache.org/)

    使用Java程式讀寫Microsoft Office,提供了下面這幾種型別:

    HSSF-提供讀寫Microsoft Excel XLS格式檔案的功能。
    XSSF-提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
    HWPF-提供讀寫Microsoft Word DOC格式檔案的功能。
    HSLF- 供讀寫Microsoft PowerPoint格式檔案的功能。
    HDGF-提供讀Microsoft Visio格式檔案的功能。
    HPBF-提供讀Microsoft Publisher格式檔案的功能。


二、POI操作Excel


    1. 官方快速幫助:http://poi.apache.org/spreadsheet/quick-guide.html

    2. HSSF匯入包:poi-3.10-FINAL.jar

        XSSF 匯入包 poi-ooxml-3.10-FINAL.jar,使用maven會自動匯入poi-ooxml-schema

        example 包: poi-examples-3.10-FINAL.jar

	<dependency>
		  <groupId>org.apache.poi</groupId>
		  <artifactId>poi</artifactId>
		  <version>3.10-FINAL</version>
		</dependency>
		<dependency>
		  <groupId>org.apache.poi</groupId>
		  <artifactId>poi-ooxml</artifactId>
		  <version>3.10-FINAL</version>
		</dependency>
		<dependency>
		  <groupId>org.apache.poi</groupId>
		  <artifactId>poi-examples</artifactId>
		  <version>3.10-FINAL</version>
		</dependency>



參考:



    1. http://www.blogjava.net/vwpolo/archive/2009/09/16/295243.html

    2. http://hacker-zxf.iteye.com/blog/746546

    3. http://zmx.iteye.com/blog/622536

    4. http://canfly2010.iteye.com/blog/701726

package excel.poi;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;

import org.apache.poi.POITextExtractor;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.XmlException;
public class ReadExcel {
	/**
	 * 讀取office 2003 xls
	 * @param filePath
	 */
 @SuppressWarnings({ "unchecked", "deprecation" })
public void loadXls(String filePath){
	  try {
		   InputStream input = new FileInputStream("D:\\資料\\文件一期\\xls\\082010 鳳鳴軒書單.xls");
		   POIFSFileSystem fs = new POIFSFileSystem(input);
		   HSSFWorkbook wb = new HSSFWorkbook(fs);
		   HSSFSheet sheet = wb.getSheetAt(0);
		   // Iterate over each row in the sheet
		   Iterator rows = sheet.rowIterator();
		   while (rows.hasNext()) {
		    HSSFRow row = (HSSFRow) rows.next();
		    System.out.println("Row #" + row.getRowNum());
		    // Iterate over each cell in the row and print out the cell"s
		    // content
		    Iterator cells = row.cellIterator();
		    while (cells.hasNext()) {
		     HSSFCell cell = (HSSFCell) cells.next();
		     System.out.println("Cell #" + cell.getCellNum());
		     switch (cell.getCellType()) {
		     case HSSFCell.CELL_TYPE_NUMERIC:
		      System.out.println(cell.getNumericCellValue());
		      break;
		     case HSSFCell.CELL_TYPE_STRING:
		      System.out.println(cell.getStringCellValue());
		      break;
		     case HSSFCell.CELL_TYPE_BOOLEAN:
		      System.out.println(cell.getBooleanCellValue());
		      break;
		     case HSSFCell.CELL_TYPE_FORMULA:
		      System.out.println(cell.getCellFormula());
		      break;
		     default:
		      System.out.println("unsuported sell type");
		      break;
		     }
		    }
		   }
		  } catch (IOException ex) {
		   ex.printStackTrace();
		  }
 }
 /**
  * 讀取xlsx文字
  * @param filePath
  */
 public void loadXlsxText(String filePath){
	 File inputFile = new File("D:\\test.xlsx");   
	 try {
		POITextExtractor extractor = ExtractorFactory.createExtractor(inputFile);
		System.out.println(extractor.getText());
	} catch (InvalidFormatException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (OpenXML4JException e) {
		e.printStackTrace();
	} catch (XmlException e) {
		e.printStackTrace();
	}   
 }
 /**
  * 讀取office 2007 xlsx
  * @param filePath
  */
 public void loadXlsx(String filePath){
	 // 構造 XSSFWorkbook 物件,strPath 傳入檔案路徑   
	XSSFWorkbook xwb = null;
	try {
		xwb = new XSSFWorkbook("D:\\text.xlsx");
	} catch (IOException e) {
		System.out.println("讀取檔案出錯");
		e.printStackTrace();
	}   
	 // 讀取第一章表格內容   
	 XSSFSheet sheet = xwb.getSheetAt(0);   
	// 定義 row、cell   
	 XSSFRow row;   
	 String cell;   
	 // 迴圈輸出表格中的內容   
	 for (int i = sheet.getFirstRowNum()+1; i < sheet.getPhysicalNumberOfRows(); i++) {   
	     row = sheet.getRow(i); 
	     for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {   
	        // 通過 row.getCell(j).toString() 獲取單元格內容,   
	    	 if (j==1&&i!=0) {
	    		 cell = row.getCell(j).getDateCellValue().toLocaleString();
			}else {
				cell = row.getCell(j).toString();
			}
	        /* //獲取字型和背景顏色
	        String rgbShort=row.getCell(j).getCellStyle().getFont().getCTFont().getColorArray()[0].xmlText();
	        rgbShort=ReadExcel.substringBetween(rgbShort, "rgb=\"","\"/>");
	        String rgbShort=row.getCell(j).getCellStyle().getFillBackgroundXSSFColor().getCTColor().toString();
	        Color color=new Color(Color.BLUE.getRGB());
	        System.out.print(cell +",index:"+rgbShort+" red:"+color.getRed()+" blue:"+color.getBlue()+"\t");   */
	        System.out.print(cell +"\t");   
	    }   
	     System.out.println("");   
	 }    
 }
/**
 * HSSF 寫入excel xls 格式
 * @param filePath
 * @throws IOException
 */
 public void writeXls(String filePath)throws IOException{
	 //工作簿 23.
	 HSSFWorkbook hssfworkbook=new HSSFWorkbook(); 
	 //建立sheet頁 25.
	 HSSFSheet hssfsheet=hssfworkbook.createSheet();
	 //sheet名稱
	 hssfworkbook.setSheetName(0,"研發部門"); 
	 //取得第一行 29.
	 HSSFRow hssfrow=hssfsheet.createRow(0); 
	 //建立第一個單元格並處理亂碼 31.
	 HSSFCell hssfcell_0=hssfrow.createCell((short)0); 
	 //hssfcell_0.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
	 //對第一個單元格賦值 34.
	 hssfcell_0.setCellValue("研發工程師1"); 
	 //日期單元格格式處理
	 HSSFCellStyle hssfcellstyle=hssfworkbook.createCellStyle();
	 //m/d/yyh:mm 39.
	 hssfcellstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); 
	 //建立第二個單元格 41.
	 HSSFCell hssfcell_1=hssfrow.createCell((short)1); 
	 hssfcell_1.setCellValue(new Date()); 
	 hssfcell_1.setCellStyle(hssfcellstyle);
	 hssfrow.createCell((short)2).setCellValue(true); 
	 hssfrow.createCell((short)3).setCellValue(122.00); 
	 //輸出 49.
	 FileOutputStream fileoutputstream=new FileOutputStream("d:\\exceltext.xls"); 
	 hssfworkbook.write(fileoutputstream);
	 fileoutputstream.close();
 }
 @SuppressWarnings("static-access")
public void writeXlsx(String filePath)throws IOException{
	 //工作簿
	 XSSFWorkbook hssfworkbook=new XSSFWorkbook();
	//獲得CreationHelper物件,這個應該是一個幫助類   
	 XSSFCreationHelper helper=hssfworkbook.getCreationHelper();
	 //建立sheet頁
	 XSSFSheet hssfsheet=hssfworkbook.createSheet();
	 //設定sheet名稱
	 hssfworkbook.setSheetName(0,"我的測試sheet"); 
	 //取得第一行 
	 XSSFRow firstRow=hssfsheet.createRow(0); 
	 //建立第一個單元格
	 XSSFCell hssfcell_0=firstRow.createCell(0); 
	 //hssfcell_0.setEncoding(HSSFWorkbook.ENCODING_UTF_16);並處理亂碼
	 //對第一個單元格賦值 
	 hssfcell_0.setCellValue("名稱"); 
	 //建立第二個單元格 
	 XSSFCell hssfcell_1=firstRow.createCell(1); 
	 hssfcell_1.setCellValue("建立日期"); 
	 //日期單元格格式處理
	 XSSFCellStyle dateCellStyle=hssfworkbook.createCellStyle();
	 //m/d/yyh:mm 設定日期格式
	 dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss")); 
	 dateCellStyle=ReadExcel.setFillBackgroundColors(dateCellStyle, IndexedColors.BLACK.getIndex(), IndexedColors.YELLOW.getIndex(), dateCellStyle.SOLID_FOREGROUND);
	 //設定其他標題
	 firstRow.createCell(2).setCellValue("使用者"); 
	 firstRow.createCell(3).setCellValue("備註");
	 
	 //寫入所有內容行
	 for (int rowInt = 1; rowInt < 10; rowInt++) {
		XSSFRow row =hssfsheet.createRow(rowInt);
		XSSFCell cell_0=row.createCell(0);  
		cell_0.setCellValue("劉伯恩");
		XSSFCell cell_1=row.createCell(1);  
		cell_1.setCellValue(new Date());
		cell_1.setCellStyle(dateCellStyle);
		XSSFCell cell_2=row.createCell(2);  
		cell_2.setCellValue("超級會員");
		XSSFCell cell_3=row.createCell(3);  
		cell_3.setCellValue("這裡是備註資訊");
		
	}
	 //輸出 49.
	 FileOutputStream fileoutputstream=new FileOutputStream("d:\\exceltext.xlsx"); 
	 hssfworkbook.write(fileoutputstream);
	 fileoutputstream.close();
 }
    /**  
     * 前景和背景填充的著色  
     * @param cellStyle  
     * @param bg IndexedColors.ORANGE.getIndex();  
     * @param fg IndexedColors.ORANGE.getIndex();  
     * @param fp CellStyle.SOLID_FOREGROUND  
     * @return  
     */  
    public static XSSFCellStyle setFillBackgroundColors(XSSFCellStyle cellStyle,short bg,short fg,short fp){   
        cellStyle.setFillBackgroundColor(bg);   
        cellStyle.setFillForegroundColor(fg);   
        cellStyle.setFillPattern(fp);   
        return cellStyle;   
    }   
 public static void main(String[] args) {
	 ReadExcel readExcel =new ReadExcel();
	/*	try {
			readExcel.writeXlsx("");
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	 readExcel.loadXls("");
 }

 
}



xls寫入圖片

	public static void main(String[] args) {
		FileOutputStream fileOut = null;
		BufferedImage bufferImg = null;
		BufferedImage bufferImg1 = null;
		try {

			// 先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
			ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
			ByteArrayOutputStream byteArrayOut1 = new ByteArrayOutputStream();
			bufferImg = ImageIO.read(new File("C:/tmp/img/test.jpg"));
			bufferImg1 = ImageIO.read(new File("C:/tmp/img/test2.jpg"));
			ImageIO.write(bufferImg, "jpg", byteArrayOut);
			ImageIO.write(bufferImg1, "jpg", byteArrayOut1);

			// 建立一個工作薄
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet1 = wb.createSheet("new sheet");
			// HSSFRow row = sheet1.createRow(2);
			HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
			HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 512, 255,(short) 0, 0, (short) 10, 10);
			HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 512, 255,(short) 2, 2, (short) 2, 3);
			anchor1.setAnchorType(2);
			// 插入圖片
			patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
			patriarch.createPicture(anchor1, wb.addPicture(byteArrayOut1.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

			fileOut = new FileOutputStream("C:/tmp/img/test2.xls");
			// 寫入excel檔案
			wb.write(fileOut);
			fileOut.close();

		} catch (IOException io) {
			io.printStackTrace();
			System.out.println("io erorr :  " + io.getMessage());
		} finally {
			if (fileOut != null) {

				try {
					fileOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}