// // 通过Response把数据以Excel格式保存
// response.reset();
// // 设置response流信息的头类型,MIME码
// response.setContentType("application/msexcel;charset=UTF-8");
// response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("塔租稽查统计有利数据", "utf-8"));
// response.addHeader("Content-Disposition", "attachment;filename=\"" + new
// String(("塔租稽查统计有利数据" + ".xls").getBytes("UTF-8"), "ISO8859_1") + "\"");
// // 创建输出流对象
// OutputStream out = response.getOutputStream();
// // 将创建的Excel对象利用二进制流的形式强制输出到客户端去
// workbook.write(out);
// // 强制将数据从内存中保存
// out.flush();
// out.close();
// String fileName = "塔租稽查统计有利数据";
// String fileName = URLEncoder.encode("塔租稽查统计有利数据.xlsx", "UTF-8");
// response.setHeader("Content-disposition","attachment; filename="+ fileName);
// response.setContentType("application/vnd.ms-excel");
// response.setCharacterEncoding("UTF-8");
// OutputStream out = response.getOutputStream();
// // 将创建的Excel对象利用二进制流的形式强制输出到客户端去
// workbook.write(out);
// // 强制将数据从内存中保存
// out.flush();
// out.close();
// String userAgent = request.getHeader("User-Agent");
// String formFileName = "塔租稽查统计有利数据.xls";
//
针对IE或者以IE为内核的浏览器:
// if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
// formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
// } else {
// // 非IE浏览器的处理:
// formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
// }
// response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", formFileName));
// response.setContentType("multipart/form-data");
// response.setCharacterEncoding("UTF-8");
// OutputStream out = response.getOutputStream();
// // 将创建的Excel对象利用二进制流的形式强制输出到客户端去
// workbook.write(out);
// // 强制将数据从内存中保存
// out.flush();
// out.close();
//post测试有问题浏览器没问题
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
try {
response.setHeader("content-disposition",
"attachment;filename=" + java.net.URLEncoder.encode("塔租稽查统计有利数据.xlsx", "UTF-8"));
} catch (UnsupportedEncodingException e) {
}
OutputStream out = response.getOutputStream();
// 将创建的Excel对象利用二进制流的形式强制输出到客户端去
workbook.write(out);
// 强制将数据从内存中保存
out.flush();
out.close();
//post测试没有问题浏览器有问题
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
//
// try {
//
// response.setHeader("content-disposition",
//
// "attachment;filename=" + java.net.URLEncoder.encode("塔租稽查统计有利数据.xls", "UTF-8")
//
// + ";filename*=utf-8''" + java.net.URLEncoder.encode("塔租稽查统计有利数据.xls", "UTF-8"));
//
// } catch (UnsupportedEncodingException e) {
// }
// OutputStream out = response.getOutputStream();
// // 将创建的Excel对象利用二进制流的形式强制输出到客户端去
// workbook.write(out);
// // 强制将数据从内存中保存
// out.flush();
// out.close();
导出Excel 多方法
最新推荐文章于 2024-09-05 14:40:56 发布
这段代码展示了如何在Java后端通过HTTP响应将数据以Excel格式发送给客户端。它涉及到设置正确的MIME类型,处理文件名编码以支持不同浏览器,以及使用OutputStream将工作簿对象写入输出流。代码中处理了IE和非IE浏览器的文件名编码差异,以及对POST请求的兼容性问题。
摘要由CSDN通过智能技术生成