Search code examples
excelspringimportstruts2struts

Importing data from .xls and .xlsx (Struts and Spring)


I am doing a excel data import and reading through the file. The file format can be .xls or .xlsx. I have seen the different methods for doing so with both files.

For .xls,

HSSFWorkbook workbook = new HSSFWorkbook(file);

........;

and for .xlsx

XSSFWorkbook workbook = new XSSFWorkbook (file);

......;

But this looks like an extra work, writing different methods for different file formats. If we write in different methods, almost all the code will be same, except the file format checking at the beginning. I'm doing the excel importing using Apache POI.

Is there a way for doing both file formats in a single method? Such as in a single method do the same for both .xls and .xlsx file data importing and validation.

I am not expecting the whole code or something(which I wont get), but the idea to get it done in a single method.


Solution

  • I have figured out the solution.

    We can make use of XSSFWorkbook in this scenario. It can handle bothxls and .xlsx formats of excel file.

                  FileInputStream path= new FileInputStream(fileName);
    
                  Workbook workbook = null;
                  if(fileName.toLowerCase().endsWith("xlsx"))
                  {
                        workbook = new XSSFWorkbook(path);
                   }else if(fileName.toLowerCase().endsWith("xls"))
                  {
                        workbook = new HSSFWorkbook(path);
                    }
    

    And the rest of the operations can be carried out after this.

    There is a tutorial given in the WEBSITE for carrying out the same operation.

    Happy Learning.