import java.io.File;
import java.util.*;
import jxl.*;
import jxl.write.*;
/**
* <p>Title: 操作EXCEL文件</p>
* <p>Description: 本實例演示使用jxl包實現對excel文件的操作</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: myExcel.java</p>
* @version 1.0
*/
public class myExcel{
Workbook workbook;
Sheet sheet;
/**
*<br>方法說明:寫入文件操作
*<br>輸入參數:
*<br>返回類型:
*/
public void write(){
try{
//創建一個可寫入的excel文件對象
WritableWorkbook workbook = Workbook.createWorkbook(new File("myfile.xls"));
//使用第一張工作表,將其命名為“午餐記錄”
WritableSheet sheet = workbook.createSheet("午餐記錄", 0);
//表頭
Label label0 = new Label(0, 0, "時間");
sheet.addCell(label0);
Label label1 = new Label(1, 0, "姓名");
sheet.addCell(label1);
Label label2 = new Label(2, 0, "午餐標准");
sheet.addCell(label2);
Label label3 = new Label(3, 0, "實際費用");
sheet.addCell(label3);
//格式化日期
jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-dd-MM hh:mm:ss");
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(0, 1, new java.util.Date(), wcfDF);
sheet.addCell(labelDTF);
//普通字符
Label labelCFC = new Label(1, 1, "riverwind");
sheet.addCell(labelCFC);
//格式化數字
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
WritableCellFormat wcfN = new WritableCellFormat(nf);
jxl.write.Number labelNF = new jxl.write.Number(2, 1, 13.1415926, wcfN);
sheet.addCell(labelNF);
jxl.write.Number labelNNF = new jxl.write.Number(3, 1, 10.50001, wcfN);
sheet.addCell(labelNNF);
//關閉對象,釋放資源
workbook.write();
workbook.close();
}catch(Exception e){
System.out.println(e);
}
}
/**
*<br>方法說明:讀取excel文件一行數據
*<br>輸入參數:int row指定的行數
*<br>返回類型:String〔〕結果數組
*/
public String[] readLine(int row){
try{
//獲取數據表列數
int colnum = sheet.getColumns();
String[] rest = new String[colnum];
for(int i = 0; i < colnum; i++){
String sTemp = read(i,row);
if(sTemp!=null)
rest[i] = sTemp;
}
return rest;
}catch(Exception e){
System.out.println("readLine err:"+e);
workbook.close();
return null;
}
}
/**
*<br>方法說明:讀取excel的指定單元數據
*<br>輸入參數:
*<br>返回類型:
*/
public String read(int col, int row){
try{
//獲得單元數據
Cell a2 = sheet.getCell(col,row);
String rest = a2.getContents();
return rest;
}catch(Exception e){
System.out.println("read err:"+e);
workbook.close();
return null;
}
}
/**
*<br>方法說明:主方法,演示程序用
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] arges){
try{
myExcel me = new myExcel();
//生成一個可讀取的excel文件對象
me.workbook = Workbook.getWorkbook(new File("myfile.xls"));
//使用第一個工作表
me.sheet = me.workbook.getSheet(0);
//讀一行記錄,並顯示出來
String[] ssTemp = me.readLine(1);
for(int i=0;i<ssTemp.length;i++)
System.out.println(ssTemp[i]);
//寫入數據
me.write();
me.workbook.close();
}catch(Exception e){
System.out.println(e);
}
}
}