Java Export Excel由浏览器



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

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

我的控制器:

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

尝试以下内容:但是您为它apaches fileutil

@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,请连接到您的写入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;

您的按钮应该像这样

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

在服务器上,我会做这个

response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exceptions.xlsx")
response.flushBuffer();

使用javascript/jquery

查看下载文件

实际上,如果正确指定了标题,则应在单击给定的元素(在新的选项卡中(单击给定的元素(在新的选项卡中(下载的文件下载,以便在同一选项卡中启动下载。

我会建议使用这样的工具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();
                    }
                }
            );

相关内容

最新更新