簡體   English   中英

從Excel文件讀取數據

[英]Read data from excel file

我已經搜索了StackOverflow,但是沒有找到明確的答案。

我有一個簡單的2列和24行xlsx(excel)文件(此文件以后將具有更多的列和行,並且最終它將具有不同的工作表)。

第一行是標題行:year = x和population = y,對於每個標題,我想閱讀以下行。 稍后,我希望能夠使用此信息來創建動態圖(x,y),

所以我認為我需要將x和y信息保存在變量中。 下面是我的偽代碼。

//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
} 

創建一個新類:

public class Point {
        int x;
        int y;

}

在您的主要功能中創建一個

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

然后將您從excel中讀取的點添加到此列表中

循環執行此操作

Point p = new Point();
p.x = xCoordinateFromExcel;
p.y = yCoordinateFromExcel;

allPoints.add(p);

也可以考慮將構造函數和getter / setter添加到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
...
}

不要忘記將其解析為int,或使用getNumericCellValue() http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getNumericCellValue()

您可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM