添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
第一种:
package com.xxl.job.admin.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FolderToExcel {
private static int rowNum = 0;
public static void main(String[] args) throws IOException {
String folderPath = "E:/repo"; // 文件夹路径
String excelPath = "E:/output.xlsx"; // Excel文件路径
XSSFWorkbook workbook = new XSSFWorkbook();
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("Folder");
File folder = new File(folderPath);
if (folder.isDirectory()) {
createFolderSheet(folder, sheet, "");
}
FileOutputStream outputStream = new FileOutputStream(excelPath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Exported to " + excelPath);
}
private static void createFolderSheet(File folder, org.apache.poi.ss.usermodel.Sheet sheet, String parentPath) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
cell.setCellValue(parentPath + folder.getName());
if (folder.isDirectory()) {
for (File subFolder : folder.listFiles()) {
createFolderSheet(subFolder, sheet, parentPath + folder.getName() + " ");
}
}
}
}
第二种
package com.xxl.job.admin.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FolderToExcel {
private static int rowNum = 0;
public static void main(String[] args) throws IOException {
String folderPath = "E:/repo"; // 文件夹路径
String excelPath = "E:/output2.xlsx"; // Excel文件路径
XSSFWorkbook workbook = new XSSFWorkbook();
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("Folder");
File folder = new File(folderPath);
if (folder.isDirectory()) {
createFolderSheet(folder, sheet, "");
}
FileOutputStream outputStream = new FileOutputStream(excelPath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Exported to " + excelPath);
}
private static void createFolderSheet(File folder, org.apache.poi.ss.usermodel.Sheet sheet, String parentPath) {
if (folder.isDirectory()) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
cell.setCellValue(parentPath + folder.getName());
for (File subFolder : folder.listFiles(File::isDirectory)) {
createFolderSheet(subFolder, sheet, parentPath + folder.getName() + " ");
}
}
}
}
标签:读取,递归,org,excel,File,poi,apache,import,folder
From: https://www.cnblogs.com/szrup0126/p/17603884.html