POI 读取EXCEL实现程序

  1. /*
  2. * 使用POI读取EXCEL文件
  3. */
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.util.ArrayList;
  7. import org.apache.poi.hssf.usermodel.HSSFCell;
  8. import org.apache.poi.hssf.usermodel.HSSFRow;
  9. import org.apache.poi.hssf.usermodel.HSSFSheet;
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  11. /**
  12. *
  13. * @author Hanbin
  14. */
  15. public class ReadExcel {
  16. /**
  17. * @param args the command line arguments
  18. */
  19. public static void main(String[] args)throws Exception {
  20. read("d:\demo.xls");
  21. }
  22. public static ArrayList read(String fileName){
  23. ArrayList list = new ArrayList();
  24. String sql = "";
  25. try{
  26. File f = new File(fileName);
  27. FileInputStream fis = new FileInputStream(f);
  28. HSSFWorkbook wbs = new HSSFWorkbook(fis);
  29. HSSFSheet childSheet = wbs.getSheetAt(0);
  30. System.out.println("行数:" + childSheet.getLastRowNum());
  31. for(int i = 4;i<childSheet.getLastRowNum();i++){
  32. HSSFRow row = childSheet.getRow(i);
  33. System.out.println("列数:" + row.getPhysicalNumberOfCells());
  34. if(null != row){
  35. for(int k=1;k<row.getPhysicalNumberOfCells();k++){
  36. HSSFCell cell;
  37. cell = row.getCell((short)k);
  38. // System.out.print(getStringCellValue(cell) + "t");
  39. list.add(getStringCellValue(cell) + "t");
  40. }
  41. }
  42. }
  43. }catch(Exception e){
  44. e.printStackTrace();
  45. }
  46. return list;
  47. }
  48. /**
  49. * 获取单元格数据内容为字符串类型的数据
  50. *
  51. * @param cell Excel单元格
  52. * @return String 单元格数据内容
  53. */
  54. private static String getStringCellValue(HSSFCell cell) {
  55. String strCell = "";
  56. switch (cell.getCellType()) {
  57. case HSSFCell.CELL_TYPE_STRING:
  58. strCell = cell.getStringCellValue();
  59. break;
  60. case HSSFCell.CELL_TYPE_NUMERIC:
  61. strCell = String.valueOf(cell.getNumericCellValue());
  62. break;
  63. case HSSFCell.CELL_TYPE_BOOLEAN:
  64. strCell = String.valueOf(cell.getBooleanCellValue());
  65. break;
  66. case HSSFCell.CELL_TYPE_BLANK:
  67. strCell = "";
  68. break;
  69. default:
  70. strCell = "";
  71. break;
  72. }
  73. if (strCell.equals("") || strCell == null) {
  74. return "";//开源代码phpfensi.com
  75. }
  76. if (cell == null) {
  77. return "";
  78. }
  79. return strCell;
  80. }
  81. }