创建EXCEL文件:
public void createXLS()
{
try
{
//打开文件
WritableWorkbook book=
Workbook.createWorkbook(new File("JAVA生成EXCEL测试.xls"));
//生成名为"第一页"的工作表,参数0表示这是第一页
WritableSheet sheet=book.createSheet("第一页",0);
//设置字体为宋体,16号字,加粗,颜色为红色
WritableFont font1=new WritableFont(WritableFont.createFont("宋体"),16,WritableFont.BOLD);
font1.setColour(Colour.RED);
WritableCellFormat format1=new WritableCellFormat(font1);
format1.setAlignment(jxl.format.Alignment.CENTRE);
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
Label labelA = new Label(0,0,"姓名",format1);
Label labelB = new Label(1,0,"地址",format1);
Label labelC = new Label(2,0,"年龄",format1);
//将定义好的单元格添加到工作表中
sheet.addCell(labelA);
sheet.addCell(labelB);
sheet.addCell(labelC);
/*生成一个保存数字的单元格
必须使用Number的完整包路径,否则有语法歧义*/
Label labelA1 = new Label(0,1,"小张");
Label labelB1 = new Label(1,1,"湖南省长沙市");
jxl.write.Number number = new jxl.write.Number(2,1,20);
sheet.addCell(labelA1);
sheet.addCell(labelB1);
sheet.addCell(number);
//写入数据并关闭文件
book.write();
book.close();
System.out.println("创建文件成功!");
}catch(Exception e)
{
System.out.println(e);
}
}
读EXCEL文件:
public void readXLS()
{
try
{
Workbook book=
Workbook.getWorkbook(new File("JAVA生成EXCEL测试.xls"));
//获得第一个工作表对象
Sheet sheet=book.getSheet(0);
//得到第一列第一.二行的单元格
Cell cellKey=sheet.getCell(0,0);
Cell cellValue=sheet.getCell(0,1);
String result=cellKey.getContents();
String value=cellValue.getContents();
System.out.println(result+" :"+value);
cellKey=sheet.getCell(1,0);
cellValue=sheet.getCell(1,1);
result=cellKey.getContents();
value=cellValue.getContents();
System.out.println(result+" :"+value);
cellKey=sheet.getCell(2,0);
cellValue=sheet.getCell(2,1);
result=cellKey.getContents();
value=cellValue.getContents();
System.out.println(result+" :"+value);
book.close();
System.out.println("查询EXCEL文件结束!");
}catch(Exception e)
{
System.out.println(e);
}
}
编辑EXCEL文件和创建差不多,只是在创建文件时有一点不同:
//Excel获得文件
Workbook wb=Workbook.getWorkbook(new File("JAVA生成EXCEL测试.xls"));
//打开一个文件的副本,并且指定数据写回到原文件
WritableWorkbook book=
Workbook.createWorkbook(new File("JAVA生成EXCEL测试.xls"),wb);