POI 读取EXCEL

关于Excel的读写,最大众的方式就是使用POI了。。。

现在越来越懒了,最近太忙了:

贴个代码:

 1 /*

 2  * 使用POI读取EXCEL文件

 3  */

 4 import java.io.File;

 5 import java.io.FileInputStream;

 6 import java.util.ArrayList;

 7 

 8 import org.apache.poi.hssf.usermodel.HSSFCell;

 9 import org.apache.poi.hssf.usermodel.HSSFRow;

10 import org.apache.poi.hssf.usermodel.HSSFSheet;

11 import org.apache.poi.hssf.usermodel.HSSFWorkbook;

12 

13 /**

14  *

15  * @author Hanbin

16  */

17 public class ReadExcel {

18 

19     /**

20      * @param args the command line arguments

21      */

22     public static void main(String[] args)throws Exception {

23         read("d:\\demo.xls");

24     }

25     

26     public static ArrayList read(String fileName){

27         ArrayList list = new ArrayList();

28         String sql = "";

29         try{

30             File f = new File(fileName);

31             FileInputStream fis = new FileInputStream(f);

32             HSSFWorkbook wbs = new HSSFWorkbook(fis);

33             HSSFSheet childSheet = wbs.getSheetAt(0);

34             System.out.println("行数:" + childSheet.getLastRowNum());

35             for(int i = 4;i<childSheet.getLastRowNum();i++){

36                 HSSFRow row = childSheet.getRow(i);

37                 System.out.println("列数:" + row.getPhysicalNumberOfCells());

38                 if(null != row){

39                     for(int k=1;k<row.getPhysicalNumberOfCells();k++){

40                         HSSFCell cell;

41                         cell = row.getCell((short)k);

42                        // System.out.print(getStringCellValue(cell) + "\t");

43                         list.add(getStringCellValue(cell) + "\t");

44                     }

45                 }

46             }

47         }catch(Exception e){

48             e.printStackTrace();

49         }

50         return list;

51     }

52     /**

53      * 获取单元格数据内容为字符串类型的数据

54      * 

55      * @param cell Excel单元格

56      * @return String 单元格数据内容

57      */

58     private static String getStringCellValue(HSSFCell cell) {

59         String strCell = "";

60         switch (cell.getCellType()) {

61         case HSSFCell.CELL_TYPE_STRING:

62             strCell = cell.getStringCellValue();

63             break;

64         case HSSFCell.CELL_TYPE_NUMERIC:

65             strCell = String.valueOf(cell.getNumericCellValue());

66             break;

67         case HSSFCell.CELL_TYPE_BOOLEAN:

68             strCell = String.valueOf(cell.getBooleanCellValue());

69             break;

70         case HSSFCell.CELL_TYPE_BLANK:

71             strCell = "";

72             break;

73         default:

74             strCell = "";

75             break;

76         }

77         if (strCell.equals("") || strCell == null) {

78             return "";

79         }

80         if (cell == null) {

81             return "";

82         }

83         return strCell;

84     }

85 }

 

你可能感兴趣的:(Excel)