如何使用java创buildExcelsheet中存在的数据的文件夹和子文件夹

我正在尝试使用Excel的内容创build文件夹。 我能够读取具有正确数据的Excel文件,但我无法从该数据创build文件夹。

我到目前为止写的代码是:

public static void main(String[] args) { try { InputStream ExcelFileToRead = new FileInputStream("C:\\Users\\430427\\Desktop\\vivek.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFWorkbook test = new XSSFWorkbook(); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { row = (XSSFRow) rows.next(); Iterator cells = row.cellIterator(); int i = 0; while (cells.hasNext()) { cell = (XSSFCell) cells.next(); XSSFCell cell2 = row.getCell(i); i++; if(cell2 !=null){ //if(cell2.toString().replaceAll("\\s", "").length()>0) System.out.print("/"+cell2); String dirName = "C:\\Users\\430427\\Desktop\\"+cell2; new File(dirName).mkdir(); } } System.out.println(); i = 0; } System.out.println("\n"); } catch (IOException ex) { ex.printStackTrace(); } } 

https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCell.html

cell2是XSSFCell对象而不是string。

尝试在String dirName = "C:\\Users\\430427\\Desktop\\"+cell2; cell2.getStringCellValue() String dirName = "C:\\Users\\430427\\Desktop\\"+cell2; 获取string值。

我build议你应该从你的代码中获取用户configuration文件,而不是硬编码path。


编辑:

Apache poi中没有columnIterator。 所以我想出了另一种方法。 这个代码只对你的情况有意义(只在第一列有一行,在最后一列有一行或多行)就像你在评论中说的那样:

数据如A1,A1,B1中的CALEG,D1,D2,D3,D4中的C1,Title A,Title B,Title C,Title D中的html。

我希望给你一些想法来实现你所需要的。

 public static void main(String[] args) { XSSFWorkbook wb = null; try { // input file path here InputStream ExcelFileToRead = new FileInputStream("D:\\test.xlsx"); wb = new XSSFWorkbook(ExcelFileToRead); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator<Row> rows = sheet.rowIterator(); // destination path here String dirName = "D:\\tmp"; String parentPath = null; int lastCellIdx = 0; while (rows.hasNext()) { row = (XSSFRow) rows.next(); if (lastCellIdx != 0) { new File(parentPath + "\\" + row.getCell(lastCellIdx).toString()).mkdir(); } else { Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { cell = (XSSFCell) cells.next(); if (cell != null) { dirName = dirName + "\\" + cell.toString(); } } lastCellIdx = row.getLastCellNum() - 1; parentPath = new File(dirName).getParent(); new File(dirName).mkdirs(); } } } catch (IOException ex) { ex.printStackTrace(); } finally { try { wb.close(); } catch (IOException e) { e.printStackTrace(); } } }