POI之心得

寫本文之前,真想哭一場,昨晚在公司加班,花了半小時把博文已經寫好了,當我點擊提交按鈕后,出現了讓我淚奔的一幕.公司關閉了服務器,我辛苦寫的直接化為虛無,早知道這該寫保存在本地,然後上傳-------此是閒話

 

      公司因為最近需要進行一些報表開發.前期是用JXI做報表,因為開發后的效果不理想,主要是JXl對公式支持不好,因此老大決定重寫開發.有兩個方法,一是:利用Excel的VBA編程,我用了三天熟悉了它的基本操作,心得在我的前一博文中.二是:利用Apache組織開發的POI開源項目 進行開發報表.後因為VBA的可移植性和安全性欠佳,而放棄了,我個人覺得如果公司規模不大,完全可以利用vba進行報表的打印輸出.因為它是基於Excel的平臺上運行,也可以說是專門為Excel開發的一種語言.執行效率高.

言歸正傳,說說POI,在官網上對于POI的解釋是這樣的.

      The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using Java. Apache POI is your Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and OLE2 formats 

 

     意思是說POI是java進行Excel,work,xml等文件的,開發,操作,維護的一個開源項目.我現在主要接觸的是基於Excel的操作.

      要開發Excel首先需要在http://poi.apache.org/下載POI的jar包 ,具體操作就不描述了,我下載了開發包 以及它的源碼.引用的 jar包為: poi-3.8-beta1-20110307.jar 它依賴的jar包為:commons-logging-1.1.jar;  junit-3.8.1.jar  ; log4j-1.2.13.jar;

    引入后請看第一個實例:

 

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 
 * @author Michael.Yang
 * @help test excel formula
 *
 */
public class NewExcel {
	
	public static void main(String args[]){
	Workbook workbook = new HSSFWorkbook();//創建工作簿
	
	Sheet sheet1 = workbook.createSheet("sheet1");//創建第一業
	
	Row row_first =sheet1.createRow(0);//創建第一行
	Cell cell_test=null;
       for(int i=0;i<4;i++){
     	   cell_test= row_first.createCell(i);//創建表格
     	   cell_test.setCellType(Cell.CELL_TYPE_NUMERIC);//設置表格的類型
     	   cell_test.setCellValue(2+i);//設置值
        }
    Cell cell_fourth =row_first.createCell(4);
    cell_fourth.setCellType(Cell.CELL_TYPE_FORMULA);
    cell_fourth.setCellFormula("Sum(A1:D4)");//設置函數
    
    Cell cell_fifth =row_first.createCell(5);
    cell_fifth.setCellType(Cell.CELL_TYPE_FORMULA);
    cell_fifth.setCellFormula("Average(A1:D4)");//設置函數
    File file = new File("D:\\test_example.xls");//輸出的地址
    if(file.exists()){
   	 file.delete();
    }
    FileOutputStream fileOut;
	try {
		fileOut = new FileOutputStream(file);
		workbook.write(fileOut);
		fileOut.close();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
	
	}
}

明天繼續.......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值