首页 > 解决方案 > 我想将 displayDirectoryContents 的输出写入 excel 表

问题描述

我想将 displayDirectoryContents 的输出写入 excel 表

我尝试使用 Apache POI 方法我想将输出到 Excel 工作表文件夹和文件名在一列中,文件名在另一列导入语句中

public class Excel {

private static String dest = "C:\\Users\\mahselva\\testexcel.xls";
private static HSSFWorkbook myWorkBook = new HSSFWorkbook();
private static HSSFSheet mySheet = myWorkBook.createSheet();

public static void excelLog(String filename, String message, int rowNum) 
{

HSSFRow myRow = null;
HSSFCell myCell = null;
String excelData[][] = new String[1][2];
excelData[0][0] = filename;
excelData[0][1] = message;

myRow = mySheet.createRow(rowNum);

for (int cellNum = 0; cellNum < 2; cellNum++) {
    myCell = myRow.createCell(cellNum);
    myCell.setCellValue(excelData[0][cellNum]);

}
try {
    FileOutputStream out = new FileOutputStream(dest);
    myWorkBook.write(out);
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}
}

public static void main(String[] args) {
File currentDir = new File("C:\\OracleATS\\openScript"); // current 
directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
    int i = 0;
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            Path path = Paths.get(file.getCanonicalPath());
            //System.out.println("Folder" 
+path.getFileName().toString());
            excelLog("Folder",path.getFileName().toString(),i);
            i++;
            displayDirectoryContents(file);
        } else {
            Path path = Paths.get(file.getCanonicalPath());
            //System.out.println(path.getFileName().toString());
            excelLog("File",path.getFileName().toString(),i);
            i++;
        }

    }
} catch (IOException e) {
    e.printStackTrace();
} 
}
}

我想要一个excel表中的两列,第1列包含文件或文件夹,第2列包含文件/文件夹的名称,例如文件books.xml文件夹脚本

因此,我想将输出写入 excel 表,我正在使用函数 excel log 写入输出屏幕

标签: javaeclipse

解决方案


我用它来写入 excel - 但是我将其设为 .csv 格式,而不是 xls。因此,这可能不是您所需要的,但它仍然部分有用,因为它正在写入可以由 excel 轻松打开的文件。

public static void printAtFile(String filename, String header, String content[])
    {
        filename+=".csv";
        System.out.println("Start creating file "+filename);
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(filename);
            writer.println(header);
            for(String u:content)
                writer.println(u);
            writer.close();
        } catch (Exception ex) {
            System.out.println("Error while writing at file "+filename);
        }
    }

推荐阅读