Java读写Excel的包是Apache POI(项目地址:http://poi.apache.org/),因此需要先获取POI的jar包,本实验使用的是POI 3.9稳定版。
Apache POI 代码例子地址:http://poi.apache.org/spreadsheet/quick-guide.html
本例子可以读取Microsoft Office Excel 2003/2007/2010,具体代码及注释如下:
读取“.xls”格式使用 import org.apache.poi.hssf.usermodel.*; 包的内容,例如:HSSFWorkbook
读取“.xlsx”格式使用 import org.apache.poi.xssf.usermodel.*; 包的内容,例如:XSSFWorkbook
读取两种格式使用 import org.apache.poi.ss.usermodel.* 包的内容,例如:Workbook
引入包如下:
1 import org.apache.poi.ss.usermodel.Cell; 2 import org.apache.poi.ss.usermodel.Row; 3 import org.apache.poi.ss.usermodel.Sheet; 4 import org.apache.poi.ss.usermodel.Workbook; 5 import org.apache.poi.ss.usermodel.WorkbookFactory; 6 import org.apache.poi.ss.usermodel.DateUtil;
1 /** 2 * 读取Excel测试,兼容 Excel 2003/2007/2010 3 */ 4 public String readExcel() 5 { 6 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); 7 try { 8 //同时支持Excel 2003、2007 9 File excelFile = new File("/home/zht/test.xls"); //创建文件对象 10 FileInputStream is = new FileInputStream(excelFile); //文件流 11 Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的 12 int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量 13 //遍历每个Sheet 14 for (int s = 0; s < sheetCount; s++) { 15 Sheet sheet = workbook.getSheetAt(s); 16 int rowCount = sheet.getPhysicalNumberOfRows(); //获取总行数 17 //遍历每一行 18 for (int r = 0; r < rowCount; r++) { 19 Row row = sheet.getRow(r); 20 int cellCount = row.getPhysicalNumberOfCells(); //获取总列数 21 //遍历每一列 22 for (int c = 0; c < cellCount; c++) { 23 Cell cell = row.getCell(c); 24 int cellType = cell.getCellType(); 25 String cellValue = null; 26 switch(cellType) { 27 case Cell.CELL_TYPE_STRING: //文本 28 cellValue = cell.getStringCellValue(); 29 break; 30 case Cell.CELL_TYPE_NUMERIC: //数字、日期 31 if(DateUtil.isCellDateFormatted(cell)) { 32 cellValue = fmt.format(cell.getDateCellValue()); //日期型 33 } 34 else { 35 cellValue = String.valueOf(cell.getNumericCellValue()); //数字 36 } 37 break; 38 case Cell.CELL_TYPE_BOOLEAN: //布尔型 39 cellValue = String.valueOf(cell.getBooleanCellValue()); 40 break; 41 case Cell.CELL_TYPE_BLANK: //空白 42 cellValue = cell.getStringCellValue(); 43 break; 44 case Cell.CELL_TYPE_ERROR: //错误 45 cellValue = "错误"; 46 break; 47 case Cell.CELL_TYPE_FORMULA: //公式 48 cellValue = "错误"; 49 break; 50 default: 51 cellValue = "错误"; 52 } 53 System.out.print(cellValue + " "); 54 } 55 System.out.println(); 56 } 57 } 58 59 } 60 catch (Exception e) { 61 e.printStackTrace(); 62 } 63 64 return Action.SUCCESS; 65 }