Excel file download in Struts2 using apache POI

Apache POI is a project by Apache Software Foundation. It provides the Java API for Microsoft Documents.

You can find out more about Apache POI. You can also download apache POI from here.

how to save xls file in java struts2

Here we are explaining how to export data from struts2 action to an XML file.
For that, we are using apache poi.


We have included the following jar files in the lib folder

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;


public class ProductDetailsAction extends ActionSupport {
 private long barCode;//bardoce
 private long productName;
 private ArrayList productList;
 private InputStream inputStream;
 /getter and setter of all fields

public String Download()
{


               ProductDetailsAction pda=new ProductDetailsAction();
                pda.setBarCode(111);
                pda.setProductName("Lux");
                setProductList(pda);                
                pda.setBarCode(112);
                pda.setProductName("Liril");
                setProductList(pda);                
                pda.setBarCode(113);
                pda.setProductName("Hamam");
                setProductList(pda);
                HSSFWorkbook myWorkBook = new HSSFWorkbook();
                HSSFSheet mySheet = myWorkBook.createSheet();
                HSSFRow myRow = null;

                int rowNum = 1;
                Row header = mySheet.createRow(0);
                header.createCell(0).setCellValue("BARCODE");
                header.createCell(1).setCellValue("productName");
               
                 for (ProductDetailsAction s : getProductList()) {
                    myRow = mySheet.createRow(rowNum++);

                    Row dataRow = mySheet.createRow(rowNum++);
                    dataRow.createCell(0).setCellValue(s.getBarCode());
                    dataRow.createCell(1).setCellValue(s.getProductName());
                }
                try {

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    myWorkBook.write(baos);
                    setInputStream(new ByteArrayInputStream(boas.toByteArray()));
       
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return SUCCESS;
}

struts.xml file configuration to download xls file in java struts2

In struts.xml

   
attachment;filename=report.xlsapplication/vnd.ms-excelinputStream  
           1024
   

In jsp

 Download