0

I have a Jar file which has many excel sheets inside it. I want to access the excels sheets while running the Jar file and copy somewhere. How can I do that ?

O_K
  • 922
  • 9
  • 14

2 Answers2

0

You can access the Excel sheets as resources in the classpath:

Class.getResourceAsStream("/excelfiles/myfile.xlsx");

For reading Excel sheets in java you can use Apache POI library

If you only want to copy the files to an output folder (without understanding Excel, you can just read the resource as an InputStream and write it to a a FileOutputStream.

Conffusion
  • 4,335
  • 2
  • 16
  • 28
  • My problem is that there are 100s of excel file inside a folder with subfolders (say "excelFolder") and I need to get the names of all excel files .I can not hard code the excel file names. – O_K Oct 19 '20 at 16:25
  • This may help:https://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory to scan the resources in a folder of the classpath. – Conffusion Oct 19 '20 at 17:12
0

The issue is resolved. I used below code to access the excels inside jar and copy excels outside my Jar

public static void main(String[] args) throws IOException {
    final String classPath = "Path_Of_Jar/abc.jar";
    JarFile jarFile = new JarFile (classPath);

    String copyFolderExcel="Path to copy excels";
    File excelFolderFile = new File (copyFolderExcel);
    excelFolderFile.mkdir();

    Enumeration<JarEntry> e = jarFile.entries ();
    while (e.hasMoreElements ()) {
        JarEntry entry = (JarEntry) e.nextElement ();

        if (entry.getName ().contains ("excelFiles/")) {
            String name = entry.getName ();

            if(name.contains (".xlsx")) {
                copyExcel(jarFile,name,copyFolderExcel);

            }
      }
    }
jarFile.close ();
}

private static void copyExcel(JarFile jarFile, String file,String updatedFolder) throws IOException {


    String[] outputFileName = file.split ("/");
    String finalName = outputFileName[outputFileName.length-1];

    JarEntry entry = (JarEntry) jarFile.getEntry(file);
    InputStream input = jarFile.getInputStream(entry);
    OutputStream output = new FileOutputStream (updatedFolder+"/"+finalName);


    try {
        byte[] buffer = new byte[input.available ()];
        for (int i = 0; i != -1; i = input.read (buffer)) {
            output.write (buffer, 0, i);
        }
    } finally {

        input.close();
        output.close();
    }
}

}

O_K
  • 922
  • 9
  • 14