如何将 excel 文件保存到 java 中的用户下载路径

How to save a excel file to users download path in java

在我的项目中,我将创建一个 ExcelWorkBook 并将一些数据写入该工作簿。 写完后想保存到用户下载路径,所以试了下面的代码:

XSSFWorkbook hwb=new XSSFWorkbook();  
XSSFSheet sheet =  hwb.createSheet("Exam Marks Entry");
//writing data to workbook

//then targeting users download path as follows
String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/"+mainDisplayDto.getClassName()+" "+mainDisplayDto.getExamName()+".xlsx");

FileOutputStream fileOut =  new FileOutputStream(file);  
hwb.write(fileOut);

以上代码仅在应用程序在本地时有效(将工作簿保存到下载路径),但在应用程序打开时无效 VPS.

当应用程序不在 运行 本地时,如何将其保存到用户系统下载文件夹?

我的问题也迎刃而解,如果把数据写到工作簿后,我可以在系统中打开excel文件,用户就可以随意保存了。

谁能帮我解决这个问题?

您可以在锚标记或按钮元素上使用 window.location.href="",当用户点击它时,您应该调用您的程序,其中响应 returns excel sheet 和用户下载文件夹中的下载。

例如: window.location.href="/downloadExcelMarks" 是 url 我指的是我的控制器。这会调用我的控制器,我将从我的控制器发送 excel 作为响应,如下所示:

XSSFWorkbook hwb=new XSSFWorkbook();
XSSFSheet sheet =  hwb.createSheet("Exam Marks Entry");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=marks.xlsx");
ServletOutputStream outStream = response.getOutputStream();
workbook.write(outStream); // Write workbook to response.
outStream.close();

我想你可以理解为浏览器属性将文件保存到下载位置。您可以将浏览器的默认下载位置设置为文件系统中的任何位置。您如何指定要存储在不同用户使用不同文件系统的用户系统中的响应。

我在@Jai Prakash 建议的帮助下解决了问题,并更改了我的 ajax 调用和一些 java 代码,请查看代码

ajax 调用:

      $(document).on("click","#downlodMarksSheet",function(event){
            var examCatId=$("#meExamMainEV").val();     
            var classId=$(".mainContainer #meClass").val();  
            var secId=$(".mainContainer #sectionId").val() ;
            var stringFromDate=$(".mainContainer #FromDate").val();
            var stringToDate=$(".mainContainer #ToDate").val();
            var url = contextPath+"/excel/exportExcel/"+classId+"/"+secId+"/"+examCatId+"/"+stringFromDate.replace(/\//g, "-")+"/"+stringToDate.replace(/\//g, "-");
            window.location.href=url;
        });

**java code :**

@GetMapping(value = "/exportExcel/{classId}/{secId}/{examCatId}/{stringFromDate}/{stringToDate}")
    public HttpServletResponse updateStudentGeneralDetailss(@PathVariable("classId") int classId,
            @PathVariable("secId") int secId,@PathVariable("examCatId") int examCatId,
            @PathVariable("stringFromDate") String stringFromDate,
            @PathVariable("stringToDate") String stringToDate,HttpServletRequest request,HttpServletResponse response) {

        try { 



            String filename="";
            XSSFWorkbook hwb=new XSSFWorkbook();  
            XSSFSheet sheet =  hwb.createSheet("Exam Marks Entry");  
            XSSFRow subsHead=   sheet.createRow(0);
            subsHead.createCell(1).setCellValue("");
            XSSFRow subSubsIdsHead=   sheet.createRow(1);
            XSSFRow subSubs=   sheet.createRow(2);



            response.setContentType("application/vnd.ms-excel");

            ServletOutputStream outStream = response.getOutputStream();


            XSSFColor myColor = new XSSFColor(Color.YELLOW);

            XSSFCellStyle style = hwb.createCellStyle();  
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());

            style.setBorderBottom(CellStyle.BORDER_THIN);
            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderLeft(CellStyle.BORDER_THIN);
            style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderRight(CellStyle.BORDER_THIN);
            style.setRightBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderTop(CellStyle.BORDER_THIN);
            style.setTopBorderColor(IndexedColors.BLACK.getIndex());  



                ExmaExportDTO mainDisplayDto  = service.getExamPartten(examCatId, classId, secId,stringFromDate.replaceAll("-", "/"),stringToDate.replaceAll("-", "/"));

            List<ExamStudentMarksDisplaySubjectsDTO> subjects=  mainDisplayDto.getSubjectsList();
            int i=2;
            int formCol=2;
            int subsubCol=2;

            sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
            sheet.addMergedRegion(new CellRangeAddress(1,1,0,1));

            Cell cel=subSubs.createCell(0); 
            cel.setCellStyle(style);  
            cel.setCellValue("Student Ids");

            Cell cel1=subSubs.createCell(1);
            cel1.setCellStyle(style);  
            cel1.setCellValue("Student Name");

            /*iterating subjects*/
            for(ExamStudentMarksDisplaySubjectsDTO subObj : subjects)
            {  
                Cell cell=subsHead.createCell(formCol);
                cell.setCellStyle(style);
                cell.setCellValue(subObj.getSubjectName());;
                List<ExamStudentMarksDisplaySubjectsSubCatDTO> subSubj=subObj.getSubCatMarks();

                int subSubjLen=subSubj.size(); 

                int toCol=formCol+subSubjLen;

                sheet.addMergedRegion(new CellRangeAddress(0,0,formCol,toCol-1));

                for(ExamStudentMarksDisplaySubjectsSubCatDTO subsubObj :subSubj)
                {
                    Cell cell1=subSubsIdsHead.createCell(subsubCol);
                    cell1.setCellStyle(style);
                    cell1.setCellValue(subsubObj.getExmSubjectSubCategory());
                    Cell cell2=subSubs.createCell(subsubCol);
                    cell2.setCellStyle(style);  
                    cell2.setCellValue(subsubObj.getSubCatName()+"("+subsubObj.getSubCatMaxMarks()+")");
                    subsubCol++;
                }

                formCol=subSubjLen+formCol;;  
                i++;        
            }
            Cell cella=subSubs.createCell(subsubCol);
            cella.setCellStyle(style);
            cella.setCellValue("Description");

            Cell cell1a=subSubs.createCell(subsubCol+1);
            cell1a.setCellStyle(style);
            cell1a.setCellValue("No.of Working Days");

            Cell cell2a=subSubs.createCell(subsubCol+2);
            cell2a.setCellStyle(style);
            cell2a.setCellValue("No.of Present Days");


            List<ExamStudentMarksDisplayStudentsDTO> students=mainDisplayDto.getStudentList();
            /*iterating students*/
            int j=3;
            for(ExamStudentMarksDisplayStudentsDTO stu : students)
            {
                XSSFRow rows=   sheet.createRow(j);
                Cell cell3=rows.createCell(0);
                cell3.setCellStyle(style);
                cell3.setCellValue(stu.getStudentId());
                String lastName="";
                if(stu.getLastMame() !=null)
                {
                    lastName=stu.getLastMame();
                }
                Cell cell4=rows.createCell(1);
                cell4.setCellStyle(style); 
                cell4.setCellValue(stu.getFirstName()+" "+lastName);
                j++;
            }  

            response.setHeader("Content-Disposition", "attachment; filename="+mainDisplayDto.getClassName()+""+mainDisplayDto.getExamName()+".xlsx");
            hwb.write(outStream);
            outStream.close();

        }
catch (Exception e) {  
    e.printStackTrace();
}
        return response;
    }

谢谢!