Sie sind auf Seite 1von 2

package org.kodejava.example.

poi;
02.
03.import org.apache.poi.hssf.usermodel.HSSFWorkbook;
04.import org.apache.poi.hssf.usermodel.HSSFSheet;
05.import org.apache.poi.hssf.usermodel.HSSFRow;
06.import org.apache.poi.hssf.usermodel.HSSFCell;
07.
08.import java.io.FileInputStream;
09.import java.io.IOException;
10.import java.util.Iterator;
11.import java.util.List;
12.import java.util.ArrayList;
13.
14.public class ExcelReadExample {
15.
16. @SuppressWarnings("unchecked")
17. public static void main(String[] args) throws Exception {
18. //
19. // An excel file name. You can create a file name with a full path
20. // information.
21. //
22. String filename = "..\\data.xls";
23.
24. //
25. // Create an ArrayList to store the data read from excel sheet.
26. //
27. List sheetData = new ArrayList();
28.
29. FileInputStream fis = null;
30. try {
31. //
32. // Create a FileInputStream that will be use to read the excel file.
33. //
34. fis = new FileInputStream(filename);
35.
36. //
37. // Create an excel workbook from the file system.
38. //
39. HSSFWorkbook workbook = new HSSFWorkbook(fis);
40. //
41. // Get the first sheet on the workbook.
42. //
43. HSSFSheet sheet = workbook.getSheetAt(0);
44.
45. //
46. // When we have a sheet object in hand we can iterator on each
47. // sheet's rows and on each row's cells. We store the data read
48. // on an ArrayList so that we can printed the content of the excel
49. // to the console.
50. //
51. Iterator rows = sheet.rowIterator();
52. while (rows.hasNext()) {
53. HSSFRow row = (HSSFRow) rows.next();
54. Iterator cells = row.cellIterator();
55.
56. List data = new ArrayList();
57. while (cells.hasNext()) {
58. HSSFCell cell = (HSSFCell) cells.next();
59. data.add(cell);
60. }
61.
62. sheetData.add(data);
63. }
64. } catch (IOException e) {
65. e.printStackTrace();
66. } finally {
67. if (fis != null) {
68. fis.close();
69. }
70. }
71.
72. showExelData(sheetData);
73. }
74.
75. private static void showExelData(List sheetData) {
76. //
77. // Iterates the data and print it out to the console.
78. //
79. for (int i = 0; i < sheetData.size(); i++) {
80. List list = (List) sheetData.get(i);
81. for (int j = 0; j < list.size(); j++) {
82. HSSFCell cell = (HSSFCell) list.get(j);
83. System.out.print(cell.getRichStringCellValue().getString());
84. if (j < list.size() - 1) {
85. System.out.print(", ");
86. }
87. }
88. System.out.println("");
89. }
90. }
91.}

Das könnte Ihnen auch gefallen