我有一个表单,它接受PDF
文件并提交给servlet。在阅读PDF的内容后,我正在使用Apache POI在servlet中创建一个xls文件,我想将其保存到本地光盘。
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Data");
ArrayList<String> keys = new ArrayList<String>(excelData.keySet());
int counter = 0;
for(int i=keys.size()-1; i>=0;i--){
String key = keys.get(i);
String value = excelData.get(key);
Row row = sheet.createRow(counter++);
Cell cell = row.createCell(0);
cell.setCellValue(key);
Cell cell1 = row.createCell(1);
cell1.setCellValue(value);
}
//工作簿是我目前正在保存的xls数据,
FileOutputStream out = new FileOutputStream(new File("C:\\Users\\user\\Desktop\\new.xls"));
workbook.write(out);
out.close();
//return back to same page.
response.sendRedirect(request.getHeader("Referer"));
我想提供一个C:\\Users\\user\\Desktop\\new.xls
选项来选择用户想要保存的文件的路径和名称,而不是直接将文件保存到save as
。有点像:
如何将此文件发送回客户端浏览器并显示另存为选项。
答案 0 :(得分:0)
//read file back after saving to some temp path.
File pdfFile = new File("D:\\temp\\"+ fileName +".xls");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".xls");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
fileInputStream.close();