使用Java Excel API(jxl.jar),下载地址:http://www.andykhan.com/jexcelapi/download.html
特别需要注意的是,jxl.jar不支持Excel2007,也就是不支持.xlsx格式的文件
一,读取Excel格式文件:
import java.io.File; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; public class ReadExcel { public static void main(String[] args) throws Exception { //不支持Excel2007格式(也就是xlsx格式文件) File file = new File("e:\\readtest.xls"); Workbook wb = Workbook.getWorkbook(file); Sheet[] sheets = wb.getSheets(); //遍历每页 for(Sheet s : sheets){ System.out.println(s.getName() + " : "); int rows = s.getRows(); if(rows > 0){ //遍历每行 for(int i = 0 ;i < rows ; i++){ System.out.print("行" + i + " : "); Cell[] cells = s.getRow(i); if(cells.length > 0){ //遍历每行中的每列 for(Cell c : cells){ String str = c.getContents().trim(); System.out.print(str + " ; "); } System.out.println(); } } } } } }
执行结果如下:
页1 : 行0 : 编号1 ; 编号2 ; 编号3 ; 行1 : 1 ; 1 ; 1 ; 行2 : 2 ; 2 ; 行3 : 3 ; 页2 : 行0 : 编号 ; 姓名 ; 年龄 ; 行1 : 1 ; Li ; 15 ; 行2 : 2 ; Sean ; 51 ;
当然在Excel格式固定的情况下,也可以直接通过Sheet.getCell(column, row)方法直接获取特定位置的单元格
二,写Excel格式文件:
import java.io.File; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class WriteExcel { public static void main(String[] args){ File file; WritableWorkbook wwb; try{ file = new File("e:\\writetest.xls"); wwb = Workbook.createWorkbook(file); WritableSheet ws = wwb.createSheet("页1", 0); ws.addCell(new Label(0, 0, "0行0列")); ws.addCell(new Label(0, 1, "1行0列")); ws.addCell(new Label(1, 1, "1行1列")); wwb.write(); wwb.close(); }catch(Exception e){ e.printStackTrace(); } } }
执行结果如下: