Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用ApachePOI在excel中写入文件夹的所有内容?_Java_Excel_Eclipse - Fatal编程技术网

Java 如何使用ApachePOI在excel中写入文件夹的所有内容?

Java 如何使用ApachePOI在excel中写入文件夹的所有内容?,java,excel,eclipse,Java,Excel,Eclipse,我已将其编码为将所有文件和文件夹放入excel中的以下路径C:\Users\hmoorthy\workspace。但是变量i正在产生一些问题。我发现,用于查找文件的递归displayDirectoryContents(file,I)是否为目录,具有旧的I值,这会导致excel中的覆盖。因此,所有文件都没有进入excel 输出 文件夹:C:\Users\hmoorthy\workspace.0 文件:C:\Users\hmoorthy\workspace.metadata.bak_0.log 1

我已将其编码为将所有文件和文件夹放入excel中的以下路径C:\Users\hmoorthy\workspace。但是变量i正在产生一些问题。我发现,用于查找文件的递归displayDirectoryContents(file,I)是否为目录,具有旧的I值,这会导致excel中的覆盖。因此,所有文件都没有进入excel

输出 文件夹:C:\Users\hmoorthy\workspace.0 文件:C:\Users\hmoorthy\workspace.metadata.bak_0.log 1 文件:C:\Users\hmoorthy\workspace.metadata.lock 2 文件:C:\Users\hmoorthy\workspace.metadata.log 3 文件夹:C:\Users\hmoorthy\workspace.metadata.mylyn 4 文件夹:C:\Users\hmoorthy\workspace.metadata.mylyn.taskListIndex 5 文件:C:\Users\hmoorthy\workspace.metadata.mylyn.taskListIndex\segments\u 1 6 文件:C:\Users\hmoorthy\workspace.metadata.mylyn.taskListIndex\write.lock 7 文件:C:\Users\hmoorthy\workspace.metadata.mylyn.tasks.xml.zip 7 文件夹:C:\Users\hmoorthy\workspace.metadata.mylyn\contexts 8 文件:C:\Users\hmoorthy\workspace.metadata.mylyn\repositories.xml.zip 10 文件:C:\Users\hmoorthy\workspace.metadata.mylyn\tasks.xml.zip 11 文件夹:C:\Users\hmoorthy\workspace.metadata.plugins 6 文件夹:C:\Users\hmoorthy\workspace.metadata.plugins\oracle.eclipse.tools.common.services 7 文件夹:C:\Users\hmoorthy\workspace.metadata.plugins\oracle.eclipse.tools.common.services\compareExcel8 文件:C:\Users\hmoorthy\workspace.metadata.plugins\oracle.eclipse.tools.common.services\CompareExcel\1.artifact.sjo 9 文件:C:\Users\hmoorthy\workspace.metadata.plugins\oracle.eclipse.tools.common.services\CompareExcel\1.command.sjo 10 文件:C:\Users\hmoorthy\workspace.metadata.plugins\oracle.eclipse.tools.common.services\CompareExcel\command.num 11 文件:C:\Users\hmoorthy\workspace.metadata.plugins\oracle.eclipse.tools.common.services\CompareExcel\project.num 12

