我希望在用户调用此方法时下载excel文件。文件正在下载成功,但这是在项目的classPath中创建另一个excel文件。任何人都可以帮我避免这个classPath文件的创建。 提前谢谢。
@Override
public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws IOException {
File file = new File("Segmentdetail.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("SegmentLogs Info");
spreadsheet.setDefaultColumnWidth(20);
.....Here is the logic for generating sheet which is quite big so iam skipping it.
}
FileOutputStream out = new FileOutputStream(file);
workbook.write(out);
downloadFile(file,response);
out.close();
workbook.close();
}
private void downloadFile(File file, HttpServletResponse response){
try {
response.setContentType("application/vnd.ms-excel");
response.addHeader("content-disposition", "attachment; filename=Segmentdetail.xlsx");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
final int size = 1024;
try {
response.setContentLength(fin.available());
final byte[] buffer = new byte[size];
ServletOutputStream outputStream = null;
outputStream = response.getOutputStream();
int length = 0;
while ((length = fin.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
fin.close();
outputStream.flush();
outputStream.close();
} catch (final IOException e) {
e.printStackTrace();
}
}catch (final Exception ex){
ex.printStackTrace();
}
}
答案 0 :(得分:1)
使用写入excel的文件的绝对路径:
File file = new File( "C:\\Segmentdetail.xlsx"); // windows
File file = new File("/home/usr/Segmentdetail.xlsx"); // unix
合理的补充是使用变量:
File file = new File(System.getenv("user.home"), "Segmentdetail.xlsx");
您当然可以定义自定义变量并使用它。
答案 1 :(得分:0)
因为您使用以下命令创建文件
File file = new File("Segmentdetail.xlsx");
它将在类路径
中生成文件在下载时更好地提供文件路径和相同的文件路径
File file = new File("c://Segmentdetail.xlsx");