从Excel文件读取数据

我已经通过StackOverflowsearch,但没有find明确的答案我的问题。

我有一个简单的2列和24行xlsx(excel)文件(稍后在这个文件将有更多的列和行,也最终会有不同的工作表)。

第一行是标题行:year = x和population = y,对于每个标题,我想读取下面的行。 后来我想能够使用这些信息来创build一个dynamic图(x,y),

所以我想我需要将x和y信息保存在variables中。 下面是我的伪代码。

//Sheet Pop final String POP = "Pop"; int startRowHeader = 1, startRowNumeric = 2, startColNumeric = 1, nrOfCols = 0, nrOfRows = 0; int nrOfSheets = excelFile.getWorkbook().getNumberOfSheets(); org.apache.poi.ss.usermodel.Sheet sheet1 = excelFile.getWorkbook().getSheetAt(0); String[] sheets = {POP}; boolean sheetExists; String activeSheet = ""; nrOfCols = sheet1.getRow(0).getLastCellNum(); nrOfRows = excelFile.getLastRowNum(POP); try { for (String sheet : sheets) { sheetExists = false; for (int sheetIndex = 0; sheetIndex < nrOfSheets; sheetIndex++) { if (sheet.equalsIgnoreCase( excelFile.getWorkbook().getSheetName(sheetIndex))) { SheetExists = true; } } if (!sheetExists) { throw new Exception("Sheet " + sheet + " is missing!"); } } //Take off! // Sheet Pop activeSheet = sheets[0]; for(int j=0; j < nrOfCols; j++) { for(int i=0; i<nrofRows; i++) { column[i] = (int)excelFile.getCellNumericValue(POP, startRowNumeric, startColNumeric); } } } catch (Exception e) { traceln(" ..... "); traceln("Error in sheet: " + activeSheet); traceln("Message: " + e.getMessage()); //Write out in console } 

创build一个新的类:

 public class Point { int x; int y; } 

在你的主要function中创build一个

 List<Point> allPoints = new List<Point>(); 

然后将您从Excel中读取的点添加到此列表中

做一个循环

 Point p = new Point(); px = xCoordinateFromExcel; py = yCoordinateFromExcel; allPoints.add(p); 

也考虑添加构造函数和getter / setters到你的Point类。

你也可能想直接使用java.awt中的Point类。 http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html

编辑:关于从Excel中提取值这是我从你的问题了解你有24行2列第一列有X,第二列有Y值

所以你可以在循环中做这样的事情

 for(int i=0;i<24;i++){ Row row = sheet.getRow(i); Cell cellX = row.getCell(1); Cell cellY = row.getCell(2); //assign to point class ... } 

不要忘了parsing为int,或使用getNumericCellValue() http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getNumericCellValue(&#xFF09;

您可以使用java.awt.geom.Point2D.Doublejava.util.ArrayList

声明清单:

 ArrayList<Point2D.Double> points = new ArrayList<>(); 

然后为每一行:

 // Read x // Read y Point2D.Double p = new Point2D.Double(x, y); /// And add to the list: points.add(p);