Wednesday 5 August 2015

Spring RestFul Web service with Excel File response using JExcel API and Apache POI

JExcelApi is a Java library that is dedicated for reading, writing and modifying Excel spreadsheets. It supports Excel 2003 file format and older versions. You can download JExcelApi from the following link:

To work with JExcelApi, you need to add its only jar file: jxl.jar - to your project’s classpath. Download JExcel

Here we are going to create spring API to download Excel file as response using JExcel Api.





import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.demo.api.exl.services.ExcelOutputService;

@RestController
@RequestMapping(value="/exceloutput")
public class ExcelOutputServiceController {

    @Autowired
    ExcelOutputService excelOutputService;
   
    @RequestMapping(value="/download", method=RequestMethod.GET)
    public ModelAndView downloadExcelOutputExl(HttpServletResponse response){
      
       excelOutputService.createExcelOutputExcel(response);
       return null;
    }
}



import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("excelOutputService")
public class ExcelOutputServiceImpl implements ExcelOutputService{
    private static final Logger LOGGER = Logger.getLogger(ExcelOutputServiceImpl.class);
   
    @Override
    public WritableWorkbook createExcelOutputExcel(HttpServletResponse response) {
       String fileName = "Excel_Output.xls";
       WritableWorkbook writableWorkbook = null;
       try {
           response.setContentType("application/vnd.ms-excel");

           response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

           writableWorkbook = Workbook.createWorkbook(response.getOutputStream());
          
           WritableSheet excelOutputsheet = writableWorkbook.createSheet("Excel Output", 0);
           addExcelOutputHeader(excelOutputsheet);
           writeExcelOutputData(excelOutputsheet);
           
           writableWorkbook.write();
           writableWorkbook.close();

       } catch (Exception e) {
           LOGGER.error("Error occured while creating Excel file", e);
       }

       return writableWorkbook;
    }

   
    private void addExcelOutputHeader(WritableSheet sheet) throws RowsExceededException, WriteException{
       // create header row
        sheet.addCell(new Label(0, 0, "Column 1"));
        sheet.addCell(new Label(1, 0, " Column 2"));
        sheet.addCell(new Label(2, 0, " Column 3"));
        sheet.addCell(new Label(3, 0, " Column 4"));
        sheet.addCell(new Label(4, 0, " Column 5"));
        sheet.addCell(new Label(5, 0, " Column 6"));
        sheet.addCell(new Label(6, 0, " Column 7"));
        sheet.addCell(new Label(7, 0, " Column 8"));
        sheet.addCell(new Label(8, 0, " Column 9"));
        sheet.addCell(new Label(9, 0, " Column 10"));
        sheet.addCell(new Label(10, 0, " Column 11"));
    }
   
    private void writeExcelOutputData(WritableSheet sheet) throws RowsExceededException, WriteException{
             
       for(int rowNo = 1; rowNo<=10; rowNo++){
              sheet.addCell(new Label(0, rowNo, “Col Data ”+ (rowNo+0)));
              sheet.addCell(new Label(1, rowNo, “Col Data ”+ (rowNo+1)));
              sheet.addCell(new Label(2, rowNo, “Col Data ”+ (rowNo+2)));
              sheet.addCell(new Label(3, rowNo, “Col Data ”+ (rowNo+3)));
              sheet.addCell(new Label(4, rowNo, “Col Data ”+ (rowNo+4)));
              sheet.addCell(new Label(5, rowNo, “Col Data ”+ (rowNo+5)));
              sheet.addCell(new Label(6, rowNo, “Col Data ”+ (rowNo+6)));  
              sheet.addCell(new Label(7, rowNo, “Col Data ”+ (rowNo+7)));
              sheet.addCell(new Label(8, rowNo, “Col Data ”+ (rowNo+8)));
              sheet.addCell(new Label(9, rowNo, “Col Data ”+ (rowNo+9)));
              sheet.addCell(new Label(10, rowNo, “Col Data ”+ (rowNo+10)));

       }

    }
}


Now call the service as :
http://localhost:8080/demo/excelOutputService/download
This will download the Excel file to download folder or show download popup window.







Create Excel using Apache POI
POI-XSSF - Java API To Access Microsoft Excel Format Files
Apache POI is a popular API that allows programmers to create, modify, and display MS Office files using Java programs.
XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.

Prerequisites

·                  DK1.5 or later versions

