Angular and Spring Boot Excel Export / Download

Hi Folks,

After a long I got some time to write new article. This article shows how to download or export data to excel file from Angular. The project stack is Angular 7 (PrimeNG) and Spring Boot. Let’s start with UI first –

In .html file declared a button to download the excel file

<div class="col-md-2">
     <p-button label="Extract & Download Excel" (onClick)="exportCampaign($event)" [disabled]="isShow" id="btnXlsRpt"></p-button>

After clicking on button the function exportCampaign from .js got called as below

exportCampaign($event) {
    this.blockedDocument = true;
    this.d = new Date();
    this.year = this.d.getFullYear();
    this.month = this.d.getMonth() + 1; = this.d.getDate();
   var result= this.mainService.exportCampaignData(this.obj.cmpNameToSearch);
   let fileName="Campaign-"+this.obj.cmpNameToSearch+"_" + "_" + this.month + "_" + this.year +".xlsx";
    (success: any) => {
      var blob = new Blob([success._body], { type: 'application/' });

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
        this.blockedDocument = false;
      } else {
        var a = document.createElement('a');
        a.href = URL.createObjectURL(blob); = fileName;
        this.blockedDocument = false;
    err => {
      alert("Error while downloading. File Not Found on the Server");
      this.blockedDocument = false;
  1. The call goes to Angular service method
    exportCampaignData(cName : String) {
    return’/api/cvs/exportExcel’, cName, this.options);

Before we jump to Spring side backend logic, we need to configure following pre-requisites
— include the following Apache POI dependency in pom.xml


  1. Then the call goes back to the Spring Controller class, notice the Return type of method is ResponseEntity
@RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
public ResponseEntity<?> exportExcel(HttpServletRequest request, HttpServletResponse response, @RequestBody String campaignName) throws Exception {
	XSSFWorkbook workbook = null;
	byte[] contentReturn=null;
	/* Here I got the object structure (pulling it from DAO layer) that I want to be export as part of Excel. */
		/* Logic to Export Excel */
		LocalDateTime localDate =;
		String fileName = "CampaignID-" + campaignName + "-" + localDate.toString() + ".xlsx";
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		OutputStream out;
workbook = (XSSFWorkbook) exportToFileService.exportToExcel(vehicleLastSeenByCampaignReport);
		out = response.getOutputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		contentReturn = baos.toByteArray();
		/* Export Excel logic end */
		} catch (Exception ecx) {
			VehicleLastSeenByCampaignReport vehicleCampaignReport = new VehicleLastSeenByCampaignReport();
			vehicleCampaignReport.setErrorMessage("Campaign Not Found");
			return new ResponseEntity<byte[]>(null, null, HttpStatus.BAD_REQUEST);
		}finally {
			if (null != workbook) {
				try {
				} catch (IOException eio) {
					logger.error("Error Occurred while exporting to XLS ", eio);
		HttpHeaders headers = new HttpHeaders();
		return new ResponseEntity<byte[]>(contentReturn, headers, HttpStatus.OK);

Call goes the service method i.e. export to excel

 public Object exportToExcel(VehicleLastSeenByCampaignReport vehicleLastSeenByCampaignReport) {
		String[] columns = setUpExcelColumns(CVSConstants.EXPORT_DATA_CMP);
		Workbook workbook = CVSUtils.writeExcelFile(vehicleLastSeenByCampaignReport, columns, summaryArray);
		return workbook;
  1. In following code I created a 2 sheets inside single excel file.
public static Workbook writeExcelFile(VehicleLastSeenByCampaignReport vehicleLastSeenByCampaignReport, String[] columns, String[] summaryColumns) {

		Workbook workbook = new XSSFWorkbook();
		int rowNum = 0;
		// Create a Font for styling header cells
		Font headerFont = setHeaderFont(workbook);

		// Create a CellStyle with the font
		CellStyle headerCellStyle = setHeaderCellStyle(workbook, headerFont);
		// Create a CellStyle for CampaignSummary mian object with Grey Color
		CellStyle styleGrey = workbook.createCellStyle();
		Sheet cmpSummarySheet = workbook.createSheet(CVSConstants.CMP_SUMMARY_SHEET);
		Sheet cmpDetailsSheet = workbook.createSheet(CVSConstants.CMP_DETAILS_SHEET);
		Row headerRowcmpSummary = cmpSummarySheet.createRow(0);
		Row headerRowCmpDetails = cmpDetailsSheet.createRow(0);
		applyHeaderCellStyle(Arrays.copyOfRange(summaryColumns, 0, (summaryColumns.length)), headerCellStyle, headerRowcmpSummary);
		applyHeaderCellStyle(Arrays.copyOfRange(columns, 0, (columns.length) ), headerCellStyle, headerRowCmpDetails);
		//Create the 'cmp summary sheet'
		defineCmpSummary(vehicleLastSeenByCampaignReport, rowNum, cmpSummarySheet, summaryColumns);
		//Create the 'cmp details sheet'
		defineCmpDetails(vehicleLastSeenByCampaignReport, rowNum, cmpDetailsSheet, columns, styleGrey);
		return workbook;
	private static void defineCmpSummary(VehicleLastSeenByCampaignReport vehicleLastSeenByCampaignReport, int rowNum, Sheet cmpSummarySheet, String[] summaryCols) {
		Row vehDetailsRow = cmpSummarySheet.createRow(++rowNum);
		CVSSummary cvsSummary = vehicleLastSeenByCampaignReport.getCvsSummary();
		int columnNum = 0;
		for (int i = 0; i < summaryCols.length; i++) {

Few important api used in code are

workbook => this is an important object that populates content of Excel file and return it to subsequent callers

autoSizeColumn => used to autoSize Columns width based on content of columns

That’s All Folks. Straight forward self explementary code. Do let me know in comments in case of any doubts.

9 thoughts on “Angular and Spring Boot Excel Export / Download

  1. return’/api/cvs/exportExcel’, cName, this.options);
    What is the value for this.options?
    we are getting exception due to this.


  2. Hi, backend is able to send the byte[] however angular front end is not able to read it. It throws an error at http.js line 1929 where it says, // Attempt the parse. If it fails, a parse error should be delivered to the user.
    body = body !== ” ? JSON.parse(body) : null;. Here, body is a random byte array character where the error is Unexpected token P in JSON at position 0.


  3. URL.createObjectURL() this method is deprecated and also removed from some browsers. Is there any alternative for this??


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s