我已经在 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);
还可以考虑向 Point 类添加构造函数和 getter/setter。
您也可能想直接使用 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 - 从Excel文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20613343/