我想在用戶調用這個方法時下載excel文件。文件正在下載成功,但這是在項目的classPath中創建另一個excel文件。任何人都可以幫助我避免這個classPath文件的創建。 在此先感謝。使用apache poi下載excel
@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();
}
}
對不起,我試過了上面的一個,但文件沒有找到異常結束。順便說一句,我使用的是Ubuntu。 – lakshmi
然後指定路徑如下/ home/usr/Filename並給出相同的路徑,而你正在下載文件名= –
不,它不工作相同的異常。無論如何要保持excel表單在會話中並從那裏下載? – lakshmi