I wanted to read contents of Excel files in my web-based project (J2EE-JSP+Servlets) which are located inside the web server's folder.
I have made a java file, which i will call through a JSP page using JSTL library, but I need to get the path of the Excel sheet in the Java file, so I can read the contents.
How can I get the path to the current Java file and so the Excel file?
Also, I will be reading the contents of the Excel file through POI library. I was able to do this in J2SE development, but is it possible here?
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());
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With