當前位置:才華齋>計算機>java語言>

Java中操作Excel表格方法

java語言 閱讀(2.08W)

引導語:我們都知道Excel 可以進行各種資料的處理、統計分析和輔助決策操作,那麼在Java中又是如何操作Excel 表格的呢,以下是本站小編分享給大家的Java中操作Excel表格方法,歡迎閱讀!

Java中操作Excel表格方法

利用Java Excel API ,下載地址:

下面給出一段讀取資料的例子程式碼

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package excel;

import InputStream;

import NotFoundException;

import ception;

import tStream;

import l;

import er;

import ;

import t;

import book;

import Exception;

/**

*

* @author

*/

public class Main {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

try {

InputStream is = new FileInputStream("d:");

book rwb = orkbook(is);

Sheet rs = heet(0);

//取第一行,第一列的元素

Cell c00 = ell(0, 0);

String strc00 = ontents();

//取第一行,第二列的元素

Cell c10 = ell(1,0);

String strc10= ontents();

tln(strc00+" "+ype()ring());

tln(strc10+" "+ype()ring());

//獲取sheet的個數

tln(umberOfSheets());

Sheet [] sheets =heets();

for(int i=0;i

tln(heet(i)ame());

}

//獲得列數

tln(heet(0)olumns());

//獲得每列的.元素

Cell [] cell = heet(0)olumn(0);

//獲得總行數

tln(heet(0)ows());

//獲得行元素

Cell [] cell2 = heet(0)ow(0);

//關閉物件

e();

} catch (Exception ex) {

ogger(ame())(RE, null, ex);

}

}

}

再給出一段,建立Excel表格的程式碼:

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package excel;

import ;

import l;

import er;

import book;

import l;

import ableCellFormat;

import ableFont;

import ableSheet;

import ableWorkbook;

import er;

/**

*

* @author

*/

public class Main {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

try {

//建立EXCEL表格

WritableWorkbook wwb = teWorkbook(new File("d:"));

//建立工作表

WritableSheet ws = teSheet("",0);

//建立單元格

ell(new Label(0,0,"Hello World"));

//新增設定字型格式的單元格

WritableFont wfc = new WritableFont(L,15,,true);

WritableCellFormat wcff= new WritableCellFormat(wfc);

Label labelcf = new Label(1,0,"Format text",wcff);

ell(labelcf);

//向單元格中寫入數字

Number labelN = new Number(0,1,12345);

ell(labelN);

e();

e();

} catch (Exception ex) {

ogger(ame())(RE, null, ex);

}

}

}

最後給出一段更新表格的程式碼:

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package excel;

import ;

import ception;

import l;

import er;

import Type;

import book;

import Exception;

import l;

import ableCell;

import ableSheet;

import ableWorkbook;

/**

*

* @author

*/

public class Main {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

try {

Workbook rw = orkbook(new File("d:"));

WritableWorkbook wwb = teWorkbook(new File("d:"),rw);

//修改單元格的值

WritableSheet ws = heet(0);

WritableCell wc = ritableCell(0,0);

if(ype() == L){

Label l= (Label)wc;

tring("Modified!!!");

}

e();

e();

e();

} catch (Exception ex) {

ogger(ame())(RE, null, ex);

}

}

}