您可以看到两次iprints 11。因此,excel中第11-1行的上一个值将被替换。我想打印所有的值

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class App2 {

    private static String dest = "C:\\Users\\hmoorthy\\test.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) {
        int i = 0;
        File currentDir = new File("C:\\Users\\hmoorthy\\workspace");
        displayDirectoryContents(currentDir,i);
    }
    public static void displayDirectoryContents(File dir,int i) {
        try {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    //System.out.println("folder:" + file.getCanonicalPath());
                    //System.out.println("file          "+i);
                    excelLog("Folder",file.getCanonicalPath(),i);
                    i=i+1;
                    displayDirectoryContents(file,i);
                    i=i+1;
                } else {
                    //System.out.println("file:" + file.getCanonicalPath());
                    excelLog("File ",file.getCanonicalPath(),i);
                    i=i+1;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入org.apache.poi.hssf.usermodel.HSSFCell;
导入org.apache.poi.hssf.usermodel.HSSFRow;
导入org.apache.poi.hssf.usermodel.HSSFSheet;
导入org.apache.poi.hssf.usermodel.HSSFWorkbook;
公共类App2{
私有静态字符串dest=“C:\\Users\\hmoorthy\\test.xls”;
私有静态HSSFWorkbook myWorkBook=新建HSSFWorkbook();
私有静态HSSFSheet mySheet=my工作簿.createSheet();
公共静态void excelLog(字符串文件名、字符串消息、int rowNum){
HSSFRow myRow=null;
HSSFCell-myCell=null;
字符串excelData[][]=新字符串[1][2];
excelData[0][0]=文件名;
excelData[0][1]=消息;
myRow=mySheet.createRow(rowNum);
对于(int-cellNum=0;cellNum<2;cellNum++){
myCell=myRow.createCell(cellNum);
myCell.setCellValue(excelData[0][cellNum]);
}
试一试{
FileOutputStream out=新的FileOutputStream(dest);
我的工作手册。写出来;
out.close();
}捕获(例外e){
e、 printStackTrace();
}
}
公共静态void main(字符串[]args){
int i=0;
File currentDir=新文件(“C:\\Users\\hmoorthy\\workspace”);
displayDirectoryContents(currentDir,i);
}
公共静态void displayDirectoryContents(文件目录,int i){
试一试{
File[]files=dir.listFiles();
用于(文件:文件){
if(file.isDirectory()){
//System.out.println(“文件夹:”+file.getCanonicalPath());
//System.out.println(“文件”+i);
excelLog(“文件夹”,文件.getCanonicalPath(),i);
i=i+1;
displayDirectoryContents(文件,i);
i=i+1;
}否则{
//System.out.println(“文件:”+file.getCanonicalPath());
excelLog(“文件”,File.getCanonicalPath(),i);
i=i+1;
}
}
}捕获(IOE异常){
e、 printStackTrace();
}
}
}

谢谢;)

测试这是否适用于您:

public static void main(String[] args) {
    javax.swing.filechooser.FileNameExtensionFilter filtroExcel = new javax.swing.filechooser.FileNameExtensionFilter("Documento Microsoft Excel 2003/2013", "xls");
    final JFileChooser miFile = new JFileChooser();
    miFile.setFileFilter(filtroExcel);
    int retornaValor = miFile.showSaveDialog(null);
    miFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (retornaValor == JFileChooser.APPROVE_OPTION) {
        FileOutputStream fileNew = null;
        File fileExcel = null;
        try{
            fileExcel = miFile.getSelectedFile();
            String nombre = fileExcel.getName();
            if (nombre.indexOf('.') == -1) {
                nombre += ".xls";
                fileExcel = new File(fileExcel.getParentFile(), nombre);
            }
            fileNew = new FileOutputStream(fileExcel);
            // header
            HSSFWorkbook book=new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet("File List");
            CellStyle estilo=book.createCellStyle();
            estilo.setFillBackgroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
            HSSFFont fondo = book.createFont();
            fondo.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            estilo.setFont(fondo);
            estilo.setAlignment(CellStyle.ALIGN_CENTER);

            HSSFRow title = sheet.createRow((short) 0);
            HSSFCell celda = title.createCell((short) 0);
            celda.setCellStyle(estilo);
            celda.setCellValue("My file list");
            writeFiles(sheet, "C:\\Users\\hmoorthy\\workspace");

            book.write(fileNew);
        }
        catch(IOException ex){
            System.out.println(ex.getMessage());
        }
        finally {
            try {
                fileNew.close();
                // open file xls
                if (System.getProperty("os.name").equals("Linux"))
                    Runtime.getRuntime().exec("libreoffice " + fileExcel.getAbsolutePath());
                else
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + fileExcel.getAbsolutePath());
            } 
            catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
}

public static void writeFiles(HSSFSheet sheet, String path){
    File directorio=new File(path);
    if(directorio.exists()){
        File[] files=directorio.listFiles();
        for(int i=0;i<files.length;i++){
            try {
                if(files[i].isDirectory())
                    writeFiles(sheet, files[i].getCanonicalPath());
                else {
                    HSSFRow row=sheet.createRow((short)(i + 1));
                    HSSFCell celdasReg = row.createCell(0);
                    celdasReg.setCellValue(files[i].getCanonicalPath());
                }
            }
            catch (IOException ex){
                System.out.println(ex.getMessage());
            }
        }
    }
}
publicstaticvoidmain(字符串[]args){
javax.swing.filechooser.FileNameExtensionFilter filtroExcel=new javax.swing.filechooser.FileNameExtensionFilter(“Documento Microsoft Excel 2003/2013”、“xls”);
final JFileChooser miFile=新的JFileChooser();
设置文件过滤器(filterExcel);
int retronavalor=miFile.showsavedilog(null);
miFile.setFileSelectionMode(仅限JFileChooser.DIRECTORIES_);
if(retronavalor==JFileChooser.APPROVE\u选项){
FileOutputStream fileNew=null;
文件fileExcel=null;
试一试{
fileExcel=miFile.getSelectedFile();
字符串nombre=fileExcel.getName();
if(nombre.indexOf('.')=-1){
nombre+=“.xls”;
fileExcel=新文件(fileExcel.getParentFile(),nombre);
}
fileNew=新的FileOutputStream(fileExcel);
//标题
HSSFWorkbook=新的HSSFWorkbook();
HSSFSheet sheet=book.createSheet(“文件列表”);
CellStyle estilo=book.createCellStyle();
estilo.setFillBackgroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
hssfont fondo=book.createFont();
方多.立根重量(hs英尺.粗体重量_粗体);
estilo.setFont(fondo);
estilo.setAlignment(CellStyle.Alignment_CENTER);
HSSFRow title=sheet.createRow((短)0);
HSSFCell-celda=title.createCell((短)0);
塞尔达·塞塞尔斯泰尔(estilo);
setCellValue(“我的文件
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class writeExcel {

private static String dest = "C:\\Users\\hmoorthy\\test.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) {
    int i = 0;
    File currentDir = new File("C:\\Users\\hmoorthy\\workspace");
    displayDirectoryContents(currentDir,i);
}
public static int displayDirectoryContents(File dir,int i) {
    try {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("folder:" + file.getCanonicalPath()+"        "+i);
                //System.out.println("file          "+i);
                excelLog("Folder",file.getCanonicalPath(),i);
                i=i+1;
                i = displayDirectoryContents(file,i);
                //i=i+1;
            } else {
                System.out.println("file:" + file.getCanonicalPath()+"        "+i);
                excelLog("File ",file.getCanonicalPath(),i);
                i=i+1;
            }

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