用一个简单的例子演示POI怎样从Excel中读取文件中的数据。
Excel文件如下:
package my.excel; import java.io.FileInputStream; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; /** * 使用POI读取Excel文件中的数据(一个用户信息表格) * @author Administrator * 2013年03月02日 */ public class FirstReadExcel { public static void main(String[] args) { try { InputStream inp = new FileInputStream("document/FirstReadExcel.xlsx"); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); // 迭代行 for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext(); ) { Row row = (Row) rit.next(); // 迭代单元格 for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) { Cell cell = (Cell) cit.next(); // 打印单元格内的数据 switch (cell.getCellType()) { // 字符串 case Cell.CELL_TYPE_STRING: System.out.print(cell.getRichStringCellValue().getString() + "\t"); break; // 数字 case Cell.CELL_TYPE_NUMERIC: // 处理日期 if (DateUtil.isCellDateFormatted(cell)) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = cell.getDateCellValue(); System.out.print(format.format(date) + "\t"); } else { System.out.print(cell.getNumericCellValue() + "\t"); } break; // 布尔值 case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; // case Cell.CELL_TYPE_FORMULA: System.out.print(cell.getCellFormula() + "\t"); break; default: System.out.print("\t"); } // switch } // for 2 System.out.println(); } // for 1 } catch (Exception e) { e.printStackTrace(); } } // main end }
运行结果:
姓名 性别 年龄 出生年月 薪水
张山 男 23.0 1990-03-01 3400.0
李艳 女 22.0 1991-04-15 3450.0
奎唔 男 20.0 1993-08-25 4350.0
更多相关知识请查看:www.bug315.com