Apache POI is project by Apache Software Foundation. It provides the Java API for Microsoft Documents.
You can find more about apache POI . You can also download apache POI from here.
Here we are explaining how to export data from struts2 action to xml file.
For that we are using apache poi.
We have included following jar files in lib folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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; } |
In struts.xml
1 2 | attachment;filename=report.xlsapplication/vnd.ms-excelinputStream 1024 |
In jsp
1 | Download |