简体   繁体   English

Java通过浏览器导出Excel

[英]Java export Excel by browser

I want to export Excel by browser. 我想通过浏览器导出Excel。 If I click the export button I can see information in Chrome network, but it did not download. 如果单击导出按钮,我可以在Chrome网络中看到信息,但该信息没有下载。 I can download excel to my project folder, but how to export excel through the browser? 我可以将excel下载到项目文件夹中,但是如何通过浏览器导出excel? Below the Ajax and controller codes. 在Ajax和控制器代码下方。

This is my Excel util: 这是我的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);

}
}

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

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 查看使用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. 实际上,如果正确指定了标头,则应在具有相同href(在新选项卡中)下面的代码的给定元素(位于新选项卡中)下单击以开始下载文件后,再开始下载文件。

I would recomend to use tools like that http://jqueryfiledownload.apphb.com . 我建议使用像http://jqueryfiledownload.apphb.com这样的工具。

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

Try following: But you Apaches FileUtils for it 尝试以下操作:但是您为此使用了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();

}

To create an Inputstream, attach to your writeData Funcion: 要创建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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM