我正在處理一個項目,我必須從excel文件中獲取文件夾和子文件夾名稱,保留層次結構並將它們存儲在數組中,以使用該數組創建目錄結構。xlsx文件中的DataStructure
我使用Apache POI來讀取excel文件。
如何將它們存儲到數組中,考慮到我有8個樹級別?
例如:
Folder
Subfolder01
Subfolder02
Subfolder02.01
Subfolder02.01.01
Subfolder02.01.01.01
Subfolder02.01.02
Subfolder03
Subfolder04
Subfolder04.01
Subfolder04.01.01
Subfolder04.01.01.01
Subfolder04.01.02
Subfolder04.01.02.01
Subfolder04.02
這是我如何使用Apache POI庫讀取Excel文件:
public class ExcelReadClass {
private static final String FILE_NAME = "D:/Work-Space/TESTExcel.xlsx";
public void readExcel(String fileName) {
try {
// XSSFWorkbook = XML SpreadSheet Format
// is for Excel 2007 or above
Workbook workbook = new XSSFWorkbook(fileName);
// Accessing the particular sheet
// here the parameter indicates the sheet number. 0 means first sheet, 1 means the second and so on
/// accessing first sheet - which is " Components "
Sheet sheet = workbook.getSheetAt(0);
/*
* Sheet can also be accessed using the sheet name like shown below
* Sheet sheet = workbook.getSheet("Components");
*/
// geting the rows
// following code will work with empty cells
Row row = null;
Cell cell = null;
// Returns: the number of physically defined rows in the selected sheet
//int noOfRows = sheet.getPhysicalNumberOfRows();
//Returns: last row contained n this sheet (0-based)
int noOfRows = sheet.getLastRowNum();
// starting from 0 - which is the first row
for(int i = 2; i <= noOfRows; i++) {
row = sheet.getRow(i);
//int noOfCells = row.getPhysicalNumberOfCells(); // returns the total number of cells in the selected row
//int noOfCells = row.getLastCellNum(); // returns the number of the last cell in the row
int noOfCells = 11;
在這裏,我outputing與SYSOUT 文件結構的地方,我必須將整個結構存儲爲陣列
// starting from 0 - which is the first column (aka cell)
for(int j = 1; j < noOfCells; j++) {
cell = row.getCell(j) ; // if there's no more cells, it returns null
if(cell != null) {
System.out.print(getCellValue(cell) + "\t");
} else {
Cell blanckCell = row.createCell(j);
blanckCell.setCellValue("");
System.out.print(getCellValue(blanckCell) + "\t");
}
}
System.out.println();
}
workbook.close();
} catch (FileNotFoundException e) {
System.out.println("File is not available.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Problem reading file from directory.");
e.printStackTrace();
} catch (NullPointerException e){
System.err.println("Last part of Excel");
e.printStackTrace();
}
}
public Object getCellValue(Cell cell){
Object cellValue = null;
if(cell.getCellTypeEnum() == CellType.STRING){
cellValue = cell.getStringCellValue();
}else if(cell.getCellTypeEnum() == CellType.NUMERIC){
cellValue = cell.getNumericCellValue();
}else if(cell.getCellTypeEnum() == CellType.BOOLEAN){
cellValue = cell.getBooleanCellValue();
}else if(cell.getCellTypeEnum() == CellType.BLANK){
cellValue = "";
}
return cellValue;
}
}
什麼是錯的樹和水平打印呢? –
上面的樹是作爲excel結構的例子給出的。 –