java poi读取excel
[java] view plain copy print?
01.package poi;
02.import java.io.FileInputStream;
03.import java.io.IOException;
04.import java.io.InputStream;
05.import java.util.Iterator;
06.import org.apache.poi.hssf.usermodel.HSSFCell;
07.import org.apache.poi.hssf.usermodel.HSSFWorkbook;
08.import org.apache.poi.ss.usermodel.Cell;
09.import org.apache.poi.ss.usermodel.Row;
10.import org.apache.poi.ss.usermodel.Sheet;
11.import org.apache.poi.ss.usermodel.Workbook;
12.import org.apache.poi.xssf.usermodel.XSSFWorkbook;
13.
14.public class ReadExcel001 {
15. public static void main(String[] args) {
16. readXml("D:/test.xlsx");
17. System.out.println("-------------");
18. readXml("d:/test2.xls");
19. }
20. public static void readXml(String fileName){
21. boolean isE2007 = false; //判断是否是excel2007格式
22. if(fileName.endsWith("xlsx"))
23. isE2007 = true;
24. try {
25. InputStream input = new FileInputStream(fileName); //建立输入流
26. Workbook wb = null;
27. //根据文件格式(2003或者2007)来初始化
28. if(isE2007)
29. wb = new XSSFWorkbook(input);
30. else
31. wb = new HSSFWorkbook(input);
32. Sheet sheet = wb.getSheetAt(0); //获得第一个表单
33. Iterator rows = sheet.rowIterator(); //获得第一个表单的迭代器
34. while (rows.hasNext()) {
35. Row row = rows.next(); //获得行数据
36. System.out.println("Row #" + row.getRowNum()); //获得行号从0开始
37. Iterator cells = row.cellIterator(); //获得第一行的迭代器
38. while (cells.hasNext()) {
39. Cell cell = cells.next();
40. System.out.println("Cell #" + cell.getColumnIndex());
41. switch (cell.getCellType()) { //根据cell中的类型来输出数据
42. case HSSFCell.CELL_TYPE_NUMERIC:
43. System.out.println(cell.getNumericCellValue());
44. break;
45. case HSSFCell.CELL_TYPE_STRING:
46. System.out.println(cell.getStringCellValue());
47. break;
48. case HSSFCell.CELL_TYPE_BOOLEAN:
49. System.out.println(cell.getBooleanCellValue());
50. break;
51. case HSSFCell.CELL_TYPE_FORMULA:
52. System.out.println(cell.getCellFormula());
53. break;
54. default:
55. System.out.println("unsuported sell type");
56. break;
57. }
58. }
59. }
60. } catch (IOException ex) {
61. ex.printStackTrace();
62. }
63. }
64.}
|