tags:

views:

3162

answers:

5

I wanted to read contents excel files in my web-based project(J2EE-JSP+Servlets) which are located inside the web server's folder..

So, I have made a java file, which i will call through a JSP page using JSTL library.

I need to have the path of excel sheet in that java file, so that i can read the contents of that excel sheet. The excel sheet is located in web server's folder..

Also, i will be reading the contents of excel file through POI library,, i was able to achieve this in J2SE development, is it possible here?? Sample code below--

so, with which method, i will be able to retrieve the path for the same..


Code:

POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream("**some path here of sheet**"));
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook(fs);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell1,cell2,cell3; 

        int rows; // No of rows, stores the no. of rows for an excel sheet
        int cols; // No of columns, stores the no. of columns for an excel sheet

        rows = sheet.getPhysicalNumberOfRows();
        cols = 5;

        for(int r = 0; r < rows; r++) {
            row = sheet.getRow(r);

            if(row != null) {
                cell1 = row.getCell(1);
                cell2 = row.getCell(2);
                cell3 = row.getCell(4);

                //System.out.println(cell1.getStringCellValue()+" "+cell2.getStringCellValue()+" "+cell3.getStringCellValue());                
            }
        }
A: 

You can ask servlet context to translate relative to real path:

context.getRealPath("/");

If you java class is servlet, you can probably do something like

getServletConfig().getServletContext();

otherwise, jsp page is a servlet, so you can pass it from there.

Finally, you can pick it up once when you start your app:

public class AppStartup implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent event) {
    }

    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        // remember it in some static class for future use
    }
}

Having said all this, it's probably better to make a servlet that has his servlet context, resolve path, and call your class with resolved path to a file, then finally forward request to a jsp page to display results.

Slartibartfast
how can i do this in my java file,, do i need to import some library to this.. and it is not a servlet basically, i have not used any library for servlet in this file.. It is just a java file.. which i have created,, and i will call this file through JSP-JSTL library..
AGeek
sir, can you give me the complete coding of this, with necessary libraries which i need to import, with some explanation.. as i am new to servlets,, and i have no idea, what's your program doing.. and how i can incorporate that in my java code..
AGeek
ok, can you give me some online tutorial wherein i can read all those things which you have mentioned in your program..
AGeek
A: 

I suspect if you're looking for the local filesystem path on the server it may not be possible. Although some web application servers (notably Tomcat, I think) do have a folder containing all of your app's files, there are others that run apps directly from a compressed WAR file. In this case there may not be a path to your Excel file as it would be inside an archive.

One possible way around this that's independent of the application server you're running on would be to package the Excel file inside one of the JARs in WEB-INF/lib, and then read it using

getClass().getResourceAsStream("/class/path/to/file.xls")

instead of

new FileInputStream("/local/filesystem/path/file.xls")

When using getResourceAsStream("...") you need to supply a class path, rather than a filesystem path. So, if you packaged the Excel file inside a JAR, in a package called com.yourcompany.files, you'd need to use

getClass().getResourceAsStream("/com/yourcompany/files/file.xls")
Martin McNulty
fs = new POIFSFileSystem(getClass().getResourceAsStream("usr/local/shared/tomcat/localhost/webapps/foldername/filename.xls"));I have used this path, this is also return null values exception..what path i need to insert in getClass().getResourceAsStream("/path/to/excel/file/inside/jar/file.xls") so that i can read the file located on servers folder
AGeek
Have edited answer to try and clarify a bit... HTH
Martin McNulty
A: 

In a basic JSP/Servlet app you'd have a backing servlet which will do almost all the logic in your program, push the model into a request and then redirect the user to a JSP page that will pull the model from the request and will only format it (by using JSTL if you want). If your method needs to perform some kind of processing using the Excel file it should be inside a class extending javax.servlet.http.HttpServlet this way you could access the ServletContext and its method

String physicalFolder = getContext().getRealPath("/");

If you don't want to follow this approach and want to still JSTL (I guess you're using <jsp:useBean /> tag) you may initialize a bean property setting the physical folder of your webapp using something like this:

<jsp:useBean id="excelBean" scope="request" class="yourpackage.YourClass" >
    <jsp:setProperty name="physicalPath" value="<%= application.getRealPath("/") %>" />
</jsp:useBean>
victor hugo
class=some.ExcelBean--- what is this...
AGeek
it is saying an error-- mandatory attribute property missing..
AGeek
also, how can i request the path then from this bean in my java file..
AGeek
POIFSFileSystem fs = null; try { fs = new POIFSFileSystem(getClass().getResourceAsStream("path of excel file here")); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } what should i write here,, inorder to recieve the path from jsp file..
AGeek
org.apache.jasper.JasperException: /admin/upload-excel-files_action.jsp(12,0) The value for the useBean class attribute yourpackage.YourClass is invalid. I have put the appropriately yourpackage and yourclass but it is showing this error. please review...
AGeek
yourpackage and YourClass is an example if your class has no package and it's called ReadExcel you should've put just "ReadExcel"..... hmmm leaving here
victor hugo
A: 

This is the wrong approach.

You should be reading that file by putting it in WEB-INF/classes and using getResourceAsStream to get the InputStream from the context path using the file name.

Try looking at this example.

duffymo
can you give me a small example sir,, how to read the excel file using getResourceAsStream..
AGeek
The example was posted by Martin McNulty!!!!
victor hugo
Yes, I wrote my response before loading his answer. Martin has the straight dope for you.
duffymo
Sir, i am not able to understand ur codes.. plz either provide any online tutorial to my problm or plz give some detailed explanation..
AGeek
A: 

I second duffymo and Martin McNulty, you must use getResourceAsStream and put your Excel file, here it goes the example:

Your webapp structure is something like this, right?

- Application Root
 |
 +- WEB-INF
     |
     +- classes/  <--- This is added to CLASSPATH
     |
     +- lib/      <--- Its contents are added to CLASSPATH
     |
     +- web.xml

In this structure your application classpath is conformed by the JAR files located into lib folder and the classes folder. When you compile using an IDE the files located in your source folder are compiled and the .class files are copied in the classes folder, if the files are not Java files they're just copied in the folder, but still are in the classpath.

So, being briefly... You can add not-class files in the classpath, like your Excel file and organise it into packages just like it'd be a class.

If you put the Excel file in the classpath you'll have the advantage that the file can be accessed independently of your JAR file or WAR file location, just by knowing its location in the classpath.

The method Class.getResourceAsStream(String path) provides you access to files into the classpath, just pass the path replacing the dots by slashes, for example:

getClass().getResourceAsStream("/yourpackage/YourExcelFile.xsl");

will provide you an InputStream of the file YourExcelFile.xsl that is inside the package yourpackage.

I tried my best to explain you this but if you have doubts you can check the method documentation.

victor hugo
Why is this downvoted?
victor hugo