需要的jar包
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
xmlbeans-2.3.0_poi.jar
[java] view plaincopy
1. /**
2. * Description:用poi解析excel,支持office2007 xls,xlsx
3. * @author liuwei DateTime 2013-8-26 上午10:58:16
4. * @param fileName
5. * @param sheetNumber
6. * @return
7. */
8. public List<String[]> readByPoi(String fileName,int sheetNumber) {
9. org.apache.poi.ss.usermodel.Workbook workbook = null;
10. List<String[]> list = new ArrayList<String[]>();
11. try {
12. String fileType=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
13. if (fileType.equals("xls")) {
14. workbook = new HSSFWorkbook(new FileInputStream(fileName));
15. }
16. else if(fileType.equals("xlsx"))
17. {
18. workbook = new XSSFWorkbook(new FileInputStream(fileName));
19. }
20. else
21. {
22. log.info("您的文档格式不正确!");
23. }
24. //创建sheet对象
25. org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(sheetNumber);
26. int firstRowIndex = sheet.getFirstRowNum();
27. int lastRowIndex = sheet.getLastRowNum();
28. int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();//获得总列数
29. for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){
30. Row row = sheet.getRow(rIndex);
31. if(row != null){
32. int firstCellIndex = row.getFirstCellNum();
33. int lastCellIndex = row.getLastCellNum();
34. String[] s=new String[coloumNum];
35. for(int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex ++){
36. Cell cell = row.getCell(cIndex);
37. String value = "";
38. int type = cell.getCellType();
39.
40. if(cell != null){
41. value = cell.toString();
42. if (Cell.CELL_TYPE_NUMERIC == type) {
43. // value = String.valueOf(cell.getNumericCellValue());
44. Double val = cell.getNumericCellValue();
45. if(val == val.longValue()){
46. value= "" + val.longValue();
47. }
48. }
49.
50. s[cIndex]=value;
51. }
52. }
53. list.add(s);
54. }
55. }
56.
57. } catch (Exception e) {
58. // Log.error(e.getMessage());
59. e.printStackTrace();
60.
61. }
62. return list;