Java讀取Execl中的內容
讀取execl檔案的方法很多,現在介紹一種最簡單的方法,用jxl來讀取,下面是測試程式碼:
package File;
import java.io.File;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
public class ExeclReader
{
public static void main(String[] args)
{
Workbook workbook = null;
Sheet sheet =null;
Cell cell = null;
try {
workbook = Workbook.getWorkbook(new File("D:/Backup/我的文件/12.xls"));
} catch (Exception e) {
try {
throw new Exception("file to import not found!");
} catch (Exception e1) {
e1.printStackTrace();
}
}
sheet= workbook.getSheet(0);
int columnCount=sheet.getColumns();
int rowCount=sheet.getRows();
for (int i = 0; i <rowCount; i++) {
for (int j = 0; j <columnCount; j++) {//注意,這裡的兩個引數,第一個是表示列的,第二才表示行
cell=sheet.getCell(j, i); //要根據單元格的型別分別做處理,否則格式化過的內容可能會不正確
if(cell.getType()==CellType.NUMBER){
System.out.print(((NumberCell)cell).getValue());
}
else if(cell.getType()==CellType.DATE){
System.out.print(((DateCell)cell).getDate());
}
else{
System.out.print(cell.getContents());
}
//System.out.print(cell.getContents());
System.out.print("/t");
}
System.out.print("/n");
}
//關閉它,否則會有記憶體洩露
workbook.close();
}
}