【发布时间】:2017-05-09 07:49:32
【问题描述】:
我正在做一个项目,我必须从 excel 文件中获取文件夹和子文件夹名称,保持层次结构并将它们存储在一个数组中,以使用该数组来创建目录结构。
我正在使用 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;
这里我用 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结构的一个例子。
标签: java excel multidimensional-array data-structures apache-poi