我正在嘗試利用 Apache POI 讀取 excel 檔案并將其轉換為二維物件陣列。附上代碼部分。
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(1);
int numRows = 3;
int cols = 5;
double[][] excelData = new double[numRows][cols];
for (int i = 1; i < numRows; i ) {
Row row = firstSheet.getRow(i);
if (row != null) {
for (int j = 1; j < cols; j ) {
Cell cell = row.getCell(j);
if (cell != null) {
try {
excelData[i][j] = cell.getNumericCellValue();
} catch (IllegalStateException e) {
System.out.println("Cell data is not a double");
}
}
}
}
}
workbook.close();
inputStream.close();
return excelData;
}
在此處輸入影像描述這是我的 excel 表,我想“只是”將它的藍色部分讀取為二維陣列,但在運行代碼后,第一行和第一列都為零,我不想要它,感謝您幫助如何快速拉出所有零 在此處輸入影像描述。
uj5u.com熱心網友回復:
您需要將第一個回圈中的索引更改為 0(excel 檔案中的第一個欄位),但在行中您必須提供 index 1 bc 您需要從第二個欄位中讀取。第二個回圈和單元欄位的類比相同
Workbook workbook = new XSSFWorkbook(new File("d:\\book1.xlsx"));
Sheet firstSheet = workbook.getSheetAt(1);
int numRows = 3;
int cols = 5;
double[][] excelData = new double[numRows][cols];
for (int i = 0; i < numRows; i ) {
Row row = firstSheet.getRow(i 1);
if (row != null) {
for (int j = 0; j < cols; j ) {
Cell cell = row.getCell(j 1);
if (cell != null) {
try {
if (cell.getCellType().equals(CellType.NUMERIC)) {
excelData[i][j] = Double.valueOf(cell.getNumericCellValue());
}
} catch (IllegalStateException e) {
System.out.println("Cell data is not a double");
}
}
}
}
}
workbook.close();
回傳結果:
0.041256 0.033079 -0.01138 -0.02138 -0.01138
0.041256 0.033079 -0.01138 -0.01138 -0.01138
0.020628 0.01654 -0.00569 -0.10569 -0.00569
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436831.html
標籤:爪哇 数组 擅长 多维数组 apache-poi
