1,所需包 jxl.jar
2 列子
package com.excel;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
public class WriterExcel {
public void writer(String path){
WritableWorkbook workBook = null;
WritableSheet sheet = null;
try{
//如果有模板
if(path != null){
Workbook workbook = Workbook.getWorkbook(new File(path));
workBook = Workbook.createWorkbook(new FileOutputStream("C:\\aa.xls"),workbook);
sheet = workBook.getSheet(0);
}else{
//建立工作文件
workBook = Workbook.createWorkbook(new FileOutputStream("C:\\aa.xls"));
//如果文件存在,則在文件裡加入sheet
sheet = workBook.createSheet("sheet1", 0);
}
/**
* 寫入數據
*/
//添加字符
WritableFont wFont = new WritableFont(WritableFont.TIMES,18,WritableFont.BOLD,true);
WritableCellFormat wFormat = new WritableCellFormat(wFont);
Label label = new Label(1,1,"我是不個格子",wFormat);
sheet.addCell(label);
//添加數字
NumberFormat nFormat = new NumberFormat("#.##");
WritableCellFormat nwFormat = new WritableCellFormat(nFormat);
Number label2 = new Number(3,1,3.123456,nwFormat);//第3列第1行
sheet.addCell(label2);
//添加boolean
Boolean labelBo = new Boolean(4,3,false);
sheet.addCell(labelBo);
//sheet.mergeCells(0, 0, 2, 1);//合並單無單,從第0列0行 到 第2列1行
//添加日期
DateTime labelTime = new DateTime(0,3,new Date());
sheet.addCell(labelTime);
//添加字體顏色
WritableFont wlFont = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.RED);
WritableCellFormat wlc = new WritableCellFormat(wlFont);
Label wlcLabel = new Label(0,4,"你好呀",wlc);
sheet.addCell(wlcLabel);
//寫入
workBook.write();
workBook.close();
}catch(Exception e){}
}
public static void main(String[] args){
WriterExcel xls = new WriterExcel();
//xls.writer("c:\\bb.xls");
xls.reader("c:\\cc.xls");
}
/**
* 讀取
* @param path
*/
public void reader(String path){
List list = new ArrayList();
try{
//得到excel
Workbook workBook = Workbook.getWorkbook(new File(path));
Sheet sheet = workBook.getSheet(0);//從第0行開始讀
int totalRows = sheet.getRows();
int totalcol = sheet.getColumns();
for(int i = 0; i < totalRows; i++){
Object[] clos = new Object[totalcol];
for(int j = 0; j < totalcol; j++){
Cell cell = sheet.getCell(j,i);//行 列
String value = cell.getContents();
clos[j] = value;
}
list.add(clos);
}
}catch(Exception e){}
/**
* 輸出
*/
for(int i = 0; i < list.size(); i++){
Object[] obj = (Object[])list.get(i);
for(int j = 0; j < obj.length; j++){
System.out.print(obj[j]+"\t");
}
System.out.println();
}
}
}