Java 使用ApachePOI下载Excel
我希望在用户调用此方法时下载excel文件。文件下载成功,但正在project的类路径中创建另一个excel文件。有人能帮我避免创建这个类路径文件吗。 提前谢谢Java 使用ApachePOI下载Excel,java,excel,spring-boot,download,apache-poi,Java,Excel,Spring Boot,Download,Apache Poi,我希望在用户调用此方法时下载excel文件。文件下载成功,但正在project的类路径中创建另一个excel文件。有人能帮我避免创建这个类路径文件吗。 提前谢谢 @Override public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws IOException { File file = new File("Segmentdetail
@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();
}
}
因为您正在使用下面的命令创建文件
File file = new File("Segmentdetail.xlsx");
它将在类路径中生成文件
下载时最好给出文件路径和相同的文件路径
File file = new File("c://Segmentdetail.xlsx");
为要将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");
当然,您也可以定义一个自定义变量并使用它。对不起,我尝试了上面的一个变量,但最后出现了file not found异常。顺便说一句,我正在使用Ubuntu。然后指定路径如下/home/usr/Filename,并在下载时给出相同的路径,路径为Filename=No,它不工作,出现相同的异常。是否仍要将excel工作表保留在会话中并从那里下载?我不希望在本地计算机中创建该文件。它应该处于会话中并从那里下载。