Java通过浏览器导出Excel

时间:2019-06-30 11:17:21

标签: java spring-boot

我想通过浏览器导出Excel。如果单击导出按钮,我可以在Chrome网络中看到信息,但该信息没有下载。我可以将excel下载到项目文件夹中,但是如何通过浏览器导出excel?在Ajax和控制器代码下方。

这是我的Excel实用程序:

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);

}
}

我的控制器:

@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);
}

我的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);
        }
    })
})

2 个答案:

答案 0 :(得分:0)

您的按钮应该像这样

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

在服务器上,我会做

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

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

response.flushBuffer();

Download File Using Javascript/jQuery

实际上,如果正确指定了标头,则应在相应标签下点击带有相应href(在新标签中)的给定元素后,开始下载文件。

我建议使用这样的工具 http://jqueryfiledownload.apphb.com

或通过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();
                    }
                }
            );

答案 1 :(得分:0)

尝试以下操作: 但是您为此使用了Apaches FileUtils

@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();

}

要创建Inputstream,请附加到您的writeData函数:

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;