赫赫,每天都有进步!!!! 希望大家指点^_^
/**
* @author snowfox
* @version 1.0
* @since 2007-8-2
*/
package com.heyi.test;
import java.io.IOException;
import java.io.File;
import jxl.DateCell;
import jxl.NumberCell;
import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableFont;
import jxl.CellType;
public class TestExcel {
public static void main(String[] args) {
TestExcel.readExcel(new File("D:/temp/进出口流程数据结构.xls"));
// TestExcel.writeExcel(new File("D:/temp/进出口流程数据结构.xls"));
}
// getCell(x,y)x 为列,y为行;
// 对excel操作下标从0开始
// 使用cell.getcontent.equals("")判断单元格是否为空
public static void readExcel(File file) {
try {
Workbook wb = Workbook.getWorkbook(file);
Sheet sheet = wb.getSheet(0);
Cell cell = sheet.getCell(1,1);
if(cell.getContents().equals("")){
System.out.println(cell.getContents().toString()+" is empty ! ");
}
if(cell.getType()==CellType.NUMBER){
jxl.NumberCell nc = (NumberCell) sheet.getCell(0,2);
System.out.println(nc.getContents()+nc.getColumn());
}
Cell cell03 = sheet.getCell(0,3);
if(cell03.getType()==CellType.DATE){
jxl.DateCell datecell = (DateCell) cell03;
System.out.println(datecell.getContents()+"***"+datecell.getRow());
}
System.out.println(sheet.getColumns()+"***"+sheet.getRows());// get current sheet total rows and total column
System.out.println(sheet.getName()+"***"+sheet.getSettings().getZoomFactor());
int irow = sheet.getRows();
int icolumns = sheet.getColumns();
jxl.Cell tempCell = null;
for(int i = 0 ;i<irow ; i++){
for(int j=0; j< icolumns ;j++){
tempCell = sheet.getCell(i, j);
if(! tempCell.getContents().equals("")){
System.out.println("cell : " + tempCell.getContents());
}
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 如果已存在excel表,不能写入,可以考虑先读取文件,然后删除,最后重新建改excel文件
// 使用label对象写单元格位置和内容,可以使用单元格格式设置如下WritableFont,WritableCellFormat两个类,label继承cell类
// 使用WritableWorkbook.createSheet("japanese", 1)创建sheet
// 单元格创建完之后,添加到某个sheet上
// 最后写入到workbook里,关闭workbook。
// note:当excel在windows下打开时,程序不能写入信息
public static void writeExcel(File file) {
try {
jxl.write.WritableWorkbook writeBook = Workbook.createWorkbook(file);
jxl.write.WritableSheet writeSheet = writeBook.createSheet("japanese", 1);
jxl.write.Label label = new jxl.write.Label(1,1,"我本善良");
writeSheet.addCell(label);
jxl.write.WritableFont font = new jxl.write.WritableFont(WritableFont.ARIAL,20,WritableFont.BOLD,false,jxl.format.UnderlineStyle.DOUBLE,jxl.format.Colour.GREEN);
jxl.write.WritableCellFormat format = new jxl.write.WritableCellFormat(font);
jxl.write.Label label1 = new Label(2,2,"幸福渴望不可及",format);
writeSheet.addCell(label1);
writeBook.write();
writeBook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}