·                  Apache POI library (http://poi.apache.org/download.html ) 

Add following library to classpath:

“C:\poi-3.9\poi-3.9-20121203.jar;”
“C:\poi-3.9\poi-ooxml-3.9-20121203.jar;”
“C:\poi-3.9\poi-ooxml-schemas-3.9-20121203.jar;”
“C:\poi-3.9\ooxml-lib\dom4j-1.6.1.jar;”
“C:\poi-3.9\ooxml-lib\xmlbeans-2.3.0.jar;.;”



import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public XSSFWorkbook createExcelOutputFile(){
XSSFWorkbook workbook = null;
    try {          
           
        ClassLoader loader = getClass().getClassLoader();
File file = new File(loader.getResource("Excel_Output.xlsx").getFile());  //file should be at classpath
        FileInputStream is = new FileInputStream(file);
           
        // Get the workbook instance for XLSX file
        workbook = new XSSFWorkbook(is);
XSSFSheet rankerSheet1 = workbook.getSheetAt(0);

        writeExcelOutputData(rankerSheet1, workbook);         

        is.close();
           
    } catch (FileNotFoundException e) {
            LOGGER.error(e);
   } catch (IOException e) {
            LOGGER.error(e);
   }
        return workbook;
}

private void writeExcelOutputData(XSSFSheet rankerSheet, XSSFWorkbook worksheet){
           
            XSSFRow row1 = rankerSheet.createRow(1);
            row1.createCell(0).setCellValue(1);
            row1.createCell(1).setCellValue(1234
            row1.createCell(2).setCellValue(“Test Excel”);
            row1.createCell(3).setCellValue(“Address”);
           
            XSSFCell cell4 = row1.createCell(4);
               cell4.setCellValue(10.00);
            XSSFCellStyle style = worksheet.createCellStyle();
            style.setDataFormat((short)8);      // this will format cell with $ sign Ex: $10.00
            cell4.setCellStyle(style);  
           
           
          //Creating Data format %
            XSSFCellStyle percentStyle = worksheet.createCellStyle();
            percentStyle.setDataFormat(worksheet.createDataFormat().getFormat("0.0%"));
           
            XSSFCell cell5 = row1.createCell(5);
            cell5.setCellStyle(percentStyle);      
            cell5.setCellValue(20.00);   

    }

49 comments:

  1. Give a Complete flow with excel / pdf / image UPLOAD with Spring REST.

    ReplyDelete
  2. Ashis,
    you can follow the link http://simplejava2.blogspot.in/2016/06/image-uplaod-using-spring-restful.html
    for upload a file using spring freamework.

    ReplyDelete
  3. Hi Can you Please Share the Following Code Base (ie Using Apche POI)

    ReplyDelete
  4. Hi Can you Please Share the Following Code Base (ie Using Apche POI)

    ReplyDelete
  5. Hi, Could you please share me example to export jsp table into pdf,excel using spring rest service

    ReplyDelete
  6. It is better to engaged ourselves in activities we like. I liked the post. Thanks for sharing.
    Selenium training in Chennai

    Selenium training in Bangalore

    ReplyDelete
  7. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    Devops Training in Bangalore
    Microsoft azure training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  8. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing..
    Believe me I did wrote an post about tutorials for beginners with reference of your blog. 




    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  9. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    Data Science Training in Indira nagar
    Data Science Training in btm layout
    Data Science Training in Kalyan nagar
    Data Science training in Indira nagar
    Data science training in bangalore

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. I think you need to put forward a good amount of informative and descriptive article for learning every tact of REST API.

    Power BI Read Rest

    ReplyDelete
  13. Informative post indeed, I’ve being in and out reading posts regularly and I see alot of engaging people sharing things and majority of the shared information is very valuable and so, here’s my fine read.
    click here for registration
    click here full resolution
    click here for result
    click here for b.pharmacy examinations results
    click here for udyog aadhaar registration certificate

    ReplyDelete
  14. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Salesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Online Training | Salesforce Training

    ReplyDelete
  15. This post is so interactive and informative.keep update more information...
    RPA Training in Tambaram
    RPA Training in Chennai

    ReplyDelete
  16. This post is so interactive and informative.keep update more information…
    SEO Training in Anna Nagar
    SEO Training in Chennai

    ReplyDelete
  17. href="https://istanbulolala.biz/">https://istanbulolala.biz/
    8ZT

    ReplyDelete