使用Java将文件名从计算机中的文件夹复制到新创建的Excel工作表,可以通过以下步骤实现:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("文件名列表");
String folderPath = "文件夹路径";
File folder = new File(folderPath);
File[] files = folder.listFiles();
int rowNum = 0;
for (File file : files) {
if (file.isFile()) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
cell.setCellValue(file.getName());
}
}
String excelFilePath = "保存Excel文件的路径";
try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
workbook.write(outputStream);
}
完整的Java代码示例:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileToExcel {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("文件名列表");
String folderPath = "文件夹路径";
File folder = new File(folderPath);
File[] files = folder.listFiles();
int rowNum = 0;
for (File file : files) {
if (file.isFile()) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
cell.setCellValue(file.getName());
}
}
String excelFilePath = "保存Excel文件的路径";
try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这段代码使用Apache POI库来操作Excel文件,创建一个新的工作簿和工作表,并将文件夹中的文件名写入Excel工作表中。你可以根据实际情况修改文件夹路径和保存Excel文件的路径。
领取专属 10元无门槛券
手把手带您无忧上云