猿问

如何将程序的输出写入Excel表格

我想将程序的输出输入到 Excel 工作表/


我尝试过使用 Apache POI


import java.io.File;

import java.io.IOException;


public class Ex3 {


    public static void main(String[] args) {

        File currentDir = new File("C:\\Myfiles\\Script"); // current directory

        displayDirectoryContents(currentDir);

    }


    public static void displayDirectoryContents(File dir) {

        try {


            File[] files = dir.listFiles();

            for (File file : files) {

                if (file.isDirectory()) {

                    System.out.println("folder:" + file.getCanonicalPath());

                    displayDirectoryContents(file);

                } else {

                System.out.println("file:" + file.getCanonicalPath());

                }

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

我想将 if 语句的输出输入到第一列,将 else 的输出输入到第二列,或者将两者都输入到单独的工作表中(只要可行)。


智慧大石
浏览 79回答 1
1回答

缥缈止盈

无论我的需要如何,我总是创建相同的方法,然后调整输入public static void printAtFile(String filename, String header, String content[])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Start creating file "+filename);&nbsp; &nbsp; &nbsp; &nbsp; PrintWriter writer = null;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer = new PrintWriter(filename);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.println(header);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(String u:content)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.println(u);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.close();&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ex) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Error while writing at file "+filename);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }在这种情况下,你想做类似的事情String h = "Column1,column2"String content[] = new String[N];Arrays.fill(content, "");for(int i=0;i<N;i++){&nbsp; &nbsp; if(...)content[i]="whateveryouwant,"+"blank";&nbsp; &nbsp; else content[i]="blank,"+"whateveryouwant";}printAtFile("file.csv",h,content);
随时随地看视频慕课网APP

相关分类

Java
我要回答