java读取excel的内容(可保存到数据库中)
//**
poi jar包
//
public class ReadExcel { @SuppressWarnings("static-access") private static String getValue(HSSFCell hssfCell) { if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) { // 返回布尔类型的值 return String.valueOf(hssfCell.getBooleanCellValue()); } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) { // 返回数值类型的值 return String.valueOf(hssfCell.getNumericCellValue()); } else { // 返回字符串类型的值 return String.valueOf(hssfCell.getStringCellValue()); } } public static List<Tuserinfo> readXls() throws IOException { InputStream is = new FileInputStream("d:/app/1.xls"); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); Tuserinfo bean = null; List<Tuserinfo> list = new ArrayList<Tuserinfo>(); // 循环工作表Sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循环行Row for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow != null) { bean = new Tuserinfo(); HSSFCell name = hssfRow.getCell(0); HSSFCell no = hssfRow.getCell(1); HSSFCell age = hssfRow.getCell(2); HSSFCell phone = hssfRow.getCell(3); HSSFCell cid = hssfRow.getCell(4); bean.setName(getValue(name)); bean.setCardcode(getValue(no)); bean.setPhone(getValue(phone)); bean.setCardno(getValue(cid)); bean.setUid(UUID.randomUUID().toString()); list.add(bean); } } } return list; }
//测试 public static void main(String[] args) { try { int i = 0; for (Tuserinfo u : readXls()) { System.out.println(u.toString()); i++; } System.out.println(i); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }