0

I want to export Excel by browser. If I click the export button I can see information in Chrome network, but it did not download. I can download excel to my project folder, but how to export excel through the browser? Below the Ajax and controller codes.

This is my Excel util:

public class WriteExcel {

/**
 * @param answerList
 * @return
 */
public static void writeData(List<Answer> answerList, String paperName, HttpServletResponse response) throws IOException {

    Workbook workbook = new HSSFWorkbook();

    Sheet sheet = workbook.createSheet("test");
    for(int i=0; i<answerList.size();i++){
        Answer answer = answerList.get(i);
        Row row = sheet.createRow(i);
        Cell cell = row.createCell(0);
        cell.setCellValue(answer.getAnswerpname());
        List<AnswerReceive> answerReceives = JSON.parseArray(answer.getAnswerdata(), AnswerReceive.class);
        for(int j=0; j<answerReceives.size(); j++){
            AnswerReceive answerReceive = answerReceives.get(j);
            Cell tmp_cell = row.createCell(j+1);
            tmp_cell.setCellValue(answerReceive.getData());
        }
    }
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename="
            .concat(String.valueOf(URLEncoder.encode(paperName, "UTF-8"))));
    OutputStream out = response.getOutputStream();
    workbook.write(out);

}
}

My controller:

@PostMapping("/export")
@ResponseBody
public Object exportExcel(@RequestParam("paperId") String paperId, HttpServletResponse response) throws IOException {
    List<Answer> answerList = answerService.getData(paperId);
    WriteExcel.writeData(answerList, "test", response);
}

My Ajax:

$("button[name='export']").click(function () {
    $.ajax({
        url: "/export",
        type: "post",
        data: {"paperId":$(this).attr("data-paper-id")},
        success: function (data) {
            console.log(data.flag);
            console.log(data.Message);
        }
    })
})
ZF007
  • 3,708
  • 8
  • 29
  • 48
Noria_kita
  • 17
  • 1
  • 3

2 Answers2

0

you button should be somethin like this

<button target='_blank' href='/export'>

on server I would make this

response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exceptions.xlsx")

response.flushBuffer();

Look at Download File Using Javascript/jQuery

Actually, if your headers are specified correctly, your file download should be started after clicking given element with corresponding href (in new tab) below code for starting download in the same tab.

I would recomend to use tools like that http://jqueryfiledownload.apphb.com.

or through axios

axios.post("/yourUrl"
                , data,
                {responseType: 'blob'}
            ).then(function (response) {
                    let fileName = response.headers["content-disposition"].split("filename=")[1];
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE variant
                        window.navigator.msSaveOrOpenBlob(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
                            fileName);
                    } else {
                        const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', response.headers["content-disposition"].split("filename=")[1]); //you can set any name(without split)
                        document.body.appendChild(link);
                        link.click();
                    }
                }
            );
Alex
  • 3,923
  • 3
  • 25
  • 43
0

Try following: But you Apaches FileUtils for it

@PostMapping("/export", produdes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Object exportExcel(@RequestParam("paperId") String paperId, HttpServletResponse response) throws IOException {
    List<Answer> answerList = answerService.getData(paperId);
    InputStream excelFile = WriteExcel.writeData(answerList, "test", response);
    response.setHeader("Content-Disposition", "attachment; filename=Export" + LocalDate.now() + ".xlsx");
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    FileCopyUtils.copy(excelFile, response.getOutputStream());
    response.flushBuffer();

}

To create an Inputstream, attach to your writeData Funcion:

ByteArrayInputStream bais = null;
try {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  workbook.write(baos);
  baos.flush();

  byte[] buffer = baos.toByteArray();

  bais = new ByteArrayInputStream(buffer);
  baos.close();
} catch (IOException e) {
  e.printStackTrace();
}
  return bais;
Florian Kling
  • 145
  • 1
  • 10